def get_start_time(prefix):
    '''
    Try to find start time in PARAM files.  Use prefix to determine
    where PARAMs should be.
    '''

    from spacepy.pybats import parse_filename_time

    starttime = False

    # Start by searching for PARAM.in files in PWD and, if necessary,
    # up one or two directories.
    params = glob('PARAM*')
    if prefix == './GM/IO2/': params += glob('../../PARAM*')
    if prefix == './GM/': params += glob('../PARAM*')

    # Flip through files searching for #STARTTIME
    for p in params:
        f = open(p, 'r')
        line = f.readline()
        while line:
            if 'STARTTIME' in line:
                starttime = dt.datetime(int(f.readline()[:4]),
                                        int(f.readline()[:2]),
                                        int(f.readline()[:2]),
                                        int(f.readline()[:2]),
                                        int(f.readline()[:2]),
                                        int(f.readline()[:2]))
                return starttime
            line = f.readline()

    # Next, attempt to use the file names themselves:
    y_file = glob(prefix + '/y??_mhd*.out')[0]
    i_iter, runtime, starttime = parse_filename_time(y_file)

    return starttime
Beispiel #2
0
 def testParse(self):
     from spacepy.pybats import parse_filename_time
     for f, d, t, i in zip(self.files, self.dates, self.times, self.iters):
         self.assertEqual(parse_filename_time(f), (i, t, d))
Beispiel #3
0
    file_list = glob(args.dir + '/GM/IO2/mag_grid*.out')
    outdir = outdir + 'GM/IO2/'
if not file_list:
    raise ValueError(f"Could not find any MagGrid files in {args.dir}")

###### CONSTANTS ##########
varlist = 'dBn dBe dBd dBnMhd dBeMhd dBdMhd dBnFac dBeFac '+\
          'dBdFac dBnHal dBeHal dBdHal dBnPed dBePed dBdPed'

###### SET UP #######
nfiles_all = len(file_list)

out = open(outdir + args.outfile, 'w')

# Get file times:
t1_all = parse_filename_time(file_list[0])[-1]
t2_all = parse_filename_time(file_list[-1])[-1]

# Get time from files OR flags:
if not args.tstart:
    t1 = t1_all
else:
    t1 = parse(args.tstart)

if not args.tstop:
    t2 = t2_all
else:
    t2 = parse(args.tstop)

