Esempio n. 1
0
    def recup_nfs_sst_seviri_recent(self, URL_SEVIRI_DATA, YYYY, MM, DD, timerange):
        """ Recuperation par NFS d un fichier de SST SEVIRI horaire recent (depuis 01/01/2012)"""
        import os, subprocess, shutil
        import cdtime, glob
        from vacumm.misc.atime import strftime

        # -- Complement du nom de repertoire avec l'annee et le jour relatif (001-> 365)
        DATA_DIR = os.path.join(URL_SEVIRI_DATA, str(YYYY))
        # print DATA_DIR
        a = cdtime.comptime(YYYY, MM, DD)
        a2 = a.torel("days since " + strftime("%Y-%m-%d", cdtime.comptime(YYYY - 1, 12, 31)))

        DATA_DIR = os.path.join(DATA_DIR, "%(#)03d" % {"#": a2.value})

        # print DATA_DIR
        if timerange == "midnight":
            filename = "%(#)04d%(##)02d%(####)02d00*" % {"#": YYYY, "##": MM, "####": DD}
        else:
            filename = "%(#)04d%(##)02d%(####)02d*" % {"#": YYYY, "##": MM, "####": DD}
        copy_mode = "nfs"
        list_file = glob.glob(os.path.join(DATA_DIR, filename))
        # si la liste est vide, on essaie en se connectant a service7
        if not list_file:
            find_cmd = "ssh service7 \"find %(DATA_DIR)s -name '%(filename)s' \"" % vars()
            list_file = subprocess.check_output(find_cmd, shell=True).strip().split()
            if list_file:
                copy_mode = "scp"

        for file_to_read in list_file:
            if os.path.isfile(os.path.basename(file_to_read)) == False:
                if copy_mode == "nfs":
                    shutil.copyfile(file_to_read, os.path.basename(file_to_read))
                if copy_mode == "scp":
                    copy_cmd = "scp caparmor-sftp.ifremer.fr:%(file_to_read)s ." % vars()
                    subprocess.check_call(copy_cmd, shell=True)
Esempio n. 2
0
    def recup_ftp_sst_seviri_recent(self, URL_CERSAT, DATA_DIR, YYYY, MM, DD, ext, usr, pwd, ntry, timerange):
        """ Recuperation par FTP d un fichier de SST SEVIRI horaire recent (depuis 01/01/2012)"""
        import os, subprocess
        from ftplib import FTP
        import cdtime
        from vacumm.misc.atime import strftime

        # --------------- LE FTP FONCTIONNE MAIS LES FICHIERS SEMBLENT CORROMPUS ... PROBLEME DANS LE BZ2
        # -- Complement du nom de repertoire avec l'annee et le jour relatif (001-> 365)
        DATA_DIR = os.path.join(DATA_DIR, str(YYYY))
        print DATA_DIR
        a = cdtime.comptime(YYYY, MM, DD)
        a2 = a.torel("days since " + strftime("%Y-%m-%d", cdtime.comptime(YYYY - 1, 12, 31)))

        DATA_DIR = os.path.join(DATA_DIR, "%(#)03d" % {"#": a2.value})

        print DATA_DIR

        # connection au CDOCO
        ftp = FTP(host=URL_CERSAT, user=usr, passwd=pwd)

        # positionnement sur le repertoire "best_estimate"
        ftp.cwd(DATA_DIR)

        # utile pour ftp.retrbinary
        def handleDownload(block):
            file.write(block)

        if timerange == "midnight":
            filename = "%(#)04d%(##)02d%(####)02d00*" % {"#": YYYY, "##": MM, "####": DD}
        else:
            filename = "%(#)04d%(##)02d%(####)02d*" % {"#": YYYY, "##": MM, "####": DD}
            # print filename

        list_file = ftp.nlst(filename)
        # print list_file

        for file_to_read in list_file:
            # recuperation fichier si non present dans work/MODEL/MARS
            if os.path.isfile(file_to_read) == False:
                # rajouter test sur date du fichier ... telecharge que si plus recent ...

                file = open(file_to_read, "wb")

                ftp.retrbinary("RETR " + file_to_read, handleDownload)

                subprocess.call(["bunzip2", "-f", file_to_read])

            else:
                print "Pas de downloading : %(file_to_read)s existe deja" % vars()

        ftp.quit()
