示例#1
0
def GetstatFiles(directory):
# gets a list of stat files, accounting for checkpointing 
# in order of first to last (time-wise) 
# also get a time index )time_index_end) for each stat file where
# statfile_i['ElapsedTime']['value'][index] = statfile_i+1['ElapsedTime']['value'][0]

  time_index_end = []
  stat_files = glob.glob(directory+'*.stat')

  time_end = []
  for sf in stat_files: 
    if 'original' in sf: stat_files.remove(sf)
  for sf in stat_files: 
    stat = stat_parser(sf); time_end.append(stat['ElapsedTime']['value'][-1])
  vals = zip(time_end, stat_files)

  vals.sort(key=key)
  unzip = lambda l:tuple(apply(zip,l))

  time_end, stat_files = unzip(vals)
  for i in range(len(stat_files)-1):
    stat_0 = stat_parser(stat_files[i])
    time_0 = stat_0['ElapsedTime']['value']
    stat_1 = stat_parser(stat_files[i+1])
    time_1 = stat_1['ElapsedTime']['value']
    try: time_index_end.append(pylab.find(numpy.array(time_0)>=time_1[0])[0])
    except IndexError: time_index_end.append(len(time_0)) 

  stat = stat_parser(stat_files[-1])
  time_index_end.append(len(stat['ElapsedTime']['value']))

  return (stat_files, time_index_end)
示例#2
0
def read_p_from_stat(statfilename):
    """
     reads the pressure from a .stat file and stores it in
     an two-dimensional array 'p'
     input: is a file containing a list of .stat files
     in the directory 'statfiles/'
  """
    #Initialising pmin and pmax as empty arrays:
    pmin = []
    pmax = []
    # Get string-array with stat filenames:
    if (statfilename.startswith('statfiles/list_')):
        f = open(statfilename)
        statfiles = f.readlines()
        f.close()
        # Read in time values, append them to 'time'
        # over all .stat files listed in 'statlistfilename'
        for filename in statfiles:
            filename = filename[0:len(filename) - 1]
            stat = fluidity_tools.stat_parser(filename)
            pmin.extend(stat['fluid']['Pressure']['min'])
            pmax.extend(stat['fluid']['Pressure']['max'])
    else:
        stat = fluidity_tools.stat_parser(statfilename)
        pmin.extend(stat['fluid']['Pressure']['min'])
        pmax.extend(stat['fluid']['Pressure']['max'])
    return pmin, pmax
示例#3
0
def read_walltime_from_stat(statfilename, totalwt=False):
  """
     reads the walltime from a .stat file and stores it in
     an one-dimensional array 'walltime'
     Input: 
      statfilename: String of the statfile
      totalwt: locigal, if True, the overall walltime is computed
        otherwise the walltime of each timestep is given back.
     
  """
  #Initialising walltime as an empty array:
  walltime = []; walltime_tmp = []
  # Get string-array with stat filenames:
  if (statfilename.startswith('statfiles/list_')):
    f = open(statfilename)
    statfiles = f.readlines()
    f.close()
    # Read in time values, append them to 'time'
    # over all .stat files listed in 'statlistfilename'
    for filename in statfiles:
        filename = filename[0:len(filename)-1]
        stat = fluidity_tools.stat_parser(filename)
        if (totalwt):
          # if totalwt == True, then compute the total walltime
          # of all (checkpointed) statfiles
          walltime_tmp = stat['ElapsedWallTime']['value']
          if (walltime):
            walltime_tmp = walltime_tmp + walltime[-1]
          walltime.extend(walltime_tmp)
        else:
          walltime.extend(stat['ElapsedWallTime']['value'])
  else:
    stat = fluidity_tools.stat_parser(statfilename)
    walltime.extend(stat['ElapsedWallTime']['value'])
  return walltime
示例#4
0
def read_void_df_viscouscomponent_from_stat(statfilename,
                                            surfacename,
                                            component=1):
    """
     reads the viscous component of the drag force
     from a void body from a .stat file and stores it in
     an one-dimensional array ''
     input: is a file containing a list of .stat files
     in the directory 'statfiles/'
  """
    #Initialising time as an empty array:
    df_vsccmp = []
    # Get string-array with stat filenames:
    if (statfilename.startswith('statfiles/list_')):
        f = open(statfilename)
        statfiles = f.readlines()
        f.close()
        for filename in statfiles:
            filename = filename[0:len(filename) - 1]
            stat = fluidity_tools.stat_parser(filename)
            df_vsccmp.extend(
                stat['fluid']['Velocity']['viscous_force_' + surfacename +
                                          '%' + str(component)])
    else:
        stat = fluidity_tools.stat_parser(statfilename)
        df_vsccmp.extend(
            stat['fluid']['Velocity']['viscous_force_' + surfacename + '%' +
                                      str(component)])
    return df_vsccmp
示例#5
0
def read_fsi_model_df_from_stat(statfilename, component=1, solidmeshname=''):
    """
     reads the drag force from an immersed body
     (fsi_model) from a .stat file and stores it in
     an one-dimensional array 'df'
     input: is a file containing a list of .stat files
     in the directory 'statfiles/'
  """
    #Initialising df as an empty array:
    df = []
    # Get string-array with stat filenames:
    if (statfilename.startswith('statfiles/list_')):
        f = open(statfilename)
        statfiles = f.readlines()
        f.close()
        for filename in statfiles:
            filename = filename[0:len(filename) - 1]
            stat = fluidity_tools.stat_parser(filename)
            df.extend(stat['ForceOnSolid_' + str(solidmeshname) +
                           str(component)]['Value'])
    else:
        stat = fluidity_tools.stat_parser(statfilename)
        df.extend(stat['ForceOnSolid_' + str(solidmeshname) +
                       str(component)]['Value'])
    return df
示例#6
0
def read_fsi_model_solidvolume_from_stat(statfilename, solidmeshname):
    """
     reads the solidvolume from an immersed body
     (fsi_model) from a .stat file and stores it in
     an one-dimensional array 'solidvolume'
     input: is a file containing a list of .stat files
     in the directory 'statfiles/'
  """
    #Initialising solidvolume as an empty array:
    solidvolume = []
    # Get string-array with stat filenames:
    if (statfilename.startswith('statfiles/list_')):
        f = open(statfilename)
        statfiles = f.readlines()
        f.close()
        for filename in statfiles:
            filename = filename[0:len(filename) - 1]
            stat = fluidity_tools.stat_parser(filename)
            solidvolume.extend(stat['VolumeOfSolid_' +
                                    str(solidmeshname)]['Value'])
    else:
        stat = fluidity_tools.stat_parser(statfilename)
        solidvolume.extend(stat['VolumeOfSolid_' +
                                str(solidmeshname)]['Value'])
    return solidvolume
示例#7
0
def read_position_from_detector(detfilename, detname):
    """
     reads the position from a detector file and stores it in
     an 'pos'
     input: is the filename of the detector file,
     and the name of the detector
  """
    #Initialising velocity as an empty array:
    pos = []
    dummy = []
    # Get string-array with stat filenames:
    if (detfilename.startswith('statfiles/list_')):
        f = open(detfilename)
        detfiles = f.readlines()
        f.close()
        for filename in detfiles:
            filename = filename[0:len(filename) - 1]
            detectors = fluidity_tools.stat_parser(filename)
            if (len(pos) == 0):
                pos = detectors[detname]['position']
            else:
                pos = column_stack((pos, detectors[detname]['position']))
    else:
        # Get velocity
        detectors = fluidity_tools.stat_parser(detfilename)
        pos = detectors[detname]['position']
    return pos
示例#8
0
def read_velocity_from_detector(detfilename, detname):
    """
     reads the velocity from a detector file and stores it in
     an 'v'
     input: is the filename of the detector file,
     and the name of the detector
  """
    #Initialising velocity as an empty array:
    v = []
    dummy = []
    # Get string-array with stat filenames:
    if (detfilename.startswith('statfiles/list_')):
        f = open(detfilename)
        detfiles = f.readlines()
        f.close()
        for filename in detfiles:
            filename = filename[0:len(filename) - 1]
            detectors = fluidity_tools.stat_parser(filename)
            if (len(v) == 0):
                v = detectors['fluid']['Velocity'][detname]
            else:
                v = column_stack((v, detectors['fluid']['Velocity'][detname]))
    else:
        # Get velocity
        detectors = fluidity_tools.stat_parser(detfilename)
        v = detectors['fluid']['Velocity'][detname]
    return v
示例#9
0
def read_p_from_stat(statfilename):
  """
     reads the pressure from a .stat file and stores it in
     an two-dimensional array 'p'
     input: is a file containing a list of .stat files
     in the directory 'statfiles/'
  """
  #Initialising pmin and pmax as empty arrays:
  pmin = []; pmax=[]
  # Get string-array with stat filenames:
  if (statfilename.startswith('statfiles/list_')):
    f = open(statfilename)
    statfiles = f.readlines()
    f.close()
    # Read in time values, append them to 'time'
    # over all .stat files listed in 'statlistfilename'
    for filename in statfiles:
        filename = filename[0:len(filename)-1]
        stat = fluidity_tools.stat_parser(filename)
        pmin.extend(stat['fluid']['Pressure']['min'])
        pmax.extend(stat['fluid']['Pressure']['max'])
  else:
    stat = fluidity_tools.stat_parser(statfilename)
    pmin.extend(stat['fluid']['Pressure']['min'])
    pmax.extend(stat['fluid']['Pressure']['max'])
  return pmin, pmax