# Reduce file list appropriately:
if t1 != t1_all:
def plot_results(fileY, fileZ, iFile=0, nFiles=1):
    '''
    Create a nice plot of WTF is happening.
    Kwargs iFile and nFiles are for reporting progress.
    '''

    # Get start times from file names:
    time_y = pb.parse_filename_time(fileY)
    time_z = pb.parse_filename_time(fileZ)

    # Check that times match:
    for t1, t2 in zip(time_y, time_z):
        if t1 != t2:
            print(
                'File times do not match!\n\tY-File: {}\n\tZ-File: {}'.format(
                    t1, t2))
            raise ValueError('File time mismatch')

    # Use file time info get actual time:
    if time_y[-1]:
        tNow = time_y[-1]  # Datetime in file name.
    elif time_y[1]:
        t_delta = dt.timedelta(seconds=time_y[1])
        tNow = start + t_delta  # Runtime in file name.
    else:
        tNow = start  # Only iteration given.

    # Check if files are outside time range.
    if tNow < trange[0]: return 0
    if tNow > trange[-1]: return 0

    # Open files & calculate important values:
    mY = pbs.Bats2d(fileY)
    mZ = pbs.Bats2d(fileZ)
    mY.calc_ndens()
    mZ.calc_ndens()
    mY.calc_utotal()
    mZ.calc_utotal()

    if mZ.attrs['runtime'] != mY.attrs['runtime']:
        print('{}\n{}\n'.format(fileY, fileZ))
        raise (ValueError('Times of files do not line up!'))

    fig = plt.figure(figsize=[11, 8.5])
    fig.subplots_adjust(left=0.08, right=.96, bottom=0.06, top=.93)

    a1 = fig.add_subplot(221)
    stuff = mY.add_contour('x',
                           'z',
                           v1,
                           91,
                           dolog=True,
                           xlim=xrng,
                           ylim=zrng,
                           add_cbar=True,
                           target=a1,
                           zlim=prng,
                           cmap=cmap1)
    a1.set_title('{} ({})'.format(pb.mhdname_to_tex(v1),
                                  mY[v1].attrs['units']))

    stuff[-1].set_label('')
    if args.mag: mY.add_b_magsphere(a1, DoOpen=True)
    a2 = fig.add_subplot(222)
    stuff = mZ.add_contour('x',
                           'y',
                           v2,
                           91,
                           dolog=True,
                           xlim=xrng,
                           ylim=yrng,
                           add_cbar=True,
                           target=a2,
                           zlim=drng,
                           cmap=cmap2)
    a2.set_title('{} ({})'.format(pb.mhdname_to_tex(v2),
                                  mZ[v2].attrs['units']))
    stuff[-1].set_label('')

    for s in sats:
        s.add_sat_loc(tNow, a1, plane='XZ', dolabel=True, color='r', size=9)
        s.add_sat_loc(tNow, a2, plane='XY', dolabel=True, color='r', size=9)

    pos = stuff[-1].ax.get_position()

    a3, a4 = fig.add_subplot(413), fig.add_subplot(414)
    a5 = a4.twinx()
    pos3, pos4 = a3.get_position(), a4.get_position()
    a3.set_position([pos3.xmin, pos3.ymin, pos3.width * .95, pos3.height])
    a4.set_position([pos4.xmin, pos4.ymin, pos4.width * .95, pos4.height])
    a5.set_position([pos4.xmin, pos4.ymin, pos4.width * .95, pos4.height])

    log.add_dst_quicklook(target=a3,
                          plot_obs=args.obsdst,
                          obs_kwargs={
                              'c': 'k',
                              'ls': '-'
                          },
                          color='r')
    a3.legend(loc='best', fontsize=10)
    a3.set_xlabel('')
    applySmartTimeTicks(a3, trange, dolabel=False)
    a3.grid(False, axis='y')
    a3.set_ylabel('D$_{ST}$ ($nT$)')
    a3.hlines(0, trange[0], trange[1], color='grey', linestyles='dashed')
    ymin, ymax = a3.get_ylim()
    a3.vlines(tNow, ymin, ymax, linestyles='solid', color='g', linewidths=2.)
    a3.set_ylim([ymin, ymax])

    a4.plot(imf['time'], imf['bz'], color=bzcolor, label='B$_Z$')
    if args.by:
        a4.plot(imf['time'], imf['by'], color=bycolor, label='B$_Y$')
        a4.legend(loc='best', ncol=2)
    a5.plot(imf['time'], imf['pram'], color=pdcolor, lw=1.5)
    applySmartTimeTicks(a4, trange, dolabel=True)
    a4.grid(False, axis='y')
    a4.hlines(0, trange[0], trange[1], color=bzcolor, linestyles='dashed')
    a4.set_ylabel('IMF ' + (not args.by) * 'B$_{Z}$ ' + '($nT$)',
                  color=bzcolor)
    a5.set_ylabel('P$_{dyn}$ ($nPa$)', color=pdcolor)
    a5.grid(False, axis='y')
    ymin, ymax = a4.get_ylim()
    a4.vlines(tNow, ymin, ymax, linestyles='solid', color='g', linewidths=2.)
    a4.set_ylim([ymin, ymax])

    fig.suptitle(args.title, size=18)

    # Save the figure (normal operation) or show figure (debug mode).
    if args.debug:
        plt.show()
    else:
        fig.savefig(args.outdir + '/mhd{:%Y%m%d_%H%M%S}.png'.format(tNow))

    # Clear and close figure.
    if not args.debug:
        fig.clf()
        plt.close(fig)

    percent_done = float(iFile + 1) / float(nFiles) * 100.0
    return percent_done
Beispiel #5
0
 def testParse(self):
     from spacepy.pybats import parse_filename_time
     for f, d, t, i in zip(self.files, self.dates, self.times, self.iters):
         self.assertEqual( parse_filename_time(f), (i,t,d) )