Esempio n. 3
0
    def recup_nfs_sst_seviri_recent(self, URL_SEVIRI_DATA, YYYY, MM, DD,
                                    timerange):
        """ Recuperation par NFS d un fichier de SST SEVIRI horaire recent (depuis 01/01/2012)"""
        import os, subprocess, shutil
        import cdtime, glob
        from vacumm.misc.atime import strftime

        # -- Complement du nom de repertoire avec l'annee et le jour relatif (001-> 365)
        DATA_DIR = os.path.join(URL_SEVIRI_DATA, str(YYYY))
        #print DATA_DIR
        a = cdtime.comptime(YYYY, MM, DD)
        a2 = a.torel('days since ' +
                     strftime('%Y-%m-%d', cdtime.comptime(YYYY - 1, 12, 31)))

        DATA_DIR = os.path.join(DATA_DIR, '%(#)03d' % {'#': a2.value})

        #print DATA_DIR
        if timerange == 'midnight':
            filename = '%(#)04d%(##)02d%(####)02d00*' % {
                '#': YYYY,
                '##': MM,
                '####': DD
            }
        else:
            filename = '%(#)04d%(##)02d%(####)02d*' % {
                '#': YYYY,
                '##': MM,
                '####': DD
            }
        copy_mode = 'nfs'
        list_file = glob.glob(os.path.join(DATA_DIR, filename))
        # si la liste est vide, on essaie en se connectant a service7
        if not list_file:
            find_cmd = 'ssh service7 "find %(DATA_DIR)s -name \'%(filename)s\' "' % vars(
            )
            list_file = subprocess.check_output(find_cmd,
                                                shell=True).strip().split()
            if list_file:
                copy_mode = 'scp'

        for file_to_read in list_file:
            if os.path.isfile(os.path.basename(file_to_read)) == False:
                if copy_mode == 'nfs':
                    shutil.copyfile(file_to_read,
                                    os.path.basename(file_to_read))
                if copy_mode == 'scp':
                    copy_cmd = 'scp caparmor-sftp.ifremer.fr:%(file_to_read)s .' % vars(
                    )
                    subprocess.check_call(copy_cmd, shell=True)
Esempio n. 4
0
def _extrema_var_(extrem,units=None,indices=False,**kwargs):
    ctime,var,idx = zip(*extrem)
    if indices:
        mytime = cdms2.createAxis(idx)
        mytime.id = 'time_index'
        mytime.long_name = 'Time index'
    else:
        if units is None:
            units = 'minutes since %s'%strftime('%Y-%m-%d %H:%M:%S',ctime[0])
        mytime = create_time(list(ctime), units)
    var = cdms2.createVariable(var,copy=0)
    var.setMissing(1.e20)
    var.setAxis(0,mytime)
    for att,val in kwargs.items():
        setattr(var,att,val)
    return var
Esempio n. 5
0
def _extrema_var_(extrem, units=None, indices=False, **kwargs):
    ctime, var, idx = zip(*extrem)
    if indices:
        mytime = cdms2.createAxis(idx)
        mytime.id = 'time_index'
        mytime.long_name = 'Time index'
    else:
        if units is None:
            units = 'minutes since %s' % strftime('%Y-%m-%d %H:%M:%S',
                                                  ctime[0])
        mytime = create_time(list(ctime), units)
    var = cdms2.createVariable(var, copy=0)
    var.setMissing(1.e20)
    var.setAxis(0, mytime)
    for att, val in kwargs.items():
        setattr(var, att, val)
    return var
Esempio n. 6
0
    P.figure()
    mod = MV2.sqrt(u10**2 + v10**2)
    levels = auto_scale(mod, nmax=10, vmin=0., vmax=10.)
    kwarg = dict(m=m,
                 lon=(milo, malo),
                 lat=(mila, mala),
                 nofill=True,
                 quiverkey_value=2,
                 quiver_scale=35,
                 quiver_norm=3,
                 contour=False,
                 quiver_alpha=.9,
                 quiver_width=7.,
                 title='Wind - ' + strftime(
                     '%d/%m/%Y - %H:%M:%S',
                     cdtime.reltime(u10.getTime().getValue()[it],
                                    u10.getTime().units).tocomp()),
                 show=False,
                 levels=levels,
                 colorbar_shrink=.7,
                 right=1,
                 quiver_samp=1,
                 cmap='cmap_jete')
    # => Practice : change map parameters.

    print strftime(
        '%d/%m/%Y - %H:%M:%S',
        cdtime.reltime(u10.getTime().getValue()[it],
                       u10.getTime().units).tocomp())

    m = map((u10[it, 0, :, :], v10[it, 0, :, :]), **kwarg)