示例#10
0
def read_int_solidconcentration_from_stat(statfilename, solidname=''):
    """
     reads the integral of the solidconcentration field
     from a .stat file and stores it in
     an one-dimensional array 'int_alpha'
     input: is a file containing a list of .stat files
     in the directory 'statfiles/'
  """
    #Initialising int_alpha as empty arrays:
    int_alpha = []
    # Get string-array with stat filenames:
    if (statfilename.startswith('statfiles/list_')):
        f = open(statfilename)
        statfiles = f.readlines()
        f.close()
        # Read in the values
        # over all .stat files listed in 'statlistfilename'
        for filename in statfiles:
            filename = filename[0:len(filename) - 1]
            stat = fluidity_tools.stat_parser(filename)
            int_alpha.extend(stat['fluid'][solidname +
                                           'SolidConcentration']['integral'])
    else:
        stat = fluidity_tools.stat_parser(statfilename)
        int_alpha.extend(stat['fluid'][solidname +
                                       'SolidConcentration']['integral'])
    return int_alpha
示例#11
0
def read_int_solidforce_comp_from_stat(statfilename, solidname='', component=1):
  """
     reads the integral of the vector 'component' of the
     solidforce field from a .stat file and stores it in
     an one-dimensional array 'int_solidforce_comp'
     input: is a file containing a list of .stat files
     in the directory 'statfiles/'
  """
  if (component=='x' or component==1 or component=='1'):
    comp='1'
  elif (component=='y' or component==2 or component=='2'):
    comp='2'
  elif (component=='z' or component==3 or component=='3'):
    comp='3'
  else:
    comp='1'

  #Initialising int_solidforce_comp as empty arrays:
  int_solidforce_comp = []
  # Get string-array with stat filenames:
  if (statfilename.startswith('statfiles/list_')):
    f = open(statfilename)
    statfiles = f.readlines()
    f.close()
    # Read in the values
    # over all .stat files listed in 'statlistfilename'
    for filename in statfiles:
        filename = filename[0:len(filename)-1]
        stat = fluidity_tools.stat_parser(filename)
        int_solidforce_comp.extend(stat['fluid'][solidname+'SolidForce%'+str(comp)]['integral'])
  else:
    stat = fluidity_tools.stat_parser(statfilename)
    int_solidforce_comp.extend(stat['fluid'][solidname+'SolidForce%'+str(comp)]['integral'])
  return int_solidforce_comp
示例#12
0
def read_position_from_detector(detfilename, detname):
  """
     reads the position from a detector file and stores it in
     an 'pos'
     input: is the filename of the detector file,
     and the name of the detector
  """
  #Initialising velocity as an empty array:
  pos = []; dummy = [];
  # Get string-array with stat filenames:
  if (detfilename.startswith('statfiles/list_')):
    f = open(detfilename)
    detfiles = f.readlines()
    f.close()
    for filename in detfiles:
        filename = filename[0:len(filename)-1]
        detectors = fluidity_tools.stat_parser(filename)
        if (len(pos) == 0):
            pos = detectors[detname]['position']
        else:
            pos = column_stack((pos,detectors[detname]['position']))
  else:
    # Get velocity
    detectors = fluidity_tools.stat_parser(detfilename)
    pos = detectors[detname]['position']
  return pos
示例#13
0
def read_int_solidconcentration_from_stat(statfilename, solidname=''):
  """
     reads the integral of the solidconcentration field
     from a .stat file and stores it in
     an one-dimensional array 'int_alpha'
     input: is a file containing a list of .stat files
     in the directory 'statfiles/'
  """
  #Initialising int_alpha as empty arrays:
  int_alpha = []
  # Get string-array with stat filenames:
  if (statfilename.startswith('statfiles/list_')):
    f = open(statfilename)
    statfiles = f.readlines()
    f.close()
    # Read in the values
    # over all .stat files listed in 'statlistfilename'
    for filename in statfiles:
        filename = filename[0:len(filename)-1]
        stat = fluidity_tools.stat_parser(filename)
        int_alpha.extend(stat['fluid'][solidname+'SolidConcentration']['integral'])
  else:
    stat = fluidity_tools.stat_parser(statfilename)
    int_alpha.extend(stat['fluid'][solidname+'SolidConcentration']['integral'])
  return int_alpha
示例#14
0
def read_velocity_from_detector(detfilename, detname):
  """
     reads the velocity from a detector file and stores it in
     an 'v'
     input: is the filename of the detector file,
     and the name of the detector
  """
  #Initialising velocity as an empty array:
  v = []; dummy = [];
  # Get string-array with stat filenames:
  if (detfilename.startswith('statfiles/list_')):
    f = open(detfilename)
    detfiles = f.readlines()
    f.close()
    for filename in detfiles:
        filename = filename[0:len(filename)-1]
        detectors = fluidity_tools.stat_parser(filename)
        if (len(v) == 0):
            v = detectors['fluid']['Velocity'][detname]
        else:
            v = column_stack((v,detectors['fluid']['Velocity'][detname]))
  else:
    # Get velocity
    detectors = fluidity_tools.stat_parser(detfilename)
    v = detectors['fluid']['Velocity'][detname]
  return v
示例#15
0
def bruneau_ke(NN):
#Bruneau and Saad 2006. Table 7. 
  vel_l2_norm = stat_parser('driven_cavity-%d/driven_cavity.stat'%NN)['Fluid']['Velocity%magnitude']['l2norm'][-1]
  kinetic_energy = 0.5*vel_l2_norm**2
  kinetic_energy_error = abs( kinetic_energy - 0.044503 )
  print "botella_ke_error:", kinetic_energy_error
  return kinetic_energy_error
示例#16
0
def gage_error_integral(detector_filename):

    mea_filename = 'raw_data/WaveGages.csv'

    s = stat_parser(detector_filename)
    timesteps = s["ElapsedTime"]["value"]
    timestep = timesteps[1] - timesteps[0]
    print("Found ", len(timesteps), " timesteps with dt=", timestep,
          " starting at t0=", timesteps[0] - timestep)

    fs = s["water"]["FreeSurface"]
    print("Found ", len(fs), " free surface detectors.")

    error_integral = [0.0, 0.0, 0.0]

    # First timestep
    gauges = get_measurement(mea_filename, timesteps[0])
    error_integral[0] += 0.5 * abs(gauges[0]) * timestep
    error_integral[1] += 0.5 * abs(gauges[1]) * timestep
    error_integral[2] += 0.5 * abs(gauges[2]) * timestep
    for i in range(1, len(timesteps) - 1):
        gauges = get_measurement(mea_filename, timesteps[i])
        error_integral[0] += abs(gauges[0]) * timestep
        error_integral[1] += abs(gauges[1]) * timestep
        error_integral[2] += abs(gauges[2]) * timestep
    # Last timestep
    gauges = get_measurement(mea_filename, timesteps[-1])
    error_integral[0] += 0.5 * abs(gauges[0]) * timestep
    error_integral[1] += 0.5 * abs(gauges[1]) * timestep
    error_integral[2] += 0.5 * abs(gauges[2]) * timestep

    return error_integral
示例#17
0
def gage_error_integral(detector_filename):

  mea_filename='raw_data/WaveGages.csv'
 
  s = stat_parser(detector_filename)
  timesteps=s["ElapsedTime"]["value"]
  timestep=timesteps[1]-timesteps[0]
  print "Found ", len(timesteps), " timesteps with dt=", timestep, " starting at t0=", timesteps[0]-timestep
  
  fs=s["water"]["FreeSurface"]
  print "Found ", len(fs), " free surface detectors."

  error_integral=[0.0, 0.0, 0.0]

  # First timestep
  gauges=get_measurement(mea_filename, timesteps[0])
  error_integral[0]+=0.5*abs(gauges[0])*timestep
  error_integral[1]+=0.5*abs(gauges[1])*timestep
  error_integral[2]+=0.5*abs(gauges[2])*timestep
  for i in range(1, len(timesteps)-1):
    gauges=get_measurement(mea_filename, timesteps[i])
    error_integral[0]+=abs(gauges[0])*timestep
    error_integral[1]+=abs(gauges[1])*timestep
    error_integral[2]+=abs(gauges[2])*timestep
  # Last timestep
  gauges=get_measurement(mea_filename, timesteps[-1])
  error_integral[0]+=0.5*abs(gauges[0])*timestep
  error_integral[1]+=0.5*abs(gauges[1])*timestep
  error_integral[2]+=0.5*abs(gauges[2])*timestep
 
  return error_integral
def bruneau_ke(NN):
#Bruneau and Saad 2006. Table 7. 
  vel_l2_norm = stat_parser('driven_cavity-%d/driven_cavity.stat'%NN)['Fluid']['Velocity%magnitude']['l2norm'][-1]
  kinetic_energy = 0.5*vel_l2_norm**2
  kinetic_energy_error = abs( kinetic_energy - 0.044503 )
  print "botella_ke_error:", kinetic_energy_error
  return kinetic_energy_error