Esempio n. 7
0
        id='VZ',
        axes=axes,
        attributes=dict(long_name='3d meridional velocity',
                        standard_name='northward_sea_water_velocity',
                        units='m.s-1',
                        valid_min='-100.',
                        valid_max='100.'))

    for iz, dep in enumerate(U.getLevel()):
        Ui2 = interp2d(U[0, iz, :, :], (xo, yo), method='bilinear')
        Vi2 = interp2d(V[0, iz, :, :], (xo, yo), method='bilinear')

        Uis[iz, :, :] = Ui2
        Vis[iz, :, :] = Vi2

    date = strftime('_%Y%m%d%H0000', c1)
    file_out = 'MARS_MENOR_' + date + '.nc'
    f = cdms2.open(os.path.join(dir_model, file_out), 'w')
    #f.write(LATITUDE)
    #f.write(LONGITUDE)
    #f.write(TIME)
    #f.write(DEPTH)

    f.write(Uis)  # ecriture d'une variable
    f.write(Vis)
    f.history = 'Created with ' + __file__.encode('utf8')  # attribut global
    f.close()  # fermeture

    del Uis, Vis

    ctest = c2
Esempio n. 8
0
    def recup_ftp_sst_seviri_recent(self, URL_CERSAT, DATA_DIR, YYYY, MM, DD,
                                    ext, usr, pwd, ntry, timerange):
        """ Recuperation par FTP d un fichier de SST SEVIRI horaire recent (depuis 01/01/2012)"""
        import os, subprocess
        from ftplib import FTP
        import cdtime
        from vacumm.misc.atime import strftime

        # --------------- LE FTP FONCTIONNE MAIS LES FICHIERS SEMBLENT CORROMPUS ... PROBLEME DANS LE BZ2
        # -- Complement du nom de repertoire avec l'annee et le jour relatif (001-> 365)
        DATA_DIR = os.path.join(DATA_DIR, str(YYYY))
        print DATA_DIR
        a = cdtime.comptime(YYYY, MM, DD)
        a2 = a.torel('days since ' +
                     strftime('%Y-%m-%d', cdtime.comptime(YYYY - 1, 12, 31)))

        DATA_DIR = os.path.join(DATA_DIR, '%(#)03d' % {'#': a2.value})

        print DATA_DIR

        # connection au CDOCO
        ftp = FTP(host=URL_CERSAT, user=usr, passwd=pwd)

        # positionnement sur le repertoire "best_estimate"
        ftp.cwd(DATA_DIR)

        # utile pour ftp.retrbinary
        def handleDownload(block):
            file.write(block)

        if timerange == 'midnight':
            filename = '%(#)04d%(##)02d%(####)02d00*' % {
                '#': YYYY,
                '##': MM,
                '####': DD
            }
        else:
            filename = '%(#)04d%(##)02d%(####)02d*' % {
                '#': YYYY,
                '##': MM,
                '####': DD
            }
    #print filename

        list_file = ftp.nlst(filename)
        #print list_file

        for file_to_read in list_file:
            # recuperation fichier si non present dans work/MODEL/MARS
            if os.path.isfile(file_to_read) == False:
                # rajouter test sur date du fichier ... telecharge que si plus recent ...

                file = open(file_to_read, 'wb')

                ftp.retrbinary('RETR ' + file_to_read, handleDownload)

                subprocess.call(["bunzip2", "-f", file_to_read])

            else:
                print "Pas de downloading : %(file_to_read)s existe deja" % vars(
                )

        ftp.quit()
Esempio n. 9
0
from vacumm.misc.atime import strftime,strptime

# Lecture a partir d'une chaine de caracteres et d'un format
# (tappez strptime dans google)
mytime = strptime('1950-01-01 07:00:00','%Y-%m-%d %H:%M:%S')
# Verification partielle
print mytime.year,mytime.minute
# -> 1950 0

# On choisit la langue francaise 
import locale
locale.setlocale(locale.LC_ALL,'fr_FR')

# Ecriture sous un autre format
print strftime('%e %B %Y a %Hh%M',mytime)
# ->  1 janvier 1950 a 07h00
Esempio n. 10
0
         xlkw.update(pmap=False, cur_color='b', cur_linestyle='', cur_marker='o')
         try: cur, var, lat, lon = sat.plot_extrema_location(**xlkw)
         except: log.exception('Cannot plot satellite')
         
         xlkw.update(pmap=False, cur_color='g', cur_linestyle='-', cur_marker='+')
         xlkw['select'].update(level=slice(int(options.level),None))
         try: cur, var, lat, lon = mars.plot_extrema_location(**xlkw)
         except: log.exception('Cannot plot mars')
         
         xrotate(45)
         pylab.legend(loc='best')
         
         try: mars.plot_trajectory_map(lon, lat, **xlkw)
         except: log.exception('Cannot plot trajectory')
         
         output = options.output%dict(plot='loc', op=op, var=varname[0], tmin=strftime(dtfmt, itv[0]), tmax=strftime(dtfmt, itv[1]))
         log.info('Saving %s', output)
         pylab.savefig(output)
 
 if 'val' in options.plots:
     for op in options.operations:
         log.notice('val %s', op)
         pylab.figure()
         lckw = datakw.copy()
         lckw.update(operation=op, cur_vmin=0, cur_vmax=20)
         
         lckw.update(pmap=False, cur_color='b', cur_linestyle='', cur_marker='o')
         try: cur, var, lat, lon = sat.plot_localized_computed_values(**lckw)
         except: log.exception('Cannot plot satellite')
         
         lckw.update(pmap=False, cur_color='g', cur_linestyle='-', cur_marker='+')
    P.figure()
    mod = MV2.sqrt(u10 ** 2 + v10 ** 2)
    levels = auto_scale(mod, nmax=10, vmin=0.0, vmax=10.0)
    kwarg = dict(
        m=m,
        lon=(milo, malo),
        lat=(mila, mala),
        nofill=True,
        quiverkey_value=2,
        quiver_scale=35,
        quiver_norm=3,
        contour=False,
        quiver_alpha=0.9,
        quiver_width=7.0,
        title="Wind - "
        + strftime("%d/%m/%Y - %H:%M:%S", cdtime.reltime(u10.getTime().getValue()[it], u10.getTime().units).tocomp()),
        show=False,
        levels=levels,
        colorbar_shrink=0.7,
        right=1,
        quiver_samp=1,
        cmap="cmap_jete",
    )
    # => Practice : change map parameters.

    print strftime("%d/%m/%Y - %H:%M:%S", cdtime.reltime(u10.getTime().getValue()[it], u10.getTime().units).tocomp())

    m = map((u10[it, 0, :, :], v10[it, 0, :, :]), **kwarg)
    # => Practice: instead of a quiver map, generate a map with current amplitude.

    P.show()
Esempio n. 12
0
print is_comptime(ctime), is_reltime(rtime), is_cdtime(ctime)

# ---- VACUMM Bonus ----
# Read from a string and a format
# => Practice: check strptime in google
mytime = strptime('1950-01-01 07:00:00',
                  '%Y-%m-%d %H:%M:%S')  # => Practice: Try different formats
# - Check
print mytime.year, mytime.minute

# We choose the french language
import locale
locale.setlocale(locale.LC_ALL, 'fr_FR')

# Write in a different format
print strftime('%e %B %Y a %Hh%M',
               mytime)  # => Practice: Try different formats

# ---- Time axes ----
print 10 * '-' + ' Time axes ' + 10 * '-'
units = 'hours since 2000-01-15 06:00'
taxis = create_time(N.arange(6.) * 48, units)
print taxis.getValue()
print 'Units before change: ', taxis.units
# - change units
ch_units(taxis, 'days since 2000-1-15 06:00', copy=0)
print taxis.getValue()
print 'Units after change: ', taxis.units