示例#19
0
def GetstatFiles(directory):
    # gets a list of stat files, accounting for checkpointing
    # in order of first to last (time-wise)
    # also get a time index )time_index_end) for each stat file where
    # statfile_i['ElapsedTime']['value'][index] = statfile_i+1['ElapsedTime']['value'][0]

    time_index_end = []
    stat_files = glob.glob(directory + '*.stat')

    time_end = []
    for sf in stat_files:
        if 'original' in sf: stat_files.remove(sf)
    for sf in stat_files:
        stat = stat_parser(sf)
        time_end.append(stat['ElapsedTime']['value'][-1])
    vals = zip(time_end, stat_files)

    vals.sort(key=key)
    unzip = lambda l: tuple(apply(zip, l))

    time_end, stat_files = unzip(vals)
    for i in range(len(stat_files) - 1):
        stat_0 = stat_parser(stat_files[i])
        time_0 = stat_0['ElapsedTime']['value']
        stat_1 = stat_parser(stat_files[i + 1])
        time_1 = stat_1['ElapsedTime']['value']
        try:
            time_index_end.append(
                pylab.find(numpy.array(time_0) >= time_1[0])[0])
        except IndexError:
            time_index_end.append(len(time_0))

    stat = stat_parser(stat_files[-1])
    time_index_end.append(len(stat['ElapsedTime']['value']))

    # in case stat file cut short when writing out:
    for ti in range(len(time_index_end)):
        stat = stat_parser(stat_files[ti])
        for bin_index in range(
                len(stat['fluid']['Temperature']
                    ['mixing_bins%cv_normalised'])):
            while stat['fluid']['Temperature']['mixing_bins%cv_normalised'][
                    bin_index][time_index_end[ti] - 1] == None:
                time_index_end[ti] = time_index_end[ti] - 1

    return (stat_files, time_index_end)
示例#20
0
def bruneau_sf(NN):
    #Bruneau and Saad 2006. Table 2.
    streamfunction_min = stat_parser(
        'driven_cavity-%d/driven_cavity.stat' %
        NN)['Fluid']['MultiplyConnectedStreamFunction']['min'][-1]
    streamfunction_min_error = abs(streamfunction_min - -0.11892)
    print "streamfunction_min_error:", streamfunction_min_error
    return streamfunction_min_error
示例#21
0
def mixing_stats():

    pylab.figure(num=2, figsize=(16.5, 11.5))
    pylab.suptitle('Mixing')

    times = []
    mixing_stats_lower = []
    mixing_stats_mixed = []
    mixing_stats_upper = []

    stat_files, time_index_end = le_tools.GetstatFiles('./')
    for sf in stat_files:
        stat = stat_parser(sf)
        for i in range(
                time_index_end[pylab.find(numpy.array(stat_files) == sf)]):
            times.append(stat['ElapsedTime']['value'][i])
            mixing_stats_lower.append(stat['fluid']['Temperature']
                                      ['mixing_bins%cv_normalised'][0][i])
            mixing_stats_mixed.append(stat['fluid']['Temperature']
                                      ['mixing_bins%cv_normalised'][1][i])
            mixing_stats_upper.append(stat['fluid']['Temperature']
                                      ['mixing_bins%cv_normalised'][2][i])

    pylab.plot(times, mixing_stats_lower, label='T < -0.4')
    pylab.plot(times, mixing_stats_mixed, label='-0.4 < T < 0.4')
    pylab.plot(times, mixing_stats_upper, label='0.4 < T')

    time = le_tools.ReadLog('diagnostics/logs/time.log')
    X_ns = [x - 0.4 for x in le_tools.ReadLog('diagnostics/logs/X_ns.log')]
    X_fs = [0.4 - x for x in le_tools.ReadLog('diagnostics/logs/X_fs.log')]
    try:
        index = pylab.find(numpy.array(X_ns) < 0.4 - 1E-3)[-1]
        pylab.fill_between([time[index], time[index + 1]], [0, 0], [0.5, 0.5],
                           color='0.3')
        index = pylab.find(numpy.array(X_fs) < 0.4 - 1E-3)[-1]
        pylab.fill_between([time[index], time[index + 1]], [0, 0], [0.5, 0.5],
                           color='0.6')
    except IndexError:
        print 'not plotting shaded regions on mixing plot as front has not reached end wall'

    pylab.axis([0, times[-1], 0, 0.5])
    pylab.grid("True")
    pylab.legend(loc=0)
    pylab.text(
        times[-1] - (times[-1] / 5),
        0.005,
        'shaded regions show when \nfronts near the end wall \ndark: free-slip, light: no-slip',
        bbox=dict(facecolor='white', edgecolor='black'))
    pylab.xlabel('time (s)')
    pylab.ylabel('domain fraction')

    pylab.savefig('diagnostics/plots/mixing.png')

    return
示例#22
0
def read_int_solidforce_comp_from_stat(statfilename,
                                       solidname='',
                                       component=1):
    """
     reads the integral of the vector 'component' of the
     solidforce field from a .stat file and stores it in
     an one-dimensional array 'int_solidforce_comp'
     input: is a file containing a list of .stat files
     in the directory 'statfiles/'
  """
    if (component == 'x' or component == 1 or component == '1'):
        comp = '1'
    elif (component == 'y' or component == 2 or component == '2'):
        comp = '2'
    elif (component == 'z' or component == 3 or component == '3'):
        comp = '3'
    else:
        comp = '1'

    #Initialising int_solidforce_comp as empty arrays:
    int_solidforce_comp = []
    # Get string-array with stat filenames:
    if (statfilename.startswith('statfiles/list_')):
        f = open(statfilename)
        statfiles = f.readlines()
        f.close()
        # Read in the values
        # over all .stat files listed in 'statlistfilename'
        for filename in statfiles:
            filename = filename[0:len(filename) - 1]
            stat = fluidity_tools.stat_parser(filename)
            int_solidforce_comp.extend(
                stat['fluid'][solidname + 'SolidForce%' +
                              str(comp)]['integral'])
    else:
        stat = fluidity_tools.stat_parser(statfilename)
        int_solidforce_comp.extend(stat['fluid'][solidname + 'SolidForce%' +
                                                 str(comp)]['integral'])
    return int_solidforce_comp
示例#23
0
 def pure_J(m_serial, m_shape):
   if verbose:
     print("Running forward model for functional evaluation (<function pure_J>)")
   m = unserialise(m_serial, m_shape)
   run_model(m, opt_options, model_options)
   simulation_name = superspud(model_options, "libspud.get_option('/simulation_name')")
   stat_file = simulation_name+".stat"
   s = stat_parser(stat_file)
   if not functional_name in s:
     print("The functional '", functional_name, "' does not exist in the stat file.")
     print("Check your model configuration")
     exit()
   J = s[functional_name]["value"][-1]
   return J
示例#24
0
def read_solid_volumefraction_from_detector(detfilename, detname):
    """
     reads the solid volume fraction from a detector file 
     and stores it in an one-dimensional vector 'alpha'
     input: is the filename of the detector file,
     and the name of the detector
  """
    #Initialising velocity as an empty array:
    alpha = []
    # Get string-array with stat filenames:
    if (detfilename.startswith('statfiles/list_')):
        f = open(detfilename)
        detfiles = f.readlines()
        f.close()
        for filename in detfiles:
            filename = filename[0:len(filename) - 1]
            detectors = fluidity_tools.stat_parser(filename)
            alpha.extend(detectors['fluid']['SolidConcentration'][detname])
    else:
        # Get volume fraction:
        detectors = fluidity_tools.stat_parser(detfilename)
        alpha = detectors["fluid"]["SolidConcentration"][detname]
    return alpha
示例#25
0
def read_void_df_viscouscomponent_from_stat(statfilename, surfacename, component=1):
  """
     reads the viscous component of the drag force
     from a void body from a .stat file and stores it in
     an one-dimensional array ''
     input: is a file containing a list of .stat files
     in the directory 'statfiles/'
  """
  #Initialising time as an empty array:
  df_vsccmp = []
  # Get string-array with stat filenames:
  if (statfilename.startswith('statfiles/list_')):
    f = open(statfilename)
    statfiles = f.readlines()
    f.close()
    for filename in statfiles:
        filename = filename[0:len(filename)-1]
        stat = fluidity_tools.stat_parser(filename)
        df_vsccmp.extend(stat['fluid']['Velocity']['viscous_force_'+surfacename+'%'+str(component)])
  else:
    stat = fluidity_tools.stat_parser(statfilename)
    df_vsccmp.extend(stat['fluid']['Velocity']['viscous_force_'+surfacename+'%'+str(component)])
  return df_vsccmp
示例#26
0
def read_pressure_from_detector(detfilename, detname):
  """
     reads the pressure from a detector file and stores it in
     an one-dimensional array 'p'
     input: is the filename of the detector file,
     and the name of the detector
  """
  #Initialising pressure as an empty array:
  p = []
  # Get string-array with stat filenames:
  if (detfilename.startswith('statfiles/list_')):
    f = open(detfilename)
    detfiles = f.readlines()
    f.close()
    for filename in detfiles:
        filename = filename[0:len(filename)-1]
        detectors = fluidity_tools.stat_parser(filename)
        p.extend(detectors['fluid']['Pressure'][detname])
  else:
    # Get pressure
    detectors = fluidity_tools.stat_parser(detfilename)
    p = detectors['fluid']['Pressure'][detname]
  return p