# ------------------------------------------------------------------------------------------------------------
# ---- lindates ----
print 10 * '-' + ' lindates ' + 10 * '-'
    Uis = cdms2.createVariable(Uis, typecode='f',id='UZ', axes=axes, attributes=dict(long_name='3d zonal velocity',standard_name='eastward_sea_water_velocity',units='m.s-1',valid_min='-100.',valid_max='100.'))
    Vis = cdms2.createVariable(Vis, typecode='f',id='VZ', axes=axes, attributes=dict(long_name='3d meridional velocity',standard_name='northward_sea_water_velocity',units='m.s-1',valid_min='-100.',valid_max='100.'))



    for iz, dep in enumerate(U.getLevel()):
        Ui2 = interp2d(U[0,iz,:,:], (xo,yo), method='bilinear')
        Vi2 = interp2d(V[0,iz,:,:], (xo,yo), method='bilinear')
 
        Uis[iz,:,:]=Ui2
        Vis[iz,:,:]=Vi2



    date=strftime('_%Y%m%d%H0000',c1)
    file_out = 'MARS_MENOR_'+date+'.nc'
    f = cdms2.open(os.path.join(dir_model,file_out), 'w')
    #f.write(LATITUDE)
    #f.write(LONGITUDE)
    #f.write(TIME)
    #f.write(DEPTH)


    f.write(Uis) # ecriture d'une variable
    f.write(Vis)
    f.history = 'Created with '+__file__.encode('utf8') # attribut global
    f.close() # fermeture

    del Uis, Vis
Esempio n. 14
0
 # ==========
 # Methode 1. Tracé des observations (points) sur fond 2D grillés de champs de modèles moyennés sur la période choisie.
 if not options.coloc:
     
     if 'mld' in options.plots:
         pylab.figure()
         kw = plotkw.copy()
         m = c = None
         try: m,c = mars.plot_mld(select, **kw)
         except: log.exception('Cannot plot mars mld')
         kw.update(map=m, cmap=c)
         try: profiles.plot_mld(select, **kw)
         except: log.exception('Cannot plot profiles mld')
         pylab.legend(loc='best')
         pylab.title('Mixed Layer Depth\ntime: %s'%(itv,))
         output = options.output%dict(plot='mld', tmin=strftime(dtfmt, itv[0]), tmax=strftime(dtfmt, itv[1]))
         log.notice('Saving %s', output)
         pylab.savefig(output)
     
     if 'ped' in options.plots:
         pylab.figure()
         kw = plotkw.copy()
         m = c = None
         try: m,c = mars.plot_ped(select, **kw)
         except: log.exception('Cannot plot mars ped')
         kw.update(map=m, cmap=c)
         try: profiles.plot_ped(select, **kw)
         except: log.exception('Cannot plot profiles ped')
         pylab.legend(loc='best')
         pylab.title('Potential Energy Deficit\ntime: %s'%(itv,))
         output = options.output%dict(plot='ped', tmin=strftime(dtfmt, itv[0]), tmax=strftime(dtfmt, itv[1]))
Esempio n. 15
0
from vacumm.misc.atime import strftime, strptime

# Lecture a partir d'une chaine de caracteres et d'un format
# (tappez strptime dans google)
mytime = strptime('1950-01-01 07:00:00', '%Y-%m-%d %H:%M:%S')
# Verification partielle
print mytime.year, mytime.minute
# -> 1950 0

# On choisit la langue francaise
import locale
locale.setlocale(locale.LC_ALL, 'fr_FR')

# Ecriture sous un autre format
print strftime('%e %B %Y a %Hh%M', mytime)
# ->  1 janvier 1950 a 07h00
Esempio n. 16
0
                        mp = profiles.plot_layer(varname=varname,
                                                 depth=depth,
                                                 select=select,
                                                 **plotkw)
                    except:
                        log.exception('Cannot plot profiles layer')

                else:
                    pylab.figure()
                    try:
                        Colocator().plot_layer_mod_on_pro(mars,
                                                          profiles,
                                                          varname=varname,
                                                          depth=depth,
                                                          select=select,
                                                          method=options.coloc)
                    except:
                        log.exception('Cannot plot layer')

                output = options.output % dict(var=varname[0],
                                               depth='%sm' % abs(depth),
                                               tmin=strftime(dtfmt, itv[0]),
                                               tmax=strftime(dtfmt, itv[1]))
                pylab.legend(loc='best')
                pylab.title('Layer %s\nDepth: %s\ntime: %s' %
                            (varname[0], depth, itv))
                log.notice('Saving %s', output)
                pylab.savefig(output)

    if options.show: pylab.show()
Esempio n. 17
0
        for itv in Intervals((tmin, tmax, tbb), (tstep, ustep)):
            log.notice("Interval %s", itv)
            select = dict(time=itv[:2])
            if options.level:
                select["level"] = slice(*map(int, options.level.split(",")))
            if options.bbox:
                select.update(dict(latitude=(latmin, latmax), longitude=(lonmin, lonmax)))
            pylab.figure()
            try:
                sec = mars.plot_section(
                    varname=varname,
                    select=select,
                    xmin=xmin,
                    ymin=ymin,
                    xmax=xmax,
                    ymax=ymax,
                    pmap=True,
                    sec_axes_rect=[0.1, 0.1, 0.6, 0.7],
                    map_axes_rect=[0.75, 0.1, 0.2, 0.3],
                    plot_show=False,
                )
            except:
                log.exception("")
            pylab.legend(loc="best")
            output = options.output % dict(var=varname[0], tmin=strftime(dtfmt, itv[0]), tmax=strftime(dtfmt, itv[1]))
            log.notice("Saving %s", output)
            pylab.savefig(output)

    if options.show:
        pylab.show()
Esempio n. 18
0
#  -> [2000-1-15 6:0:0.0, 2000-1-17 6:0:0.0]

# Matplotlib times
taxis_mpl = mpl(taxis)
print taxis_mpl[0], taxis_mpl.units
#  -> 730134.25 days since 0001

# Change the time units of a variable
import MV2

var = MV2.array(MV2.arange(len(taxis)), dtype='f', axes=[taxis])
ch_units(var, 'hours since 2000-01-15 06')
print var.getTime()[0:2]
#  -> [  0.  48.]

# Change time zone
# - UTC time now
t_utc = now(True)
print strftime('%H:%M', t_utc), t_utc.hour
#  -> 15:54 15
# - Paris time
t_paris = utc_to_paris(t_utc)
print strftime('%H:%M', t_paris), t_paris.hour
#  -> 17:54 17
# - back to UTC
print tz_to_tz(t_paris, 'Europe/Paris', 'UTC').hour
#  -> 15
# - we can work on a time string!
print to_utc('2000-10-01 10:20', 'Europe/Paris')
#  -> '2000-10-1 8:20:0.0'
Esempio n. 19
0
print is_comptime(ctime),is_reltime(rtime),is_cdtime(ctime)


# ---- VACUMM Bonus ----
# Read from a string and a format
# => Practice: check strptime in google
mytime = strptime('1950-01-01 07:00:00','%Y-%m-%d %H:%M:%S') # => Practice: Try different formats
# - Check
print mytime.year,mytime.minute

# We choose the french language 
import locale
locale.setlocale(locale.LC_ALL,'fr_FR')

# Write in a different format
print strftime('%e %B %Y a %Hh%M',mytime) # => Practice: Try different formats

# ---- Time axes ---- 
print 10*'-'+' Time axes '+10*'-'
units = 'hours since 2000-01-15 06:00'
taxis = create_time(N.arange(6.)*48, units)
print taxis.getValue()
print 'Units before change: ',taxis.units
# - change units
ch_units(taxis, 'days since 2000-1-15 06:00', copy=0)
print taxis.getValue()
print 'Units after change: ',taxis.units