示例#27
0
def read_fsi_model_solidvolume_from_stat(statfilename, solidmeshname):
  """
     reads the solidvolume from an immersed body
     (fsi_model) from a .stat file and stores it in
     an one-dimensional array 'solidvolume'
     input: is a file containing a list of .stat files
     in the directory 'statfiles/'
  """
  #Initialising solidvolume as an empty array:
  solidvolume = []
  # Get string-array with stat filenames:
  if (statfilename.startswith('statfiles/list_')):
    f = open(statfilename)
    statfiles = f.readlines()
    f.close()
    for filename in statfiles:
        filename = filename[0:len(filename)-1]
        stat = fluidity_tools.stat_parser(filename)
        solidvolume.extend(stat['VolumeOfSolid_'+str(solidmeshname)]['Value'])
  else:
    stat = fluidity_tools.stat_parser(statfilename)
    solidvolume.extend(stat['VolumeOfSolid_'+str(solidmeshname)]['Value'])
  return solidvolume
示例#28
0
def read_solid_volumefraction_from_detector(detfilename, detname):
  """
     reads the solid volume fraction from a detector file 
     and stores it in an one-dimensional vector 'alpha'
     input: is the filename of the detector file,
     and the name of the detector
  """
  #Initialising velocity as an empty array:
  alpha = []
  # Get string-array with stat filenames:
  if (detfilename.startswith('statfiles/list_')):
    f = open(detfilename)
    detfiles = f.readlines()
    f.close()
    for filename in detfiles:
        filename = filename[0:len(filename)-1]
        detectors = fluidity_tools.stat_parser(filename)
        alpha.extend(detectors['fluid']['SolidConcentration'][detname])
  else:
    # Get volume fraction:
    detectors = fluidity_tools.stat_parser(detfilename)
    alpha = detectors["fluid"]["SolidConcentration"][detname]
  return alpha
示例#29
0
def read_fsi_model_df_from_stat(statfilename, component=1, solidmeshname=''):
  """
     reads the drag force from an immersed body
     (fsi_model) from a .stat file and stores it in
     an one-dimensional array 'df'
     input: is a file containing a list of .stat files
     in the directory 'statfiles/'
  """
  #Initialising df as an empty array:
  df = []
  # Get string-array with stat filenames:
  if (statfilename.startswith('statfiles/list_')):
    f = open(statfilename)
    statfiles = f.readlines()
    f.close()
    for filename in statfiles:
        filename = filename[0:len(filename)-1]
        stat = fluidity_tools.stat_parser(filename)
        df.extend(stat['ForceOnSolid_'+str(solidmeshname)+str(component)]['Value'])
  else:
    stat = fluidity_tools.stat_parser(statfilename)
    df.extend(stat['ForceOnSolid_'+str(solidmeshname)+str(component)]['Value'])
  return df
示例#30
0
def read_pressure_from_detector(detfilename, detname):
    """
     reads the pressure from a detector file and stores it in
     an one-dimensional array 'p'
     input: is the filename of the detector file,
     and the name of the detector
  """
    #Initialising pressure as an empty array:
    p = []
    # Get string-array with stat filenames:
    if (detfilename.startswith('statfiles/list_')):
        f = open(detfilename)
        detfiles = f.readlines()
        f.close()
        for filename in detfiles:
            filename = filename[0:len(filename) - 1]
            detectors = fluidity_tools.stat_parser(filename)
            p.extend(detectors['fluid']['Pressure'][detname])
    else:
        # Get pressure
        detectors = fluidity_tools.stat_parser(detfilename)
        p = detectors['fluid']['Pressure'][detname]
    return p
示例#31
0
def GetstatFiles(directory):
    # gets a list of stat files, accounting for checkpointing
    # in order of first to last (time-wise)
    # also get a time index )time_index_end) for each stat file where
    # statfile_i['ElapsedTime']['value'][index] = statfile_i+1['ElapsedTime']['value'][0]

    time_index_end = []
    stat_files = glob.glob(directory + '*.stat')

    time_end = []
    for sf in stat_files:
        if 'original' in sf: stat_files.remove(sf)
    for sf in stat_files:
        stat = stat_parser(sf)
        time_end.append(stat['ElapsedTime']['value'][-1])
    vals = zip(time_end, stat_files)

    vals.sort(key=key)
    unzip = lambda l: tuple(apply(zip, l))

    time_end, stat_files = unzip(vals)
    for i in range(len(stat_files) - 1):
        stat_0 = stat_parser(stat_files[i])
        time_0 = stat_0['ElapsedTime']['value']
        stat_1 = stat_parser(stat_files[i + 1])
        time_1 = stat_1['ElapsedTime']['value']
        try:
            time_index_end.append(
                numpy.nonzero(
                    numpy.ravel(numpy.array(time_0) >= time_1[0]))[0])
        except IndexError:
            time_index_end.append(len(time_0))

    stat = stat_parser(stat_files[-1])
    time_index_end.append(len(stat['ElapsedTime']['value']))

    return (stat_files, time_index_end)
示例#32
0
def read_num_of_elements_from_stat(statfilename):
  """
     reads the number of elements from a .stat file and stores it in
     an one-dimensional array 'num_elem'
     input: is a file containing a list of .stat files
     in the directory 'statfiles/'
  """
  #Initialising num_elem as an empty array:
  num_elem = []
  # Get string-array with stat filenames:
  if (statfilename.startswith('statfiles/list_')):
    f = open(statfilename)
    statfiles = f.readlines()
    f.close()
    # Read in time values, append them to 'time'
    # over all .stat files listed in 'statlistfilename'
    for filename in statfiles:
        filename = filename[0:len(filename)-1]
        stat = fluidity_tools.stat_parser(filename)
        num_elem.extend(stat['CoordinateMesh']['elements'])
  else:
    stat = fluidity_tools.stat_parser(statfilename)
    num_elem.extend(stat['CoordinateMesh']['elements'])
  return num_elem
示例#33
0
def read_timestep_from_stat(statfilename):
  """
     reads the timestep from a .stat file and stores it in
     an one-dimensional array 'timestep'
     input: is a file containing a list of .stat files
     in the directory 'statfiles/'
  """
  #Initialising timestep as an empty array:
  timestep = []
  # Get string-array with stat filenames:
  if (statfilename.startswith('statfiles/list_')):
    f = open(statfilename)
    statfiles = f.readlines()
    f.close()
    # Read in timestep values, append them to 'timestep'
    # over all .stat files listed in 'statlistfilename'
    for filename in statfiles:
        filename = filename[0:len(filename)-1]
        stat = fluidity_tools.stat_parser(filename)
        timestep.extend(stat['dt']['value'])
  else:
    stat = fluidity_tools.stat_parser(statfilename)
    timestep.extend(stat['dt']['value'])
  return timestep
示例#34
0
def read_walltime_from_stat(statfilename, totalwt=False):
    """
     reads the walltime from a .stat file and stores it in
     an one-dimensional array 'walltime'
     Input: 
      statfilename: String of the statfile
      totalwt: locigal, if True, the overall walltime is computed
        otherwise the walltime of each timestep is given back.
     
  """
    #Initialising walltime as an empty array:
    walltime = []
    walltime_tmp = []
    # Get string-array with stat filenames:
    if (statfilename.startswith('statfiles/list_')):
        f = open(statfilename)
        statfiles = f.readlines()
        f.close()
        # Read in time values, append them to 'time'
        # over all .stat files listed in 'statlistfilename'
        for filename in statfiles:
            filename = filename[0:len(filename) - 1]
            stat = fluidity_tools.stat_parser(filename)
            if (totalwt):
                # if totalwt == True, then compute the total walltime
                # of all (checkpointed) statfiles
                walltime_tmp = stat['ElapsedWallTime']['value']
                if (walltime):
                    walltime_tmp = walltime_tmp + walltime[-1]
                walltime.extend(walltime_tmp)
            else:
                walltime.extend(stat['ElapsedWallTime']['value'])
    else:
        stat = fluidity_tools.stat_parser(statfilename)
        walltime.extend(stat['ElapsedWallTime']['value'])
    return walltime
示例#35
0
def run_test(layers, binary):
    '''run_test(layers, binary)

    Run a single test of the channel problem. Layers is the number of mesh
    points in the cross-channel direction. The mesh is unstructured and
    isotropic. binary is a string containing the fluidity command to run.
    The return value is the error in u and p at the end of the simulation.'''

    generate_meshfile("channel", layers)

    os.system(binary + " channel_viscous.flml")

    s = stat_parser("channel-flow-dg.stat")
    return (s["Water"]['AnalyticUVelocitySolutionError']['l2norm'][-1],
            s["Water"]['AnalyticPressureSolutionError']['l2norm'][-1])
def run_test(layers, binary):
    '''run_test(layers, binary)

    Run a single test of the channel problem. Layers is the number of mesh
    points in the cross-channel direction. The mesh is unstructured and
    isotropic. binary is a string containing the fluidity command to run.
    The return value is the error in u and p at the end of the simulation.'''

    generate_meshfile("channel",layers)

    os.system(binary+" channel_viscous.flml")

    s=stat_parser("channel-flow-dg.stat")
    return (s["Water"]['AnalyticUVelocitySolutionError']['l2norm'][-1],
        s["Water"]['AnalyticPressureSolutionError']['l2norm'][-1])