# ------------------------------------------------------------------------------------------------------------
# ---- lindates ----
print 10*'-'+' lindates '+10*'-'
Esempio n. 20
0
                select = dict(time=itv[:2], latitude=(latmin,latmax,'ccb'), longitude=(lonmin,lonmax,'ccb'))
                
                if not options.coloc:
                
                    pylab.figure()
                    try:
                        mp = mars.plot_layer(varname=varname, depth=depth, select=select, **plotkw)
                        plotkw['map'] = mp
                    except: log.exception('Cannot plot mars layer')
                    try: mp = profiles.plot_layer(varname=varname, depth=depth, select=select, **plotkw)
                    except: log.exception('Cannot plot profiles layer')
                
                else:
                    pylab.figure()
                    try: Colocator().plot_layer_mod_on_pro(mars, profiles, varname=varname, depth=depth, select=select, method=options.coloc)
                    except: log.exception('Cannot plot layer')
                    
                output = options.output%dict(var=varname[0], depth='%sm'%abs(depth), tmin=strftime(dtfmt, itv[0]), tmax=strftime(dtfmt, itv[1]))
                pylab.legend(loc='best')
                pylab.title('Layer %s\nDepth: %s\ntime: %s'%(varname[0], depth, itv))
                log.notice('Saving %s', output)
                pylab.savefig(output)
    
    if options.show: pylab.show()
    
    




Esempio n. 21
0
#  -> [2000-1-15 6:0:0.0, 2000-1-17 6:0:0.0]

# Matplotlib times
taxis_mpl = mpl(taxis)
print taxis_mpl[0], taxis_mpl.units
#  -> 730134.25 days since 0001

# Change the time units of a variable
import MV2
var = MV2.array(MV2.arange(len(taxis)), dtype='f', axes=[taxis])
ch_units(var, 'hours since 2000-01-15 06')
print var.getTime()[0:2]
#  -> [  0.  48.]


# Change time zone
# - UTC time now
t_utc = now(True)
print strftime('%H:%M', t_utc), t_utc.hour
#  -> 15:54 15
# - Paris time
t_paris = utc_to_paris(t_utc)
print strftime('%H:%M', t_paris), t_paris.hour
#  -> 17:54 17
# - back to UTC
print tz_to_tz(t_paris,'Europe/Paris','UTC').hour
#  -> 15
# - we can work on a time string!
print to_utc('2000-10-01 10:20', 'Europe/Paris')
#  -> '2000-10-1 8:20:0.0'
Esempio n. 22
0
# We load a cdms variable
f = cdms.open(data_sample('mars3d.t.nc'))
temp = f('temp')
u =  f('u')
v =  f('v')
f.close()

# We get the Time
time =  temp.getTime() # axis
ctime = time.asComponentTime() # time cdtime.comptime()

# Create the file with the format : YYYY/MM/DDZHH:MM TEMP U V
f = open('misc.io.ascii.1.dat', 'w')
f.write('# Ligne de commentaire\n')
for it in xrange(len(temp)):
    t = strftime('%Y/%m/%dZ%H:%M',  ctime[it])
    f.write('%s %.4f %f %f\n' % (t, temp[it], u[it], v[it]))
f.close()
# => Practice: Read just a small part of the file (10 last lines and/or 10 first lines)

# Quick check (two first lines)
f = open('misc.io.ascii.1.dat')
print ''.join(f.readlines()[:3])
f.close()

# Quick writing using Numpy
# - Creation
time_units = 'hours since %s'%ctime[0]
newtime = ch_units(time, time_units)[:]
data = N.array([newtime,temp.filled(999.), 
    u.filled(999.), v.filled(999.)],copy=0)
Esempio n. 23
0
temp = f("temp")
u = f("u")
v = f("v")
f.close()

# On recupre le temps
time = temp.getTime()  # axe
ctime = time.asComponentTime()  # temps cdtime.comptime()

# Creation a la main au format : YYYY/MM/DDZHH:MM TEMP U V
from vacumm.misc.atime import strftime, ch_units, strptime

f = open("misc.io.ascii.1.dat", "w")
f.write("# Ligne de commentaire\n")
for it in xrange(len(temp)):
    t = strftime("%Y/%m/%dZ%H:%M", ctime[it])
    f.write("%s %.4f %f %f\n" % (t, temp[it], u[it], v[it]))
f.close()

# Verification rapide (deux premieres lignes)
f = open("misc.io.ascii.1.dat")
print "".join(f.readlines()[:3])
f.close()
#  -> # Ligne de commentaire
# -> 2008/01/07Z00:00 12.0672 0.359631 0.156422
# -> 2008/01/07Z01:00 11.9421 0.493174 0.158244

# Ecriture rapide via numpy
# - creation
import numpy as N