示例#37
0
def read_num_of_elements_from_stat(statfilename):
    """
     reads the number of elements from a .stat file and stores it in
     an one-dimensional array 'num_elem'
     input: is a file containing a list of .stat files
     in the directory 'statfiles/'
  """
    #Initialising num_elem as an empty array:
    num_elem = []
    # Get string-array with stat filenames:
    if (statfilename.startswith('statfiles/list_')):
        f = open(statfilename)
        statfiles = f.readlines()
        f.close()
        # Read in time values, append them to 'time'
        # over all .stat files listed in 'statlistfilename'
        for filename in statfiles:
            filename = filename[0:len(filename) - 1]
            stat = fluidity_tools.stat_parser(filename)
            num_elem.extend(stat['CoordinateMesh']['elements'])
    else:
        stat = fluidity_tools.stat_parser(statfilename)
        num_elem.extend(stat['CoordinateMesh']['elements'])
    return num_elem
示例#38
0
def read_timestep_from_stat(statfilename):
    """
     reads the timestep from a .stat file and stores it in
     an one-dimensional array 'timestep'
     input: is a file containing a list of .stat files
     in the directory 'statfiles/'
  """
    #Initialising timestep as an empty array:
    timestep = []
    # Get string-array with stat filenames:
    if (statfilename.startswith('statfiles/list_')):
        f = open(statfilename)
        statfiles = f.readlines()
        f.close()
        # Read in timestep values, append them to 'timestep'
        # over all .stat files listed in 'statlistfilename'
        for filename in statfiles:
            filename = filename[0:len(filename) - 1]
            stat = fluidity_tools.stat_parser(filename)
            timestep.extend(stat['dt']['value'])
    else:
        stat = fluidity_tools.stat_parser(statfilename)
        timestep.extend(stat['dt']['value'])
    return timestep
示例#39
0
 def pure_J(m_serial, m_shape):
     if verbose:
         print "Running forward model for functional evaluation (<function pure_J>)"
     m = unserialise(m_serial, m_shape)
     run_model(m, opt_options, model_options)
     simulation_name = superspud(model_options,
                                 "libspud.get_option('/simulation_name')")
     stat_file = simulation_name + ".stat"
     s = stat_parser(stat_file)
     if not functional_name in s:
         print "The functional '", functional_name, "' does not exist in the stat file."
         print "Check your model configuration"
         exit()
     J = s[functional_name]["value"][-1]
     return J
示例#40
0
def mixing_stats():

  pylab.figure(num=2, figsize = (16.5, 11.5))
  pylab.suptitle('Mixing')
   
  times = []
  mixing_stats_lower = [] 
  mixing_stats_mixed = []
  mixing_stats_upper = []
  
  
  stat_files, time_index_end = le_tools.GetstatFiles('./')
  for sf in stat_files:
    stat = stat_parser(sf)
    for i in range(time_index_end[pylab.find(numpy.array(stat_files) == sf)]):
      times.append(stat['ElapsedTime']['value'][i])
      mixing_stats_lower.append(stat['fluid']['Temperature']['mixing_bins%cv_normalised'][0][i])
      mixing_stats_mixed.append(stat['fluid']['Temperature']['mixing_bins%cv_normalised'][1][i])
      mixing_stats_upper.append(stat['fluid']['Temperature']['mixing_bins%cv_normalised'][2][i])
  
  pylab.plot(times,mixing_stats_lower, label = 'T < -0.4')
  pylab.plot(times,mixing_stats_mixed, label = '-0.4 < T < 0.4')
  pylab.plot(times,mixing_stats_upper, label = '0.4 < T')
  
  time = le_tools.ReadLog('diagnostics/logs/time.log')
  X_ns = [x-0.4 for x in le_tools.ReadLog('diagnostics/logs/X_ns.log')]
  X_fs = [0.4-x for x in le_tools.ReadLog('diagnostics/logs/X_fs.log')]
  try:
    index = pylab.find(numpy.array(X_ns)<0.4-1E-3)[-1]
    pylab.fill_between([time[index],time[index+1]],[0,0],[0.5,0.5], color = '0.3') 
    index = pylab.find(numpy.array(X_fs)<0.4-1E-3)[-1]
    pylab.fill_between([time[index],time[index+1]],[0,0],[0.5,0.5], color = '0.6')
  except IndexError: 
    print 'not plotting shaded regions on mixing plot as front has not reached end wall'
  
  
  pylab.axis([0,times[-1],0,0.5])
  pylab.grid("True")
  pylab.legend(loc=0)
  pylab.text(times[-1]-(times[-1]/5), 0.005, 'shaded regions show when \nfronts near the end wall \ndark: free-slip, light: no-slip', bbox=dict(facecolor='white', edgecolor='black'))
  pylab.xlabel('time (s)')
  pylab.ylabel('domain fraction')
  
  pylab.savefig('diagnostics/plots/mixing.png')

  return
示例#41
0
def readstat():
    s = stat_parser("lagrangian_detectors.detectors")

    last_locations_error = zeros((2,100))
    for i in range(100):
        n = i + 1
        padding = ''
        if(n<100):
            padding = '0'
            if(n<10):
                padding ='00'
        last_locations_error[0,i] = s['Steve_'+padding+str(n)]['position'][0][-1]
        last_locations_error[1,i] = s['Steve_'+padding+str(n)]['position'][1][-1]
    X = fromfile('Xvals.txt',sep=' ')
    Y = fromfile('Yvals.txt',sep=' ')
    last_locations_error[0,:] = last_locations_error[0,:] - X
    last_locations_error[1,:] = last_locations_error[1,:] - Y
    return last_locations_error
def get_time_integrated_fs_error(filename):

    s = stat_parser(filename)
    # one wave lasts 1/((8*9.81*50/(430620*430620))^0.5)*2*pi=43193 seconds.

    timesteps = s["ElapsedTime"]["value"]
    timestep = timesteps[1] - timesteps[0]
    print "Found ", len(timesteps), " timesteps with dt=", timestep
    if timesteps[-1] < 43193:
        print 'Simulation must run for at least 43193s'
        exit()
    lastindex = int(ceil(43193.0 / float(timestep)))
    print 'But only the first ', lastindex, ' are considered for the error integration.'
    print ''

    print 'Integrating errors over time...'

    l2error = s["water"]["fs_error_abs"]["l2norm"]
    timel2error = l2error[0] + l2error[lastindex - 1]
    timel2error = timel2error / 2
    for i in range(1, lastindex - 1):
        timel2error = timel2error + l2error[i]
    timel2error = timel2error * timestep
    print "FreeSurface - Time integrated l2error: ", timel2error

    l1error = s["water"]["fs_error_abs"]["integral"]
    timel1error = l1error[0] + l1error[lastindex - 1]
    timel1error = timel1error / 2
    for i in range(1, lastindex - 1):
        timel1error = timel1error + l1error[i]
    timel1error = timel1error * timestep
    print "FreeSurface - Time integrated l1error: ", timel1error

    Inferror = s["water"]["fs_error_abs"]["max"]
    timeInferror = Inferror[0] + Inferror[lastindex - 1]
    timeInferror = timeInferror / 2
    for i in range(1, lastindex - 1):
        timeInferror = timeInferror + Inferror[i]
    timeInferror = timeInferror * timestep
    print "FreeSurface - Time integrated Inf Error: ", timeInferror

    print "Done"
    return [timel1error, timel2error, timeInferror]
示例#43
0
def readstat_3d():
    s = stat_parser("lagrangian_detectors.detectors")

    num_detectors = 100
    zfill_length  = int(len(str(num_detectors)))
    array_name    = "Steve_"
    last_locations_error = zeros((3,num_detectors))
    
    for i in range(num_detectors):
        n = i + 1
        last_locations_error[0,i] = s[array_name+str(n).zfill(zfill_length)]['position'][0][-1]
        last_locations_error[1,i] = s[array_name+str(n).zfill(zfill_length)]['position'][1][-1]
        last_locations_error[2,i] = s[array_name+str(n).zfill(zfill_length)]['position'][2][-1]
    X = fromfile('Xvals.txt',sep=' ')
    Y = fromfile('Yvals.txt',sep=' ')
    Z = 0.5*ones(shape(X))
    last_locations_error[0,:] = last_locations_error[0,:] - X
    last_locations_error[1,:] = last_locations_error[1,:] - Y
    last_locations_error[2,:] = last_locations_error[2,:] - Z 
    return last_locations_error
示例#44
0
def readstat():
    s = stat_parser("lagrangian_detectors.detectors")

    last_locations_error = zeros((2, 100))
    for i in range(100):
        n = i + 1
        padding = ''
        if (n < 100):
            padding = '0'
            if (n < 10):
                padding = '00'
        last_locations_error[0, i] = s['Steve_' + padding +
                                       str(n)]['position'][0][-1]
        last_locations_error[1, i] = s['Steve_' + padding +
                                       str(n)]['position'][1][-1]
    X = fromfile('Xvals.txt', sep=' ')
    Y = fromfile('Yvals.txt', sep=' ')
    last_locations_error[0, :] = last_locations_error[0, :] - X
    last_locations_error[1, :] = last_locations_error[1, :] - Y
    return last_locations_error
def retrieve_results(layers):
    '''retrieve_results(layers)

    For each layer count in the sequence layers, retrieve the velocity and
    pressure error from the simulation results in appropriate channel-n
    directory.

    The first column of the result is the l2 norm of the error in the u
    component of velocity. The second is the l2 norm in the pressure.
    '''
    from numpy import zeros

    error=zeros((len(layers),2))

    for i,layer in enumerate(layers):
        s=stat_parser("channel-%d/rotating_channel.stat"%layer)

        error[i,0]=s["Water"]['AnalyticUVelocitySolutionError']['l2norm'][-1]
        error[i,1]=s["Water"]['AnalyticPressureSolutionError']['l2norm'][-1]
    
    return error
示例#46
0
 def pure_dJdm(m_serial, m_shape):
   if verbose:
     print("Running forward/adjoint model for functional derivative evaluation (<function pure_dJdm>)")
   m = unserialise(m_serial, m_shape)
   run_model(m, opt_options, model_options)
   # While computing dJdm we run the forward/adjoint model and in particular we compute the 
   # functional values. In order to not compute the functional values again when calling 
   # J, we manually add write it into the memoize cache.
   simulation_name = superspud(model_options, "libspud.get_option('/simulation_name')")
   stat_file = simulation_name+".stat"
   J = stat_parser(stat_file)[functional_name]["value"][-1]
   # Add the functional value the memJ's cache
   mem_pure_J.__add__(J, m_serial, m_shape)
   # Now get the functional derivative information
   djdm = read_control_derivatives(opt_options, model_options)
   check_control_consistency(m, djdm, m_bounds)
   # Serialise djdm in the same order than m_serial
   djdm_serial = [] 
   for k, v in sorted(m_shape.items()):
     djdm_serial = numpy.append(djdm_serial, djdm[k])
   return djdm_serial
示例#47
0
 def pure_dJdm(m_serial, m_shape):
     if verbose:
         print "Running forward/adjoint model for functional derivative evaluation (<function pure_dJdm>)"
     m = unserialise(m_serial, m_shape)
     run_model(m, opt_options, model_options)
     # While computing dJdm we run the forward/adjoint model and in particular we compute the
     # functional values. In order to not compute the functional values again when calling
     # J, we manually add write it into the memoize cache.
     simulation_name = superspud(model_options,
                                 "libspud.get_option('/simulation_name')")
     stat_file = simulation_name + ".stat"
     J = stat_parser(stat_file)[functional_name]["value"][-1]
     # Add the functional value the memJ's cache
     mem_pure_J.__add__(J, m_serial, m_shape)
     # Now get the functional derivative information
     djdm = read_control_derivatives(opt_options, model_options)
     check_control_consistency(m, djdm, m_bounds)
     # Serialise djdm in the same order than m_serial
     djdm_serial = []
     for k, v in sorted(m_shape.items()):
         djdm_serial = numpy.append(djdm_serial, djdm[k])
     return djdm_serial
示例#48
0
def retrieve_results(layers):
    '''retrieve_results(layers)

    For each layer count in the sequence layers, retrieve the velocity and
    pressure error from the simulation results in appropriate channel-n
    directory.

    The first column of the result is the l2 norm of the error in the u
    component of velocity. The second is the l2 norm in the pressure.
    '''
    from numpy import zeros

    error = zeros((len(layers), 2))

    for i, layer in enumerate(layers):
        s = stat_parser("channel-%d/rotating_channel.stat" % layer)

        error[i,
              0] = s["Water"]['AnalyticUVelocitySolutionError']['l2norm'][-1]
        error[i, 1] = s["Water"]['AnalyticPressureSolutionError']['l2norm'][-1]

    return error
示例#49
0
import numpy as np
import matplotlib  as mpl
mpl.use('ps')
import matplotlib.pyplot as plt

#label = sys.argv[1]
#basename = sys.argv[2]


path0 = path1 = path2 = '../RST/stat_files/'
path2b = '/scratch/jmensa/m_10_1/'

#
file0 = 'm_50_6f.stat'
filepath0 = path0+file0
stat0 = fluidity_tools.stat_parser(filepath0)

file1 = 'm_25_1.stat'
filepath1 = path1+file1
stat1 = fluidity_tools.stat_parser(filepath1)

file2 = 'm_10_1.stat'
filepath2 = path2+file2
stat2 = fluidity_tools.stat_parser(filepath2)

file2b = 'mli_checkpoint.stat'
filepath2b = path2b+file2b
stat2b = fluidity_tools.stat_parser(filepath2b)

#file1 = 'ring.stat'
#filepath1 = path1+file1
示例#50
0
def main(argv=None):

        Rmesh=440000
        filename=''
        csvbasename=''
        timestep_ana=0.0
        dzero=0.8
        save='' # If nonempty, we save the plots as images instead if showing them
        handoffset=2.7

        global debug
        debug=False
        debug=True  
        verbose=False
        verbose_timestep=-1

        try:                                
                opts, args = getopt.getopt(sys.argv[1:], "t:h:", ['file=','csv=','save='])
        except getopt.GetoptError:  
                print "Getopterror :("
                usage()                     
                sys.exit(2)                     
        for opt, arg in opts:                
                if opt == '--file':      
                        filename=arg
                elif opt == '--csv':      
                        csvbasename=arg
                elif opt == '--save':
                        save=arg
                elif opt == '-t':
                        verbose_timestep=int(arg)
                elif opt == '-h' or opt == '--help':
                    usage()                     
                    sys.exit(2) 
        if filename=='':
                print 'No filename specified. You have to give the detectors filename.'
                usage()   
                sys.exit(2) 

        
        ####################### Print time plot  ###########################
        print 'Generating time plot'
              
        s = stat_parser(filename)

        timesteps=s["ElapsedTime"]["value"]
        timestep=timesteps[1]-timesteps[0]
        print "Found ", len(timesteps), " timesteps with dt=", timestep
        if timestep_ana==0.0:
                timestep_ana=timestep


        fs=s["water"]["FreeSurface"]
        print "Found ", len(fs), " detectors. We assume they are equidistant distributed over the domain (", -Rmesh, "-", Rmesh, ")."


        # Get and plot results
        plt.ion() # swith on interactive mode
        fig2 = figure()
        ax2 = fig2.add_subplot(111)

        for t in range(0,len(timesteps)):
                if verbose_timestep>-1 and verbose_timestep!=t:
                        continue
                #if not t%10==0:
                #        continue
                fsvalues=[]
                xcoords=[]
                # check if we want to use detector (or vtu probe) data
                if csvbasename=='':
                        minfs=1000
                        for name, item in fs.iteritems():
                                xcoords.append(s[name]['position'][0][0])
                                
                                fsvalues.append(fs[name][t])
                                # alternativly: Probe data with vtktools:
                                # d0=1.0
                                # fsvalues.append(probe_fs(filename, [xcoords[-1],0, -bathymetry_function([xcoords[-1],0])+d0/2], t))

                                print 'Time: ', t, ', Name: ',name, ', X-Coord: ', s[name]['position'][0][0], ', FS: ', fs[name][t]
                                if minfs>fs[name][t]:
                                        minfs=fs[name][t]
                        print 'Minfs: ', minfs

                        # sort coords and values 
                        temp=[]
                        for i in range(0,len(xcoords)):
                                temp.append([xcoords[i], fsvalues[i]])
                        temp.sort()
                        xcoords=[]
                        fsvalues=[]
                        for i in range(0,len(temp)):
                                xcoords.append(temp[i][0])
                                fsvalues.append(temp[i][1])

                        # Plot result of one timestep
                        ax2.plot(xcoords,fsvalues,'r.', label='Numerical solution')
                        plt.ylim(-10,0)

                # use csv data
                else:
                        csvreader=csv.reader(open(csvbasename+'.'+str(t)+'.csv', 'rb'), delimiter=',', quotechar='|')
                        firstrow=True
                        fs_id=-1
                        pos_x_id=-1
                        pos_y_id=-1
                        # get indices
                        for row in csvreader:
                                if firstrow:
                                        firstrow=False
                                        for i in range(0,len(row)):
                                                if row[i]=='"FreeSurface"':
                                                        fs_id=i
                                                elif row[i]=='"Points:0"':
                                                        pos_x_id=i
                                                elif row[i]=='"Points:1"':
                                                        pos_y_id=i
                                        assert(fs_id>=0 and pos_x_id>=0 and pos_y_id>=0)        
                                        continue
                                if abs(float(row[pos_y_id]))>=1e-5:
                                        print 'You didnt save the csv file on a slice on the x axis!'
                                        exit()
                                xcoords.append(float(row[pos_x_id]))
                                fsvalues.append(float(row[fs_id])+handoffset)

                        # sort coords and values 
                        temp=[]
                        for i in range(0,len(xcoords)):
                                temp.append([xcoords[i], fsvalues[i]])
                        temp.sort()
                        xcoords=[]
                        fsvalues=[]
                        for i in range(0,len(temp)):
                                xcoords.append(temp[i][0]/1000) # in km
                                fsvalues.append(temp[i][1])
                        # Plot result of one timestep
                        ax2.plot(xcoords,fsvalues, label='Numerical solution', linestyle='--')
                        plt.ylim(-10,0)



                
                # Plot Analytical solution
                fsvalues_ana=[]
                xcoords=[]
                        
                offset=-bathymetry_function([0.0,0.0])+50.0+dzero

                for i in range(-250,250): # number of points for the analytical solution
                        xcoords.append(Rmesh*float(i)/250/1000) # in km
                        fsvalues_ana.append(analytic_solution(xcoords[-1]*1000, t*timestep_ana)+offset+handoffset)

                ax2.plot(xcoords, fsvalues_ana, label='Analytical solution', linestyle='-')
                #       plt.ylim(-10,0)

                       # plt.title('d_min=2.5m, Time='+ str(t*timestep)+'s')
                plt.xlabel('Position [km]')
                plt.ylabel('Free surface [m]')
                plt.legend(loc='lower center')

                if verbose:
                        print 'Current time: ', timesteps[t]
                        print 'Numerical position at domain center: ', fsvalues[len(fs)/2]
                        print 'Error in the domain center: ', abs(fsvalues_ana[len(fs)/2]-fsvalues[len(fs)/2])
                        deltax=Rmesh/(len(fs)-1)
                        integral=0.0
                        for i in range(0,len(xcoords)):
                                integral=integral+abs(fsvalues_ana[i]-fsvalues[i])
                        integral=integral-fsvalues_ana[0]/2-fsvalues_ana[len(xcoords)-1]/2
                        integral=integral*deltax
                        print 'Integral error: ', integral
                        exit()

                if save=='':
                        plt.draw()
                        raw_input("Please press Enter")
                else:
                        plt.savefig(save+'_'+str(100000+t+1)+'.pdf', facecolor='white', edgecolor='black', dpi=100)
                plt.cla()
                t=t+1
        if verbose:
                print 'Ups, program ended unexpected. Are you sure you specified the correct time for the -v argument?'
示例#51
0
#code to quantify errors
# Analyse and know what are the reasons the error is propogaing  
########################################################################################################################################################################################################

CANNOT WORK !!!!!!!!!!!!! AS THE ELAPSED TIME VALUES ARE DIFFERENT FOR ALL CAESES................ 
BUT THERE IS WAY USING RANGE AND GETTING SPECIFIC VALUES AT SPECIFIC INTERVALS........ LITTLE BIT OF LOGIC NOTHING ELSE ........
TRY IT OUT LATER 

########################################################################################################################################################################################################
import fluidity_tools
import os 
import matplotlib.pyplot as plt
stat1 = fluidity_tools.stat_parser("PV_05_TS-2/popbal_nhomog3D.stat")
stat2 = fluidity_tools.stat_parser("PV_min_TS-3/popbal_nhomog3D.stat")
stat3 = fluidity_tools.stat_parser("PV_min_TS-4/popbal_nhomog3D.stat")
stat4 = fluidity_tools.stat_parser("PV_min_TS-5/popbal_nhomog3D.stat")
#first graph
T_2_m0 = stat1["fluid"]["diff_m0"]["l2norm"]
T_3_m0 = stat2["fluid"]["diff_m0"]["l2norm"]
T_4_m0 = stat3["fluid"]["diff_m0"]["l2norm"]
T_5_m0 = stat4["fluid"]["diff_m0"]["l2norm"]
# Second graph 
T_2_m1 = stat1["fluid"]["diff_m1"]["l2norm"]
T_3_m1 = stat2["fluid"]["diff_m1"]["l2norm"]
T_4_m1 = stat3["fluid"]["diff_m1"]["l2norm"]
T_5_m1 = stat4["fluid"]["diff_m1"]["l2norm"]
# Third Graph
T_2_m2 = stat1["fluid"]["diff_m2"]["l2norm"]
T_3_m2 = stat2["fluid"]["diff_m2"]["l2norm"]
T_4_m2 = stat3["fluid"]["diff_m2"]["l2norm"]
T_5_m2 = stat4["fluid"]["diff_m2"]["l2norm"]
示例#52
0
def xforce_stat(sf):
    stat = fluidity_tools.stat_parser(sf)
    time_avg_xforce = pylab.average(stat["0"]["Velocity"]["force%1"][-20:])
    return time_avg_xforce
def bruneau_sf(NN):
#Bruneau and Saad 2006. Table 2. 
  streamfunction_min = stat_parser('driven_cavity-%d/driven_cavity.stat'%NN)['Fluid']['MultiplyConnectedStreamFunction']['min'][-1]
  streamfunction_min_error = abs( streamfunction_min - -0.11892 )
  print "streamfunction_min_error:", streamfunction_min_error
  return streamfunction_min_error
示例#54
0
## This Python script searches through the current directory, loads the maximum Tephra::Velocity values
## from the .stat file, and then prints out the results in a .pdf file.

from fluidity_tools import stat_parser
import matplotlib
matplotlib.use('pdf')
import pylab
import numpy
import os

# List the contents of the current directory
dir_list = os.listdir(".")
# If the stat file exists, then read from it
if("tephra_settling.stat" in dir_list):
   s = stat_parser("tephra_settling.stat")
   time = s["ElapsedTime"]["value"]
   tephra_u_max = s["Tephra"]["Velocity%magnitude"]["max"]

   pylab.plot(time, tephra_u_max, label='Numerical results')

   # Print it all out as a pretty picture
   pylab.xlabel('Time (s)')
   pylab.ylabel('Maximum tephra velocity (m/s)')
   pylab.legend(loc=2)

   pylab.savefig('tephra_velocity.pdf')
   
   print "Data plotted and saved in tephra_velocity.pdf"
else:
   print "No .stat file found - cannot plot data."
   
示例#55
0
def main(argv=None):

    filename = ''
    timestep_ana = 0.0
    dzero = 0.01
    save = ''  # If nonempty, we save the plots as images instead if showing them
    wetting = False

    try:
        opts, args = getopt.getopt(sys.argv[1:], ":w", ['file=', 'save='])
    except getopt.GetoptError:
        usage()
        sys.exit(2)
    for opt, arg in opts:
        if opt == '--file':
            filename = arg
        elif opt == '--save':
            save = arg
        elif opt == '-w':
            wetting = True
    if filename == '':
        print(
            'No filename specified. You have to give the detectors filename.')
        usage()
        sys.exit(2)

    ####################### Print time plot  ###########################
    print('Generating time plot')

    s = stat_parser(filename)

    timesteps = s["ElapsedTime"]["value"]
    timestep = timesteps[1] - timesteps[0]
    print("Found ", len(timesteps), " timesteps with dt=", timestep)
    if timestep_ana == 0.0:
        timestep_ana = timestep

    fs = s["water"]["FreeSurface"]
    print(
        "Found ", len(fs),
        " detectors. We assume they are equidistant distributed over the domain (",
        0, "-", 13800, ").")

    # Get and plot results
    plt.ion()  # swith on interactive mode
    fig2 = figure()
    ax2 = fig2.add_subplot(111)

    if wetting:
        ##plot_start=90 # in timesteps
        plot_start = 22  # in timesteps, after 18 timesteps the waterlevel reaches its lowest point
        ##plot_end=114 # in timesteps
        plot_end = 54  # in timesteps
        plot_name = 'Wetting'
    else:
        plot_start = 54  # in timesteps
        plot_end = 90  # in timesteps
        plot_name = 'Drying'

    for t in range(0, len(timesteps)):
        # ignore the first waveperiod
        if t < plot_start:
            continue
        if t > plot_end:
            continue
        fsvalues = []
        xcoords = []
        for name, item in fs.iteritems():
            #print name
            xcoords.append(mirror(s[name]['position'][0][0]))
            #print xcoord
            fsvalues.append(fs[name][t])

        # Plot result of one timestep
        ax2.plot(xcoords, fsvalues, 'r,', label='Numerical solution')

        # Plot Analytical solution
        fsvalues_ana = []

        offset = -bathymetry_function(0.0) + dzero

        xcoords.sort()
        for x in xcoords:
            fsvalues_ana.append(bathymetry_function(mirror(x)) - offset)

        # Plot vertical line in bathmetry on right boundary
        xcoords.append(xcoords[len(xcoords) - 1] + 0.000000001)
        fsvalues_ana.append(2.1)

        ax2.plot(xcoords, fsvalues_ana, 'k', label='Bathymetry')

        #plt.legend()
        if t == plot_end:
            plt.ylim(-2.2, 1.4)
            # change from meters in kilometers in the x-axis
            # return locs, labels where locs is an array of tick locations and
            # labels is an array of tick labels.
            locs, labels = plt.xticks()
            for i in range(0, len(locs)):
                labels[i] = str(locs[i] / 1000)
            plt.xticks(locs, labels)

            #plt.title(plot_name)
            plt.xlabel('Position [km]')
            plt.ylabel('Free surface [m]')

            if save == '':
                plt.draw()
                raw_input("Please press Enter")
            else:
                plt.savefig(save + '_' + plot_name + '.pdf',
                            facecolor='white',
                            edgecolor='black',
                            dpi=100)
            plt.cla()
        t = t + 1
示例#56
0
def mixing(flmlname):

  print "\n********** Calculating the mixing diagnostics\n"
  # warn user about assumptions
  print "Background potential energy calculations makes two assumptions: \n i) domain height = 0.1m \n ii) initial temperature difference is 1.0 degC"
  domainheight = 0.1
  rho_zero, T_zero, alpha, g = le_tools.Getconstantsfromflml(flmlname)

  # get mixing bin bounds and remove lower bound (=-\infty)
  bounds = le_tools.Getmixingbinboundsfromflml(flmlname)[1:]

  # find indicies of selected bounds for plotting
  index_plot = []
  for b in [-0.5,-0.25, 0.0,0.25,0.5]:
    index_plot.append(pylab.find(numpy.array([abs(val - b) for val in bounds]) < 1E-6)[0]) 
  
  time = []
  volume_fraction = []
  reference_state = []
  bpe = [] 
  
  # get stat files 
  # time_index_end used to ensure don't repeat values
  stat_files, time_index_end = le_tools.GetstatFiles('./')
  for i in range(len(stat_files)):
    stat = stat_parser(stat_files[i])
    for j in range(time_index_end[i]):
      time.append(stat['ElapsedTime']['value'][j])
      bins = stat['fluid']['Temperature']['mixing_bins%cv_normalised'][:,j]
      # rearrange bins so have nobins = nobounds -1
      # amounts to including any undershoot or overshoots in lower/upper most bin
      # for discussion of impacts see H. Hiester, PhD thesis (2011), chapter 4.
      bins[1] = bins[0]+bins[1]
      bins[-2] = bins[-2]+bins[-1]
      bins = bins[1:-1]
      
      # sum up bins for plot
      volume_fraction.append(tuple([sum(bins[index_plot[k]:index_plot[k+1]]) for k in range(len(index_plot)-1)]))
      
      # get reference state using method of Tseng and Ferziger 2001
      Abins = sum([bins[k]*(bounds[k+1]-bounds[k]) for k in range(len(bins))])
      pdf = [val/Abins for val in bins]
      rs = [0]
      for k in range(len(pdf)): rs.append(rs[-1]+(domainheight*pdf[k]*(bounds[k+1]-bounds[k])))
      reference_state.append(tuple(rs))
      
      # get background potential energy, 
      # noting \rho = \rho_zero(1-\alpha(T-T_zero))
      # and reference state is based on temperature
      # bpe_bckgd = 0.5*(g*rho_zero*(1.0+(alpha*T_zero)))*(domainheight**2)
      # but don't include this as will look at difference over time
      bpe.append(-rho_zero*alpha*g*scipy.integrate.trapz(x=reference_state[-1],y=[bounds[j]*reference_state[-1][j] for j in range(len(reference_state[-1]))]))
  
  volume_fraction = numpy.array(volume_fraction)
  reference_state = numpy.array(reference_state)
  
  bpe_zero = bpe[0]
  bpe = [val - bpe_zero for val in bpe]

  # plot
  fs = 18
  pylab.figure(num=2, figsize = (16.5, 11.5))
  pylab.suptitle('Mixing', fontsize = fs)
  
  # volume fraction
  pylab.subplot(221)
  pylab.plot(time,volume_fraction[:,0], label = '$T < -0.25$', color = 'k')
  pylab.plot(time,volume_fraction[:,1], label = '$-0.25 < T < 0.0$', color = 'g')
  pylab.plot(time,volume_fraction[:,2], label = '$0.0 < T < 0.25$', color = 'b')
  pylab.plot(time,volume_fraction[:,3], label = '$0.25 < T$', color = '0.5')
  
  pylab.axis([0,time[-1],0,0.5])
  pylab.legend(loc = 0)
  pylab.grid('on')
  pylab.xlabel('$t$ (s)', fontsize = fs)
  pylab.ylabel('$V/|\\Omega|$', fontsize = fs)
  pylab.title('Volume fraction', fontsize = fs) 
  
  # reference state contours
  pylab.subplot(222)
  for i in index_plot: pylab.plot(time, reference_state[:,i],  color = 'k')
  pylab.text(time[-1]/100, 1.5E-3, 'From bottom to top contours correspond to values \n $T = -0.5, \, -0.25, \, 0.0, \, 0.25, \, 0.5$ \nwhere the values for $T=-0.5$ and $0.5$ take the values\n$z_* = 0.0$ and $0.1$ respectively', bbox=dict(facecolor='white', edgecolor='black'))
  pylab.axis([0,time[-1],0,domainheight])
  pylab.grid('on')
  pylab.xlabel('$t$ (s)', fontsize = fs)
  pylab.ylabel('$z_*$ (m)', fontsize = fs)
  pylab.title('Reference state', fontsize = fs) 
  
  pylab.subplot(223)
  pylab.plot(bounds, reference_state[-1], color = 'k')
  pylab.grid('on')
  pylab.axis([-0.5,0.5,0,domainheight])
  pylab.xlabel('$T$ ($^\\circ$C)', fontsize = fs)
  pylab.ylabel('$z_*$ (m)', fontsize = fs)
  pylab.title('Reference state at $t='+str(time[-1])+'\\,$s', fontsize = fs) 
  
  pylab.subplot(224)
  pylab.plot(time, bpe, color = 'k')
  pylab.grid('on')
  pylab.gca().get_xaxis().get_axes().set_xlim(0.0,time[-1])
  pylab.xlabel('$t$ (s)', fontsize = fs)
  pylab.ylabel('$\\Delta E_b$', fontsize = fs-2)
  pylab.gca().get_yaxis().set_major_formatter(pylab.FormatStrFormatter('%1.1e'))
  pylab.title('Background potential energy', fontsize = fs) 
  
  pylab.savefig('diagnostics/plots/mixing.png')
  return
mpl.use('ps')
import matplotlib.pyplot as plt
import spectrum

label = sys.argv[1]
basename = sys.argv[2]

path = '/tamay2/mensa/fluidity/'+label+'/'

try: os.stat('./plot/'+label)
except OSError: os.mkdir('./plot/'+label)

#
file0 = basename+'.stat'
filepath0 = path+file0
stat0 = fluidity_tools.stat_parser(filepath0)

#file1 = 'mli_checkpoint.stat'
#filepath1 = path+file1
#stat1 = fluidity_tools.stat_parser(filepath1)

time0 = stat0["ElapsedTime"]["value"]/86400.0
#time1 = stat1["ElapsedTime"]["value"]/86400.0

KE0 = 0.5*np.sqrt(stat0["BoussinesqFluid"]["Velocity_CG%3"]["l2norm"])

print len(KE0[1:len(KE0)])
pwd = KE0[500:1524]
print len(pwd)

p = spectrum.Periodogram(pwd, sampling=1024, window='hann', NFFT=None, scale_by_freq=False, detrend=True)
import myfun
import numpy as np
import pyvtk
import vtktools
import copy
import os 

exp = 'm_250_8c_h1'
filename = '/nethome/jmensa/fluidity-exp/'+exp+'/mli_checkpoint.detectors'
day = '40'

try: os.stat('./plot/'+exp)
except OSError: os.mkdir('./plot/'+exp)

print 'reading detectors'
det = fluidity_tools.stat_parser(filename)
keys = det.keys()				 # particles
print 'done.' 

tt = 80
pt = 450000
step = 1

# dimensions particles

lat = 15000
lon = 7500
depth = -50

nlat = 100
nlon = 100
示例#59
0
# need for extraction from the vtus
for p in range(len(parray)):
    pylab.figure(p + len(xarray))
    pylab.title(parray[p] + ' pressure gauge')
    pylab.xlabel('Time (s)')
    pylab.ylabel('Pressure (Pa)')
    if (parray[p] == "P2"):
        experiment = numpy.load(parray[p] + ".npy")
        pylab.plot(experiment[:, 0],
                   experiment[:, 1],
                   marker='o',
                   markerfacecolor='white',
                   markersize=6,
                   markeredgecolor='black',
                   linestyle="None")

results = fluidity_tools.stat_parser("water_collapse.detectors")
time = results["ElapsedTime"]["value"]
for p in range(len(parray)):
    pylab.figure(p + len(xarray))
    data = results["Water"]["Pressure"][parray[p]]
    pylab.plot(time, data, color='black', linestyle="dashed")

for p in range(len(parray)):
    pylab.figure(p + len(xarray))
    pylab.axis([0.0, 2.5, -2000., 12000.])
    pylab.legend(("Experiment", "Fluidity"), loc="upper left")
    pylab.savefig("pressure_gauge_" + parray[p] + ".pdf")

pylab.show()
示例#60
0
    print str(warray[x]), "TOL=", TOLERANCE_H, ", ERROR=", abs(
        numpy.std(
            numpy.array(experiment[:, 2]) - numpy.array(results[:, 2 + x])))
    H_check = abs(
        numpy.std(
            numpy.array(experiment[:, 2]) -
            numpy.array(results[:, 2 + x]))) < TOLERANCE_H
    if H_check == False:
        print "H_check=", H_check
        break

ts = time[1:]  #ignore 0

# then the pressure gauges - this takes it data from the detectors so no
# need for extraction from the vtus
results = fluidity_tools.stat_parser("cwc.detectors")
time = results["ElapsedTime"]["value"]

for p in range(len(parray)):

    data_o = results["phase1"]["Pressure"][parray[p]]
    if "HydrostaticPressure" in results["phase1"]:
        data_o += results["phase1"]["HydrostaticPressure"][parray[p]]
    experiment = numpy.load(parray[p] + ".npy")
    data = experiment.item(0)["phase1"]["Pressure"][parray[p]]
    if "HydrostaticPressure" in experiment.item(0)["phase1"]:
        data += experiment.item(0)["phase1"]["HydrostaticPressure"][parray[p]]

# We need to calculate pressures at dump file steps
    data_o2 = []
    data_2 = []