def Creating_z(Plane,Slope,Sediment,Start_time,End_time,Time_step):

	vtuObject = vtktools.vtu(Plane)
	vtuObject.GetFieldNames()
	gradient = vtuObject.GetScalarField('u')
	ugrid = vtk.vtkUnstructuredGrid()
	gridreader=vtk.vtkXMLUnstructuredGridReader()
	gridreader.SetFileName(Plane)
	gridreader.Update()
	ugrid = gridreader.GetOutput()
	points = ugrid.GetPoints()

	nPoints = ugrid.GetNumberOfPoints()
	for p in range(0,nPoints):
		x = (points.GetPoint(p)[:2] + (gradient[p],))
		points.SetPoint(p,x)
    
	ugrid.Update()
###################################################################################################################
	t = Start_time
	dt = Time_step
	et = End_time
	while t <= et:

		Import = Sediment + str(t) +'000000.vtu'
		NewSave = Sediment + str(t) + '_sed_slope.pvd'
		vtuObjectSed = vtktools.vtu(Import)
		vtuObjectSed.GetFieldNames()
		gradientSed = vtuObjectSed.GetScalarField('u')
		sedgrid = vtk.vtkUnstructuredGrid()
		sedgridreader=vtk.vtkXMLUnstructuredGridReader()
		sedgridreader.SetFileName(Import)
		sedgridreader.Update()
		sedgrid = sedgridreader.GetOutput()
		s = sedgrid.GetPoints()
	
		for p in range(0,nPoints):
			x = ((s.GetPoint(p)[0],) + (s.GetPoint(p)[1],) + ((gradientSed[p]+gradient[p]),))
			s.SetPoint(p,x)

		writer = vtk.vtkUnstructuredGridWriter()
		writer.SetFileName(NewSave)
		writer.SetInput(sedgrid)
		writer.Update()
		writer.Write()
		t += dt
	writer = vtk.vtkUnstructuredGridWriter()
	writer.SetFileName(Slope)
	writer.SetInput(ugrid)
	writer.Update()
	writer.Write()
Пример #2
0
def probe_visc():
    # Files and probing resolution:
    vtufile = "Benchmark_Case_1a_1.pvtu"
    npoints = 500

    # First probe viscosity at y = 550e3

    # Setup Coordinates:
    colx               = numpy.array([numpy.linspace(0,500e3,npoints)]).reshape(npoints,1)
    colz               = numpy.zeros((npoints,1))
    coly               = numpy.ones((npoints,1))*550e3
    coordinates        = numpy.concatenate((colx,coly,colz),1) 

    # Open file and probe for Viscosity:
    vtu                = vtktools.vtu(vtufile)
    viscosity_y_550    = vtktools.vtu.ProbeData(vtu,coordinates,'Mantle::Viscosity')[:,0,0]

    # Next probe viscosity at x = 500e3

    # Setup Coordinates:
    coly               = numpy.array([numpy.linspace(0,660e3,npoints)]).reshape(npoints,1)
    colz               = numpy.zeros((npoints,1))
    colx               = numpy.ones((npoints,1))
    coordinates        = numpy.concatenate((colx,coly,colz),1) 

    # Open file and probe for Viscosity:
    vtu                = vtktools.vtu(vtufile)
    viscosity_x_500    = vtktools.vtu.ProbeData(vtu,coordinates,'Mantle::Viscosity')[:,0,0]

    return min(viscosity_y_550), max(viscosity_y_550), min(viscosity_x_500), max(viscosity_x_500)
Пример #3
0
def probe_visc():
    # Files and probing resolution:
    vtufile = "Benchmark_Case_1a_1.pvtu"
    npoints = 500

    # First probe viscosity at y = 550e3

    # Setup Coordinates:
    colx = numpy.array([numpy.linspace(0, 500e3, npoints)]).reshape(npoints, 1)
    colz = numpy.zeros((npoints, 1))
    coly = numpy.ones((npoints, 1)) * 550e3
    coordinates = numpy.concatenate((colx, coly, colz), 1)

    # Open file and probe for Viscosity:
    vtu = vtktools.vtu(vtufile)
    viscosity_y_550 = vtktools.vtu.ProbeData(vtu, coordinates,
                                             'Mantle::Viscosity')[:, 0, 0]

    # Next probe viscosity at x = 500e3

    # Setup Coordinates:
    coly = numpy.array([numpy.linspace(0, 660e3, npoints)]).reshape(npoints, 1)
    colz = numpy.zeros((npoints, 1))
    colx = numpy.ones((npoints, 1))
    coordinates = numpy.concatenate((colx, coly, colz), 1)

    # Open file and probe for Viscosity:
    vtu = vtktools.vtu(vtufile)
    viscosity_x_500 = vtktools.vtu.ProbeData(vtu, coordinates,
                                             'Mantle::Viscosity')[:, 0, 0]

    return min(viscosity_y_550), max(viscosity_y_550), min(
        viscosity_x_500), max(viscosity_x_500)
Пример #4
0
def l2(file, numericalfield, analyticalfield):
  ug = vtktools.vtu(file)
  ug.GetFieldNames()
  uv = ug.GetScalarField(numericalfield)
  ex = ug.GetScalarField(analyticalfield)
  pos = ug.GetLocations()
  x = pos[:,0]; y=pos[:,1]; z=pos[:,2]

  NE = ug.ugrid.GetNumberOfCells()
  ML = zeros(size(x), float)
  for ele in range(NE):
    ndglno = ug.GetCellPoints(ele)
    if(size(ndglno)==4):
      t = tetvol(x[ndglno],y[ndglno],z[ndglno])
    elif(size(ndglno)==3):
      t = triarea(x[ndglno],y[ndglno])
    for nod in ndglno:
      ML[nod] = ML[nod]+t/size(ndglno)
  
  err_x = ex- uv
  
  norm_x = 0.0 
  diff = zeros(size(x), float)
  for nod in range(size(x)):
    norm_x = norm_x + ML[nod]*(err_x[nod])**2


  norm_x = sqrt(abs(norm_x))
  return (norm_x)
Пример #5
0
def get_velocity_field(fileNumber):
    """
    Used to get the Velocity Field as a numpy array corresponding to a vtu file 
    from the Fluids dataset. Note this normalises the returned array.
    :param fileNumber: int or string
        Used to identify which vtu file to return
        Values are between 0 and 988
    :return: numpy array
        Velocity Fields are returned as numpy array
    """
    folderPath = defaultFilePath + '/small3DLSBU'
    filePath = folderPath + '/LSBU_' + str(fileNumber) + '.vtu'
    sys.path.append('fluidity-master')
    ug = vtktools.vtu(filePath)
    ug.GetFieldNames()
    p = ug.GetVectorField('Velocity')
    p = np.array(p)

    # Normalise p
    p = normalise(p, x_min, x_max)
    # Convert p into 1 x N array
    p = np.array(p)
    p = p.transpose()
    #p = np.array([p[:]])
    return p
Пример #6
0
def get_prediction_velocity(fileNumber):
    """
    Used to get the Tracers as a numpy array corresponding to a vtu file from the Fluids dataset 
    :param fileNumber: int or string
        Used to identify which vtu file to return
        Values are between 0 and 988
    :return: numpy array
        Tracers are returned as numpy array
    """
    networkName = 'vDA' # Change this to prediction folder name

    folderPath = defaultFilePath + '/' + networkName
    filePath = folderPath + '/' + networkName + '_' + str(fileNumber) + '.vtu' 
    sys.path.append('fluidity-master')
    ug = vtktools.vtu(filePath)
    ug.GetFieldNames()
    p = ug.GetVectorField('Latent-GAN')
    p = np.array(p)

    # Normalise p
    p = normalise(p, x_min, x_max)
    # Convert p into 3 x N array
    #p = np.array([p[:]])
    p = p.transpose()
    return p
Пример #7
0
def calc_mld(files, start, x0=0.0, y0=0.0):
    """ Caclulate density-based MLD from a bunch of VTU files
    """

    mld = []
    times = []
    dates = []
    for file in files:

        try:
            os.stat(file)
        except:
            print("No such file: %s" % file)
            sys.exit(1)

        # open vtu and derive the field indices of the edge at (x=0,y=0) ordered by depth
        u = vtktools.vtu(file)
        pos = u.GetLocations()
        ind = get_1d_indices(pos, x0, y0)

        # from this we can derive the 1D profile of any field like this:
        depth = vtktools.arr([-pos[i, 2] for i in ind])

        # handle time for different types of plots
        time = u.GetScalarField('Time')
        times.append(time[0])  # seconds
        dates.append(date2num(start +
                              timedelta(seconds=time[0])))  # integer datetime

        # grab density profile and calculate MLD_den (using 2 different deviation parameters
        d = u.GetScalarField('Density')
        den = vtktools.arr([d[i] * 1000 for i in ind])
        mld.append(calc_mld_den(den, depth))  #den0 = 0.03 is default

    return mld, times, dates
Пример #8
0
def create_velocity_field_VTU_GAN(fileNumber, prediction, networkName):
    """
    Duplicates preexisting VTU file and attaches a prediction field alongside it.
    Files are named based on the input timestep t.
    Files contain prediction for t+1 and ground truth for t+1.
    :param fileNumber: int or string
        Used to identify which vtu file to return
        Values are between 0 and 988
    :param prediction: numpy array
        Predicted tracers
    :param networkName: string
        Name of the network e.g. "AE", "GAN" or "AEGAN" etc.
        All created tracers will be saved to the default file directory in a
        folder with the network name.
    """
    folderPath = defaultFilePath + '/small3DLSBU'
    filePath = folderPath + '/LSBU_' + str(fileNumber + 1) + '.vtu'
    sys.path.append('fluidity-master')
    ug = vtktools.vtu(filePath)

    ug.AddVectorField('Latent-GAN', prediction)

    saveFolderPath = defaultFilePath + '/' + networkName
    saveFolderPath = 'E:/MSc Individual Project/Fluids Dataset'
    saveFilePath = saveFolderPath + '/' + networkName + '_' + str(
        fileNumber) + '.vtu'

    ug.Write(saveFilePath)
Пример #9
0
def get_water_depths(filelist, xarray, delta):
  results = []
  for f in filelist:
    try:
      os.stat(f)
    except:
      print "No such file: %s" % f
      sys.exit(1)
    
    y = numpy.arange(delta/2.0,2.0+delta/2.0,delta)[:,numpy.newaxis]
    
    num = int(f.split(".vtu")[0].split('_')[-1])
    vtu = vtktools.vtu(f)
    for name in vtu.GetFieldNames(): 
      if name.endswith("Time"): 
        time = max(vtu.GetScalarRange(name))
        break
    waterdepths = []
    waterdepths.append(num)
    waterdepths.append(time)
    for x in range(len(xarray)):
      coordinates = numpy.concatenate((numpy.ones((len(y),1))*xarray[x], y, numpy.zeros((len(y),1))),1)
      waterdepths.append(sum(vtu.ProbeData(coordinates, "Water::MaterialVolumeFraction"))[0]*delta)
    
    results.append(waterdepths)
  
  results.sort(key=operator.itemgetter(1))
  results = numpy.array(results)
  return results
Пример #10
0
def GetXandt(filelist):
  time = []
  X_ns = []
  X_fs = []
  for files in filelist:

      data = vtktools.vtu(files) 
      
      time.append(data.GetScalarField("Time")[0])
      
      # Get X
      data.ugrid.GetPointData().SetActiveScalars('Temperature')
      data = data.ugrid
      
      contour = vtk.vtkContourFilter()
      if vtk.vtkVersion.GetVTKMajorVersion() <= 5:
        contour.SetInput(data)
      else:
        contour.SetInputData(data)
      contour.SetValue(0, 0.0)
      contour.Update()
      polydata = contour.GetOutput()

      bounding_box = polydata.GetBounds()
   
      X_ns.append(bounding_box[1])
      X_fs.append(bounding_box[0])

  return time, X_ns, X_fs
Пример #11
0
    def create_X_from_fps(fps, settings, field_type="scalar"):
        """Creates a numpy array of values of scalar field_name
        Input list must be sorted"""

        M = len(fps)  #number timesteps

        for idx, fp in enumerate(fps):
            # create array of tracer
            ug = vtktools.vtu(fp)
            if not settings.THREE_DIM:
                matrix = FluidityUtils.get_1D_grid(ug, settings.FIELD_NAME,
                                                   field_type)
            elif settings.THREE_DIM == True:
                matrix = FluidityUtils().get_3D_grid(ug, settings)
            else:
                raise ValueError(
                    "<config>.THREE_DIM must be True or eval to False")
            mat_size = matrix.shape

            if idx == 0:
                #fix length of vectors and initialize the output array:
                n = matrix.shape
                size = (M, ) + n
                output = np.zeros(size)
            else:
                #enforce all vectors are of the same length
                assert mat_size == n, "All input .vtu files must be of the same size."
            output[idx] = matrix

        #return (M x nx x ny x nz) or (M x n)
        if settings.SAVE:
            np.save(settings.X_FP, output, allow_pickle=True)

        return output
Пример #12
0
def get_water_depths(filelist, xarray, delta):
    results = []
    for f in filelist:
        try:
            os.stat(f)
        except:
            print "No such file: %s" % f
            sys.exit(1)

        y = numpy.arange(delta / 2.0, 2.0 + delta / 2.0, delta)[:,
                                                                numpy.newaxis]

        num = int(f.split(".vtu")[0].split('_')[-1])
        vtu = vtktools.vtu(f)
        for name in vtu.GetFieldNames():
            if name.endswith("Time"):
                time = max(vtu.GetScalarRange(name))
                break
        waterdepths = []
        waterdepths.append(num)
        waterdepths.append(time)
        for x in range(len(xarray)):
            coordinates = numpy.concatenate((numpy.ones(
                (len(y), 1)) * xarray[x], y, numpy.zeros((len(y), 1))), 1)
            waterdepths.append(
                sum(vtu.ProbeData(coordinates,
                                  "Water::MaterialVolumeFraction"))[0] * delta)

        results.append(waterdepths)

    results.sort(key=operator.itemgetter(1))
    results = numpy.array(results)
    return results
Пример #13
0
def meanvelo(file, x, y):

    print("\nRunning velocity profile script on files at times...\n")

    ##### create array of points. Correct for origin not at step.
    pts = []
    for i in range(len(x)):
        for j in range(len(y)):
            pts.append([x[i] + 5.0, y[j], 0.0])

    pts = numpy.array(pts)
    profiles = numpy.zeros([x.size, y.size], float)

    datafile = vtktools.vtu(file)

    ##### Get x-velocity
    uvw = datafile.ProbeData(pts, "AverageVelocity")
    u = uvw[:, 0]
    u = u.reshape([x.size, y.size])
    for i in range(len(x)):
        umax = max(u[i, :])
        u[i, :] = u[i, :] / umax
    profiles[:, :] = u

    print("\n...Finished writing data files.\n")
    return profiles
Пример #14
0
def create_tracer_VTU_AE(fileNumber, prediction, networkName):
    """
    Duplicates preexisting VTU file and attaches a reconstruction field alongside it.
    :param fileNumber: int or string
        Used to identify which vtu file to return
        Values are between 0 and 988
    :param prediction: numpy array
        Predicted tracers
    :param networkName: string
        Name of the network e.g. "AE", "GAN" or "AEGAN" etc.
        All created tracers will be saved to the default file directory in a
        folder with the network name.
    """
    folderPath = defaultFilePath + '/small3DLSBU'
    filePath = folderPath + '/LSBU_' + str(fileNumber) + '.vtu'
    sys.path.append('fluidity-master')
    ug = vtktools.vtu(filePath)

    ug.AddScalarField('Latent-AE', prediction)

    saveFolderPath = defaultFilePath + '/' + networkName
    saveFolderPath = 'E:/MSc Individual Project/Fluids Dataset/tLatentGANExtrap'
    saveFilePath = saveFolderPath + '/' + networkName + '_' + str(
        fileNumber) + '.vtu'

    ug.Write(saveFilePath)
Пример #15
0
def calc_mld_tke_files(files,start,x0=0.0,y0=0.0):
    """ Caclulate tke-based MLD from a bunch of VTU files
    """

    mld = []
    times = []
    dates = []
    for file in files:
      
        try:
            os.stat(file)
        except:
            print "No such file: %s" % file
            sys.exit(1)

        # open vtu and derive the field indices of the edge at (x=0,y=0) ordered by depth
        u=vtktools.vtu(file)
        pos = u.GetLocations()
        ind = get_1d_indices(pos, x0, y0)
    
        # from this we can derive the 1D profile of any field like this:
        depth = vtktools.arr([-pos[i,2] for i in ind])
    
        # handle time for different types of plots
        time = u.GetScalarField('Time')
        times.append(time[0])   # seconds
        dates.append( date2num(start + timedelta(seconds=time[0])) ) # integer datetime
    
        # grab density profile and calculate MLD
        d = u.GetScalarField('GLSTurbulentKineticEnergy')
        tke = vtktools.arr( [d[i] for i in ind] )
        mld.append( calc_mld_tke(tke, depth) )


    return mld, times, dates
Пример #16
0
def meanvelo(file,x,y):

  print "\nRunning velocity profile script on files at times...\n"

  ##### create array of points. Correct for origin not at step.
  pts=[]
  for i in range(len(x)):
    for j in range(len(y)):
      pts.append([x[i]+5.0, y[j], 0.0])

  pts=numpy.array(pts)
  profiles=numpy.zeros([x.size, y.size], float)

  datafile = vtktools.vtu(file)

  ##### Get x-velocity
  uvw = datafile.ProbeData(pts, "AverageVelocity")
  u = uvw[:,0]
  u=u.reshape([x.size,y.size])
  for i in range(len(x)):
    umax = max(u[i,:])
    u[i,:] = u[i,:]/umax
  profiles[:,:] = u

  print "\n...Finished writing data files.\n"
  return profiles
Пример #17
0
def calc_mld(files,start,x0=0.0,y0=0.0):
    """ Caclulate density-based MLD from a bunch of VTU files
    """

    mld = []
    times = []
    dates = []
    for file in files:
      
        try:
            os.stat(file)
        except:
            print("No such file: %s" % file)
            sys.exit(1)

        # open vtu and derive the field indices of the edge at (x=0,y=0) ordered by depth
        u=vtktools.vtu(file)
        pos = u.GetLocations()
        ind = get_1d_indices(pos, x0, y0)
    
        # from this we can derive the 1D profile of any field like this:
        depth = vtktools.arr([-pos[i,2] for i in ind])
    
        # handle time for different types of plots
        time = u.GetScalarField('Time')
        times.append(time[0])   # seconds
        dates.append( date2num(start + timedelta(seconds=time[0])) ) # integer datetime
    
        # grab density profile and calculate MLD_den (using 2 different deviation parameters
        d = u.GetScalarField('Density')
        den = vtktools.arr( [d[i] * 1000 for i in ind] )
        mld.append( calc_mld_den(den, depth) ) #den0 = 0.03 is default


    return mld, times, dates
Пример #18
0
def GetXandt(filelist):
    time = []
    X_ns = []
    X_fs = []
    for files in filelist:

        data = vtktools.vtu(files)

        time.append(data.GetScalarField("Time")[0])

        # Get X
        data.ugrid.GetPointData().SetActiveScalars('Temperature')
        data = data.ugrid

        contour = vtk.vtkContourFilter()
        if vtk.vtkVersion.GetVTKMajorVersion() <= 5:
            contour.SetInput(data)
        else:
            contour.SetInputData(data)
        contour.SetValue(0, 0.0)
        contour.Update()
        polydata = contour.GetOutput()

        bounding_box = polydata.GetBounds()

        X_ns.append(bounding_box[1])
        X_fs.append(bounding_box[0])

    return time, X_ns, X_fs
Пример #19
0
def l2(file, numericalfield, analyticalfield):
    ug = vtktools.vtu(file)
    ug.GetFieldNames()
    uv = ug.GetScalarField(numericalfield)
    ex = ug.GetScalarField(analyticalfield)
    pos = ug.GetLocations()
    x = pos[:, 0]
    y = pos[:, 1]
    z = pos[:, 2]

    NE = ug.ugrid.GetNumberOfCells()
    ML = zeros(size(x), float)
    for ele in range(NE):
        ndglno = ug.GetCellPoints(ele)
        if (size(ndglno) == 4):
            t = tetvol(x[ndglno], y[ndglno], z[ndglno])
        elif (size(ndglno) == 3):
            t = triarea(x[ndglno], y[ndglno])
        for nod in ndglno:
            ML[nod] = ML[nod] + t / size(ndglno)

    err_x = ex - uv

    norm_x = 0.0
    diff = zeros(size(x), float)
    for nod in range(size(x)):
        norm_x = norm_x + ML[nod] * (err_x[nod])**2

    norm_x = sqrt(abs(norm_x))
    return (norm_x)
Пример #20
0
def MLD(filelist):
  x0 = 0.
  tke0 = 1.0e-5
  last_mld = 0
  
  times = []
  depths = []
  Dm = []
  for file in filelist:
     try:
       os.stat(file)
     except:
       print("No such file: %s" % file)
       sys.exit(1)
     
     u=vtktools.vtu(file)
     time = u.GetScalarField('Time')
     tt = time[0]
     kk = u.GetScalarField('GLSTurbulentKineticEnergy')
     pos = u.GetLocations()
     # ignore first 4 hours of simulaiton
     if (tt < 14400):
       continue

     xyzkk = []
     for i in range(0,len(kk)):
       if( abs(pos[i,0] - x0) < 0.1 ):
         xyzkk.append((pos[i,0],-pos[i,1],pos[i,2],(kk[i])))

     xyzkkarr = vtktools.arr(xyzkk)
     III = argsort(xyzkkarr[:,1])
     xyzkkarrsort = xyzkkarr[III,:]
     # march down the column, grabbing the last value above tk0 and the first 
     # one less than tke0. Interpolate between to get the MLD
     kea = 1000
     keb = 0
     zza = 0
     zzb = 0
     for values in xyzkkarrsort:
        if (values[3] > tke0):
            kea = values[3]
            zza = -values[1]
        if (values[3] < tke0):
            keb = values[3]
            zzb = -values[1]
            break

     # the MLD is somewhere between these two values - let's estimate half way!
     mld = (zzb+zza)/2.
     if (last_mld == mld):
        continue

     times.append(tt/3600)
     depths.append(-1.0*mld)
     last_mld = mld
     Dm.append(1.05*0.00988211768*(1.0/sqrt(0.01))*sqrt(tt))


  return times, depths, Dm
Пример #21
0
def MLD(filelist):
  x0 = 0.
  tke0 = 1.0e-5
  last_mld = 0
  
  times = []
  depths = []
  Dm = []
  for file in filelist:
     try:
       os.stat(file)
     except:
       print "No such file: %s" % file
       sys.exit(1)
     
     u=vtktools.vtu(file)
     time = u.GetScalarField('Time')
     tt = time[0]
     kk = u.GetScalarField('GLSTurbulentKineticEnergy')
     pos = u.GetLocations()
     # ignore first 4 hours of simulaiton
     if (tt < 14400):
       continue

     xyzkk = []
     for i in range(0,len(kk)):
       if( abs(pos[i,0] - x0) < 0.1 ):
         xyzkk.append((pos[i,0],-pos[i,1],pos[i,2],(kk[i])))

     xyzkkarr = vtktools.arr(xyzkk)
     III = argsort(xyzkkarr[:,1])
     xyzkkarrsort = xyzkkarr[III,:]
     # march down the column, grabbing the last value above tk0 and the first 
     # one less than tke0. Interpolate between to get the MLD
     kea = 1000
     keb = 0
     zza = 0
     zzb = 0
     for values in xyzkkarrsort:
        if (values[3] > tke0):
            kea = values[3]
            zza = -values[1]
        if (values[3] < tke0):
            keb = values[3]
            zzb = -values[1]
            break

     # the MLD is somewhere between these two values - let's estimate half way!
     mld = (zzb+zza)/2.
     if (last_mld == mld):
        continue

     times.append(tt/3600)
     depths.append(-1.0*mld)
     last_mld = mld
     Dm.append(1.05*0.00988211768*(1.0/sqrt(0.01))*sqrt(tt))


  return times, depths, Dm
Пример #22
0
def reattachment_length(filelist):

    print "Calculating reattachment point locations using change of x-velocity sign\n"

    nums = []
    results = []
    files = []
    ##### check for no files
    if (len(filelist) == 0):
        print "No files!"
        sys.exit(1)
    for file in filelist:
        try:
            os.stat(file)
        except:
            print "No such file: %s" % file
            sys.exit(1)
        files.append(file)
    sort_nicely(files)

    for file in files:
        ##### Read in data from vtu
        datafile = vtktools.vtu(file)
        ##### Get time for plot:
        t = min(datafile.GetScalarField("Time"))
        print file, ', elapsed time = ', t

        ##### points near bottom surface, 0 < x < 20
        pts = []
        no_pts = 82
        offset = 0.1
        x = 5.0
        for i in range(1, no_pts):
            pts.append((x, offset, 0.0))
            x += 0.25

        pts = numpy.array(pts)

        ##### Get x-velocity on bottom boundary
        uvw = datafile.ProbeData(pts, "Velocity")
        u = []
        u = uvw[:, 0]
        points = []

        for i in range(len(u) - 1):
            ##### Hack to ignore division by zero entries in u.
            ##### All u should be nonzero away from boundary!
            if ((u[i] / u[i + 1]) < 0. and not numpy.isinf(u[i] / u[i + 1])):
                ##### interpolate between nodes. Correct for origin not at step.
                p = pts[i][0] + (pts[i + 1][0] - pts[i][0]) * (0.0 - u[i]) / (
                    u[i + 1] - u[i]) - 5.0
                ##### Ignore spurious corner points
                if (p > 1.0):
                    points.append(p)

        ##### Append actual reattachment point and time:
        results.append([points[0], t])

    return results
Пример #23
0
def reattachment_length(filelist):

  print "Calculating reattachment point locations using change of x-velocity sign\n"

  nums=[]; results=[]; files = []
  ##### check for no files
  if (len(filelist) == 0):
    print "No files!"
    sys.exit(1)
  for file in filelist:
    try:
      os.stat(file)
    except:
      print "No such file: %s" % file
      sys.exit(1)
    files.append(file)
  sort_nicely(files)

  for file in files:
    ##### Read in data from vtu
    datafile = vtktools.vtu(file)
    ##### Get time for plot:
    t = min(datafile.GetScalarField("Time"))
    print file, ', elapsed time = ', t

    ##### points near bottom surface, 0 < x < 20
    pts=[]; no_pts = 82; offset = 0.01
    x = 5.0
    for i in range(1, no_pts):
      pts.append((x, offset, 0.0))
      x += 0.25

    pts = numpy.array(pts)

    ##### Get x-velocity on bottom boundary
    uvw = datafile.ProbeData(pts, "AverageVelocity")
    u = []
    u = uvw[:,0]
    points = 0.0

    for i in range(len(u)-1):
      ##### Hack to ignore division by zero entries in u.
      ##### All u should be nonzero away from boundary!
      if((u[i] / u[i+1]) < 0. and u[i+1] > 0. and not numpy.isinf(u[i] / u[i+1])):
        ##### interpolate between nodes. Correct for origin not at step.
        p = pts[i][0] + (pts[i+1][0]-pts[i][0]) * (0.0-u[i]) / (u[i+1]-u[i]) -5.0
        print 'p ', p
        ##### Ignore spurious corner points
        if(p>2):
          points = p
          ##### We have our first point on this plane so...
          break
    print "reattachment point found at: ", points

    ##### Append actual reattachment point and time:
    results.append([points,t])

  return results
Пример #24
0
def meanvelo(filelist, xarray, yarray, zarray):

    print "\nRunning velocity profile script on files at times...\n"
    ##### check for no files
    if (len(filelist) < 0):
        print "No files!"
        sys.exit(1)

    ##### create array of points
    pts = []
    for i in range(len(xarray)):
        for j in range(len(yarray)):
            for k in range(len(zarray)):
                pts.append([xarray[i], yarray[j], zarray[k]])
    pts = numpy.array(pts)

    ##### Create output array of correct shape
    files = 3
    filecount = 0
    profiles = numpy.zeros([files, xarray.size, zarray.size], float)

    for file in filelist:
        try:
            os.stat(file)
        except:
            f_log.write("No such file: %s" % files)
            sys.exit(1)

        ##### Only process these 3 datafiles:
        vtu_no = float(file.split('_')[-1].split('.')[0])
        if (vtu_no == 6 or vtu_no == 11 or vtu_no == 33):

            datafile = vtktools.vtu(file)
            t = min(datafile.GetScalarField("Time"))
            print file, ', elapsed time = ', t

            ##### Get x-velocity
            uvw = datafile.ProbeData(pts, "Velocity")
            umax = max(abs(datafile.GetVectorField("Velocity")[:, 0]))
            u = uvw[:, 0] / umax
            u = u.reshape([xarray.size, yarray.size, zarray.size])

            ##### Spanwise averaging
            usum = numpy.zeros([xarray.size, zarray.size], float)
            usum = numpy.array(usum)
            for i in range(len(yarray)):
                uav = u[:, i, :]
                uav = numpy.array(uav)
                usum += uav
            usum = usum / len(yarray)
            profiles[filecount, :, :] = usum

            ##### reset time to something big to prevent infinite loop
            t = 100.
            filecount += 1

    print "\n...Finished extracting data.\n"
    return profiles
def meanvelo(filelist,xarray,yarray,zarray):

  print "\nRunning velocity profile script on files at times...\n"
  ##### check for no files
  if (len(filelist) < 0):
    print "No files!"
    sys.exit(1)

  ##### create array of points
  pts=[]
  for i in range(len(xarray)):
    for j in range(len(yarray)):
      for k in range(len(zarray)):
        pts.append([xarray[i], yarray[j], zarray[k]])
  pts=numpy.array(pts)

  ##### Create output array of correct shape
  files = 3; filecount = 0
  profiles = numpy.zeros([files, xarray.size, zarray.size], float)

  for file in filelist:
    try:
      os.stat(file)
    except:
      f_log.write("No such file: %s" % files)
      sys.exit(1)

    ##### Only process these 3 datafiles:
    vtu_no = float(file.split('_')[-1].split('.')[0])
    if (vtu_no == 6 or vtu_no == 11 or vtu_no == 33):

      datafile = vtktools.vtu(file)
      t = min(datafile.GetScalarField("Time"))
      print file, ', elapsed time = ', t

      ##### Get x-velocity
      uvw = datafile.ProbeData(pts, "Velocity")
      umax = max(abs(datafile.GetVectorField("Velocity")[:,0]))
      u = uvw[:,0]/umax
      u = u.reshape([xarray.size,yarray.size,zarray.size])

      ##### Spanwise averaging
      usum = numpy.zeros([xarray.size,zarray.size],float)
      usum = numpy.array(usum)
      for i in range(len(yarray)):
        uav = u[:,i,:]
        uav = numpy.array(uav)
        usum += uav
      usum = usum / len(yarray)
      profiles[filecount,:,:] = usum

      ##### reset time to something big to prevent infinite loop
      t = 100.
      filecount += 1

  print "\n...Finished extracting data.\n"
  return profiles
Пример #26
0
def values_per_node(file):
  
  u=vtktools.vtu(file)
  zoo = u.GetScalarField('Zooplankton')
  phyto = u.GetScalarField('Phytoplankton')
  nut = u.GetScalarField('Nutrient')
  det = u.GetScalarField('Detritus')
   
  return phyto, zoo, nut, det
Пример #27
0
def values_per_node(file):

    u = vtktools.vtu(file)
    zoo = u.GetScalarField('Zooplankton')
    phyto = u.GetScalarField('Phytoplankton')
    nut = u.GetScalarField('Nutrient')
    det = u.GetScalarField('Detritus')

    return phyto, zoo, nut, det
Пример #28
0
def inf(file, numericalfield, analyticalfield):
  ug = vtktools.vtu(file)
  ug.GetFieldNames()
  uv = ug.GetScalarField(numericalfield)
  ex = ug.GetScalarField(analyticalfield)

  err_x = ex - uv
        
  norm_x = max(abs(err_x))
  return (norm_x)
Пример #29
0
    def save_vtu_file(arr, name, filename, sample_fp=None):
        """Saves an unstructured VTU file - NOTE TODO - should be using deep copy method in vtktools.py -> VtuDiff()"""
        if sample_fp == None:
            sample_fp = vda.get_sorted_fps_U(self.settings.DATA_FP)[0]

        ug = vtktools.vtu(
            sample_fp)  #use sample fp to initialize positions on grid

        ug.AddScalarField('name', arr)
        ug.Write(filename)
Пример #30
0
def inf(file, numericalfield, analyticalfield):
    ug = vtktools.vtu(file)
    ug.GetFieldNames()
    uv = ug.GetScalarField(numericalfield)
    ex = ug.GetScalarField(analyticalfield)

    err_x = ex - uv

    norm_x = max(abs(err_x))
    return (norm_x)
Пример #31
0
def botella_p2(NN):
    #Botella and Peyret (1998) Table 10.
    filelist_not_sorted = glob.glob('driven_cavity-%d/*.vtu' % NN)
    vtu_nos_not_sorted = [
        int(file.split('.vtu')[0].split('_')[-1])
        for file in filelist_not_sorted
    ]
    filelist = [
        filelist_not_sorted[i] for i in numpy.argsort(vtu_nos_not_sorted)
    ]
    file = filelist[-1]
    print file
    try:
        os.stat(file)
    except:
        print "No such file: %s" % file
        sys.exit(1)

    u = vtktools.vtu(file)
    pts = vtktools.arr([[1.0000, 0.5, 0.0, 0.077455],
                        [0.9688, 0.5, 0.0, 0.078837],
                        [0.9609, 0.5, 0.0, 0.078685],
                        [0.9531, 0.5, 0.0, 0.078148],
                        [0.9453, 0.5, 0.0, 0.077154],
                        [0.9063, 0.5, 0.0, 0.065816],
                        [0.8594, 0.5, 0.0, 0.049029],
                        [0.8047, 0.5, 0.0, 0.034552],
                        [0.5000, 0.5, 0.0, 0.000000],
                        [0.2344, 0.5, 0.0, 0.044848],
                        [0.2266, 0.5, 0.0, 0.047260],
                        [0.1563, 0.5, 0.0, 0.069511],
                        [0.0938, 0.5, 0.0, 0.084386],
                        [0.0781, 0.5, 0.0, 0.086716],
                        [0.0703, 0.5, 0.0, 0.087653],
                        [0.0625, 0.5, 0.0, 0.088445],
                        [0.0000, 0.5, 0.0, 0.090477]])

    velocity = u.ProbeData(pts, "Velocity")
    (ilen, jlen) = velocity.shape
    pressure = u.ProbeData(pts, "Pressure")

    pts0 = vtktools.arr([[
        0.5, 0.5, 0.0
    ]])  # We're going to subtract off the pressure at the centre point
    press0 = u.ProbeData(pts0, "Pressure")

    norm = 0.0
    for i in range(ilen):
        diff = pts[i][3] - (pressure[i][0] - press0[0][0])
        norm = norm + diff * diff

    norm = math.sqrt(norm / ilen)
    print "botella_p2_norm:", norm

    return norm
Пример #32
0
def erturk_u(NN):
    #Erturk et al 2005. Table VI
    filelist_not_sorted = glob.glob('driven_cavity-%d/*.vtu' % NN)
    vtu_nos_not_sorted = [
        int(file.split('.vtu')[0].split('_')[-1])
        for file in filelist_not_sorted
    ]
    filelist = [
        filelist_not_sorted[i] for i in numpy.argsort(vtu_nos_not_sorted)
    ]
    file = filelist[-1]
    print file
    try:
        os.stat(file)
    except:
        print "No such file: %s" % file
        sys.exit(1)

    u = vtktools.vtu(file)
    pts = vtktools.arr([[0.5, 0.000, 0.000, 0.0000],
                        [0.5, 0.000, 0.000, 0.0000],
                        [0.5, 0.020, 0.000, -0.0757],
                        [0.5, 0.040, 0.000, -0.1392],
                        [0.5, 0.060, 0.000, -0.1951],
                        [0.5, 0.080, 0.000, -0.2472],
                        [0.5, 0.100, 0.000, -0.2960],
                        [0.5, 0.120, 0.000, -0.3381],
                        [0.5, 0.140, 0.000, -0.3690],
                        [0.5, 0.160, 0.000, -0.3854],
                        [0.5, 0.180, 0.000, -0.3869],
                        [0.5, 0.200, 0.000, -0.3756],
                        [0.5, 0.500, 0.000, -0.0620],
                        [0.5, 0.900, 0.000,
                         0.3838], [0.5, 0.910, 0.000, 0.3913],
                        [0.5, 0.920, 0.000,
                         0.3993], [0.5, 0.930, 0.000, 0.4101],
                        [0.5, 0.940, 0.000,
                         0.4276], [0.5, 0.950, 0.000, 0.4582],
                        [0.5, 0.960, 0.000,
                         0.5102], [0.5, 0.970, 0.000, 0.5917],
                        [0.5, 0.980, 0.000,
                         0.7065], [0.5, 0.990, 0.000, 0.8486],
                        [0.5, 1.000, 0.000, 1.0000]])

    velocity = u.ProbeData(pts, "Velocity")
    (ilen, jlen) = velocity.shape
    norm = 0.0
    for i in range(ilen):
        diff = pts[i][3] - velocity[i][0]
        norm = norm + diff * diff

    norm = math.sqrt(norm / ilen)
    print "erturk_u_norm:", norm

    return norm
Пример #33
0
def botella_p1(NN):
    #Botella and Peyret (1998) Table 9.
    filelist_not_sorted = glob.glob('driven_cavity-%d/*.vtu' % NN)
    vtu_nos_not_sorted = [
        int(file.split('.vtu')[0].split('_')[-1])
        for file in filelist_not_sorted
    ]
    filelist = [
        filelist_not_sorted[i] for i in numpy.argsort(vtu_nos_not_sorted)
    ]
    file = filelist[-1]
    print file
    try:
        os.stat(file)
    except:
        print "No such file: %s" % file
        sys.exit(1)

    u = vtktools.vtu(file)
    pts = vtktools.arr([[0.5, 0.0000, 0.0, 0.110591],
                        [0.5, 0.0547, 0.0, 0.109689],
                        [0.5, 0.0625, 0.0, 0.109200],
                        [0.5, 0.0703, 0.0, 0.108566],
                        [0.5, 0.1016, 0.0, 0.104187],
                        [0.5, 0.1719, 0.0, 0.081925],
                        [0.5, 0.2813, 0.0, 0.040377],
                        [0.5, 0.4531, 0.0, 0.004434],
                        [0.5, 0.5000, 0.0, 0.000000],
                        [0.5, 0.6172, 0.0, -0.000827],
                        [0.5, 0.7344, 0.0, 0.012122],
                        [0.5, 0.8516, 0.0, 0.034910],
                        [0.5, 0.9531, 0.0, 0.050329],
                        [0.5, 0.9609, 0.0, 0.050949],
                        [0.5, 0.9688, 0.0, 0.051514],
                        [0.5, 0.9766, 0.0, 0.052009],
                        [0.5, 1.0000, 0.0, 0.052987]])

    velocity = u.ProbeData(pts, "Velocity")
    (ilen, jlen) = velocity.shape
    pressure = u.ProbeData(pts, "Pressure")

    pts0 = vtktools.arr([[
        0.5, 0.5, 0.0
    ]])  # We're going to subtract off the pressure at the centre point
    press0 = u.ProbeData(pts0, "Pressure")

    norm = 0.0
    for i in range(ilen):
        diff = pts[i][3] - (pressure[i][0] - press0[0][0])
        norm = norm + diff * diff

    norm = math.sqrt(norm / ilen)
    print "botella_p1_norm:", norm

    return norm
Пример #34
0
def MLD(filelist):
    x0 = 0.
    tke0 = 1.0e-5
    last_mld = 0

    times = []
    depths = []
    for file in filelist:
        try:
            os.stat(file)
        except:
            print "No such file: %s" % file
            sys.exit(1)

        u = vtktools.vtu(file)
        time = u.GetScalarField('Time')
        tt = time[0]
        kk = u.GetScalarField('GLSTurbulentKineticEnergy')
        pos = u.GetLocations()
        if (tt < 100):
            continue

        xyzkk = []
        for i in range(0, len(kk)):
            if (abs(pos[i, 0] - x0) < 0.1):
                xyzkk.append((pos[i, 0], -pos[i, 1], pos[i, 2], (kk[i])))

        xyzkkarr = vtktools.arr(xyzkk)
        III = argsort(xyzkkarr[:, 1])
        xyzkkarrsort = xyzkkarr[III, :]
        # march down the column, grabbing the last value above tk0 and the first
        # one less than tke0. Interpolate between to get the MLD
        kea = 1000
        keb = 0
        zza = 0
        zzb = 0
        for values in xyzkkarrsort:
            if (values[3] > tke0):
                kea = values[3]
                zza = -values[1]
            if (values[3] < tke0):
                keb = values[3]
                zzb = -values[1]
                break

        mld = zza
        if (last_mld == mld):
            continue

        times.append(tt / 3600)
        depths.append(-1.0 * mld)
        last_mld = mld

    return times, depths
def MLD(filelist):
  x0 = 0.
  tke0 = 1.0e-5
  last_mld = 0
  
  times = []
  depths = []
  for file in filelist:
     try:
       os.stat(file)
     except:
       print("No such file: %s" % file)
       sys.exit(1)
     
     u=vtktools.vtu(file)
     time = u.GetScalarField('Time')
     tt = time[0]
     kk = u.GetScalarField('GLSTurbulentKineticEnergy')
     pos = u.GetLocations()
     if (tt < 100):
       continue

     xyzkk = []
     for i in range(0,len(kk)):
       if( abs(pos[i,0] - x0) < 0.1 ):
         xyzkk.append((pos[i,0],-pos[i,1],pos[i,2],(kk[i])))

     xyzkkarr = vtktools.arr(xyzkk)
     III = argsort(xyzkkarr[:,1])
     xyzkkarrsort = xyzkkarr[III,:]
     # march down the column, grabbing the last value above tk0 and the first 
     # one less than tke0. Interpolate between to get the MLD
     kea = 1000
     keb = 0
     zza = 0
     zzb = 0
     for values in xyzkkarrsort:
        if (values[3] > tke0):
            kea = values[3]
            zza = -values[1]
        if (values[3] < tke0):
            keb = values[3]
            zzb = -values[1]
            break

     mld = zza
     if (last_mld == mld):
        continue

     times.append(tt/3600)
     depths.append(-1.0*mld)
     last_mld = mld

  return times, depths
Пример #36
0
def get_cloud_front(path_prefix, n_files, resolution, threshold):

    # Size of the domain
    lx = 0.025
    ly = 4.5

    # Arrays to store the results
    # Note: n_files is the number of VTU files to be read.
    upper_positions = numpy.zeros(n_files)
    lower_positions = numpy.zeros(n_files)
    times = numpy.zeros(n_files)

    path = path_prefix  # + "/output/"

    # For each vtu file...
    for i in range(0, n_files, 20):
        # Open the VTU files one by one
        try:
            file = vtktools.vtu(path +
                                '/mphase_rogue_shock_tube_dense_bed_nylon_' +
                                str(i) + '.pvtu')
        except:
            print("WARNING: Could not open VTU file!")
            front_position[i] = 0
            times[i] = 0
            continue
        file.GetFieldNames()

        time = max(file.GetScalarField('Gas::Time'))
        print("At time t = %f s" % time)

        # Generate a set of probe positions
        probes = numpy.linspace(1.35, 1.7, (ly / resolution))

        # Loop over each of the probes in the y direction, from the top down
        for j in range(len(probes) - 1, -1, -1):
            vfrac = vtktools.vtu.ProbeData(file,
                                           numpy.array([[0.0, probes[j], 0]]),
                                           'Particles::PhaseVolumeFraction')
            if (vfrac >= 0.3):
                upper_positions[i] = probes[j]
                break

        for j in range(0, len(probes)):
            vfrac = vtktools.vtu.ProbeData(file,
                                           numpy.array([[0.0, probes[j], 0]]),
                                           'Particles::PhaseVolumeFraction')
            if (vfrac >= 0.01):
                lower_positions[i] = probes[j]
                break

        times[i] = time - 0.0008

    return times, upper_positions, lower_positions
Пример #37
0
def getDistanceMeshDensity(file):
  v = vtktools.vtu(file)
  l = [0.0] * v.ugrid.GetNumberOfPoints()
  a = vtktools.arr(l)
  for i in range(v.ugrid.GetNumberOfPoints()):
    neighbours = v.GetPointPoints(i)
    sum = 0.0
    for neighbour in neighbours:
      sum = sum + v.GetDistance(i, neighbour)
    a[i] = sum / len(neighbours)
  return a
def getDistanceMeshDensity(file):
    v = vtktools.vtu(file)
    l = [0.0] * v.ugrid.GetNumberOfPoints()
    a = vtktools.arr(l)
    for i in range(v.ugrid.GetNumberOfPoints()):
        neighbours = v.GetPointPoints(i)
        sum = 0.0
        for neighbour in neighbours:
            sum = sum + v.GetDistance(i, neighbour)
        a[i] = sum / len(neighbours)
    return a
Пример #39
0
def flux(file,x,y):

    u=vtktools.vtu(file)
    flux = u.GetScalarField('HeatFlux')
    pos = u.GetLocations()
    f = finfo(float)

    for i in range(0,len(flux)):
        if( abs(pos[i,0] - x) < f.eps and abs(pos[i,1] - y) < f.eps and (pos[i,2] - 0.0) < f.eps ):
            return flux[i]

    return -666
Пример #40
0
def get_interface_depth(file):
    vtu = vtktools.vtu(file)
    data = vtu.ugrid
    data.GetPointData().SetActiveScalars("Dense::MaterialVolumeFraction")
    contour = vtk.vtkContourFilter()
    contour.SetInput(data)
    contour.SetValue(0, 0.5)
    contour.Update()
    polydata = contour.GetOutput()
    bounding_box = polydata.GetBounds()
    interface_depth = bounding_box[2]
    return interface_depth
def get_interface_depth(file):
  vtu=vtktools.vtu(file)
  data = vtu.ugrid
  data.GetPointData().SetActiveScalars("Dense::MaterialVolumeFraction")
  contour = vtk.vtkContourFilter ()
  contour.SetInput(data)
  contour.SetValue(0, 0.5)
  contour.Update()
  polydata = contour.GetOutput()
  bounding_box = polydata.GetBounds()
  interface_depth = bounding_box[2]
  return interface_depth
Пример #42
0
def getData(file, xmin=float('nan'), xmax=float('nan'), ymin=float('nan'), ymax=float('nan'), step_x=1,step_y=1):
  u=vtktools.vtu(file)

  print numpy.isnan(xmin), numpy.isnan(xmax), numpy.isnan(ymin), numpy.isnan(ymax)

  if numpy.isnan(xmin): 
    xmin=u.ugrid.GetBounds()[0]
    print 'xmin = ', xmin
  if numpy.isnan(ymin):
    ymin=u.ugrid.GetBounds()[2]
    print 'ymin = ', ymin
  if numpy.isnan(xmax):
    xmax=u.ugrid.GetBounds()[1]
    print 'xmax = ', xmax
  if numpy.isnan(ymax):
    ymax=u.ugrid.GetBounds()[3]
    print 'ymax = ', ymax
  
  Xlist = numpy.arange(xmin,xmax,step_x)# x coordinates
  Ylist = numpy.arange(ymin,ymax,step_y)# y coordinates
  [X0,Y0] = scipy.meshgrid(Xlist,Ylist)
  X0=X0.transpose()
  Y0=Y0.transpose()
  print Xlist.shape, Ylist.shape, X0.shape, Y0.shape
  Z0 = 0.0*Y0 # This is 2d so z is an array of zeros.
  X = numpy.reshape(X0,(numpy.size(X0),))
  Y = numpy.reshape(Y0,(numpy.size(Y0),))
  Z = numpy.reshape(Z0,(numpy.size(Z0),))
  pts = zip(X,Y,Z)
  pts = vtktools.arr(pts)
  # create arrays of velocity and temperature values at the desired points
  sol = u.ProbeData(pts, 'solution')
  print sol.shape, Xlist.shape, Ylist.shape
  #temperature_structured = u.ProbeData(pts, 'Temperature')
  numpy.savetxt("pts.dat", zip(X,Y,sol))

  sol = sol.reshape((numpy.size(Xlist),numpy.size(Ylist)))
  x=[]
  y=[]
  z=[]
  for i in range(len(Xlist)):
    for j in range(len(Ylist)):
      #print i,j
      x.append(X0[i,j])
      y.append(Y0[i,j])
      z.append(sol[i,j])
  numpy.savetxt("pts2.dat", numpy.array(zip(x, y, z)))

  #data = scipy.interpolate.RectBivariateSpline(Xlist,Ylist,sol)
  
  # return Xlist, Ylist, sol
  return Xlist,Ylist,sol
Пример #43
0
    def testVtuDim(self):
        import vtktools
        vtu = vtktools.vtu()
        self.assertEquals(VtuDim(vtu), 0)

        points = vtk.vtkPoints()
        points.SetDataTypeToDouble()
        points.InsertNextPoint(0.0, 0.0, 0.0)
        points.InsertNextPoint(0.0, 0.0, 1.0)
        vtu.ugrid.SetPoints(points)
        self.assertEquals(VtuDim(vtu), 1)

        return
Пример #44
0
 def testVtuDim(self):
   import vtktools
   vtu = vtktools.vtu()
   self.assertEquals(VtuDim(vtu), 0)
   
   points = vtk.vtkPoints()
   points.SetDataTypeToDouble()
   points.InsertNextPoint(0.0, 0.0, 0.0)
   points.InsertNextPoint(0.0, 0.0, 1.0)
   vtu.ugrid.SetPoints(points)
   self.assertEquals(VtuDim(vtu), 1)
   
   return
Пример #45
0
def flux(file, x, y):

    u = vtktools.vtu(file)
    flux = u.GetScalarField('HeatFlux')
    pos = u.GetLocations()
    f = finfo(float)

    for i in range(0, len(flux)):
        if (abs(pos[i, 0] - x) < f.eps and abs(pos[i, 1] - y) < f.eps
                and (pos[i, 2] - 0.0) < f.eps):
            return flux[i]

    return -666
Пример #46
0
 def __call__(self, options):
     stem = '{}/{}'.format(options.case_name, options.simulation_name)
     # get the last dump file
     n = 0
     while os.path.isfile(get_filename(options, n + 1)):
         n += 1
     # load results and plot
     vtu_obj = vtktools.vtu(get_filename(options, n))
     x = vtu_obj.GetLocations()[:,0]
     f = vtu_obj.GetScalarField('Tracer')
     x, f = monotonic(x, f)
     plt.plot(x, f, label=options.simulation_name)
     self.print_end(options.simulation_name, options)
def erturk_v(NN):
#Erturk et al 2005. Table VII
  filelist_not_sorted = glob.glob('driven_cavity-%d/*.vtu'%NN)
  vtu_nos_not_sorted = [int(file.split('.vtu')[0].split('_')[-1]) for file in filelist_not_sorted]
  filelist = [filelist_not_sorted[i] for i in numpy.argsort(vtu_nos_not_sorted)]
  file = filelist[-1]
  print file
  try:
    os.stat(file)
  except:
    print "No such file: %s" % file
    sys.exit(1)

  u=vtktools.vtu(file)
  pts=vtktools.arr([
  [0.000, 0.5, 0.0,  0.0000],
  [0.015, 0.5, 0.0,  0.1019],
  [0.030, 0.5, 0.0,  0.1792],
  [0.045, 0.5, 0.0,  0.2349],
  [0.060, 0.5, 0.0,  0.2746],
  [0.075, 0.5, 0.0,  0.3041],
  [0.090, 0.5, 0.0,  0.3273],
  [0.105, 0.5, 0.0,  0.3460],
  [0.120, 0.5, 0.0,  0.3605],
  [0.135, 0.5, 0.0,  0.3705],
  [0.150, 0.5, 0.0,  0.3756],
  [0.500, 0.5, 0.0,  0.0258],
  [0.850, 0.5, 0.0, -0.4028],
  [0.865, 0.5, 0.0, -0.4407],
  [0.880, 0.5, 0.0, -0.4803],
  [0.895, 0.5, 0.0, -0.5132],
  [0.910, 0.5, 0.0, -0.5263],
  [0.925, 0.5, 0.0, -0.5052],
  [0.940, 0.5, 0.0, -0.4417],
  [0.955, 0.5, 0.0, -0.3400],
  [0.970, 0.5, 0.0, -0.2173],
  [0.985, 0.5, 0.0, -0.0973],
  [1.000, 0.5, 0.0,  0.0000]])
  
  velocity = u.ProbeData(pts, "Velocity")
  (ilen, jlen) = velocity.shape
  norm=0.0
  for i in range(ilen):
      diff = pts[i][3] - velocity[i][1]
      norm = norm + diff*diff
  
  norm = math.sqrt(norm/ilen)
  print "erturk_v_norm:", norm

  return norm
def erturk_u(NN):
#Erturk et al 2005. Table VI
  filelist_not_sorted = glob.glob('driven_cavity-%d/*.vtu'%NN)
  vtu_nos_not_sorted = [int(file.split('.vtu')[0].split('_')[-1]) for file in filelist_not_sorted]
  filelist = [filelist_not_sorted[i] for i in numpy.argsort(vtu_nos_not_sorted)]
  file = filelist[-1]
  print file
  try:
    os.stat(file)
  except:
    print "No such file: %s" % file
    sys.exit(1)

  u=vtktools.vtu(file)
  pts=vtktools.arr([[0.5, 0.000, 0.000, 0.0000],
  [0.5, 0.000, 0.000,  0.0000],
  [0.5, 0.020, 0.000, -0.0757],
  [0.5, 0.040, 0.000, -0.1392],
  [0.5, 0.060, 0.000, -0.1951],
  [0.5, 0.080, 0.000, -0.2472],
  [0.5, 0.100, 0.000, -0.2960],
  [0.5, 0.120, 0.000, -0.3381],
  [0.5, 0.140, 0.000, -0.3690],
  [0.5, 0.160, 0.000, -0.3854],
  [0.5, 0.180, 0.000, -0.3869],
  [0.5, 0.200, 0.000, -0.3756],
  [0.5, 0.500, 0.000, -0.0620],
  [0.5, 0.900, 0.000,  0.3838],
  [0.5, 0.910, 0.000,  0.3913],
  [0.5, 0.920, 0.000,  0.3993],
  [0.5, 0.930, 0.000,  0.4101],
  [0.5, 0.940, 0.000,  0.4276],
  [0.5, 0.950, 0.000,  0.4582],
  [0.5, 0.960, 0.000,  0.5102],
  [0.5, 0.970, 0.000,  0.5917],
  [0.5, 0.980, 0.000,  0.7065],
  [0.5, 0.990, 0.000,  0.8486],
  [0.5, 1.000, 0.000,  1.0000]])
  
  velocity = u.ProbeData(pts, "Velocity")
  (ilen, jlen) = velocity.shape
  norm=0.0
  for i in range(ilen):
      diff = pts[i][3] - velocity[i][0]
      norm = norm + diff*diff
  
  norm = math.sqrt(norm/ilen)
  print "erturk_u_norm:", norm

  return norm
Пример #49
0
def calc_mld(files, mld_depths):
    for file in files:
        try:
            os.stat(file)
        except:
            print "No such file: %s" % file
            sys.exit(1)
        num = int(file.split(".vtu")[0].split('_')[-1])
        u = vtktools.vtu(file)
        pos = u.GetLocations()
        time = u.GetScalarField('Time')
        tt = time[0]

        # grab the data e need from the VTUs and shove in an array
        den = u.GetScalarField('Density')
        xyz_data = []
        for i in range(0, len(den)):
            if (x0 - 0.1 < pos[i, 0] < x0 + 0.1
                    and y0 - 0.1 < pos[i, 1] < y0 + 0.1):
                xyz_data.append(
                    (pos[i, 0], pos[i, 1], -pos[i, 2] + z0, 1000 * den[i]))

        # sorted the array based on depth
        xyz_data = vtktools.arr(xyz_data)
        III = argsort(xyz_data[:, 2])
        xyz_data_sorted = xyz_data[III, :]

        # Surface values
        sden = xyz_data_sorted[0, 3]

        # grab any values where the UML condition is met for temperature, density and TKE
        uml_den = ((xyz_data_sorted[:, 3]) <= (sden + den0)).nonzero()

        # ...on density
        if ((size(uml_den) > 0)):
            LL = uml_den[-1][-1]
            zz = xyz_data_sorted[:, 2]
            if (LL + 1 < size(zz)):
                zza = zz[LL + 1]
                kea = xyz_data_sorted[LL + 1, 3]
            else:
                zza = zz[LL]
                kea = xyz_data_sorted[LL, 3]
            zzb = zz[LL]
            keb = xyz_data_sorted[LL, 3]
            tt = tt / (24 * 60 * 60)
            time = start_datetime + timedelta(days=tt)
            key = '%04d/%02d/%02d' % (time.year, time.month, time.day)
            mld_depths[key] = (zza - (zzb - zza) * (((sden + den0) - kea) /
                                                    (kea - keb)))
Пример #50
0
def erturk_v(NN):
#Erturk et al 2005. Table VII
  filelist_not_sorted = glob.glob('driven_cavity-%d/*.vtu'%NN)
  vtu_nos_not_sorted = [int(file.split('.vtu')[0].split('_')[-1]) for file in filelist_not_sorted]
  filelist = [filelist_not_sorted[i] for i in numpy.argsort(vtu_nos_not_sorted)]
  file = filelist[-1]
  print file
  try:
    os.stat(file)
  except:
    print "No such file: %s" % file
    sys.exit(1)

  u=vtktools.vtu(file)
  pts=vtktools.arr([
  [0.000, 0.5, 0.0,  0.0000],
  [0.015, 0.5, 0.0,  0.1019],
  [0.030, 0.5, 0.0,  0.1792],
  [0.045, 0.5, 0.0,  0.2349],
  [0.060, 0.5, 0.0,  0.2746],
  [0.075, 0.5, 0.0,  0.3041],
  [0.090, 0.5, 0.0,  0.3273],
  [0.105, 0.5, 0.0,  0.3460],
  [0.120, 0.5, 0.0,  0.3605],
  [0.135, 0.5, 0.0,  0.3705],
  [0.150, 0.5, 0.0,  0.3756],
  [0.500, 0.5, 0.0,  0.0258],
  [0.850, 0.5, 0.0, -0.4028],
  [0.865, 0.5, 0.0, -0.4407],
  [0.880, 0.5, 0.0, -0.4803],
  [0.895, 0.5, 0.0, -0.5132],
  [0.910, 0.5, 0.0, -0.5263],
  [0.925, 0.5, 0.0, -0.5052],
  [0.940, 0.5, 0.0, -0.4417],
  [0.955, 0.5, 0.0, -0.3400],
  [0.970, 0.5, 0.0, -0.2173],
  [0.985, 0.5, 0.0, -0.0973],
  [1.000, 0.5, 0.0,  0.0000]])
  
  velocity = u.ProbeData(pts, "Velocity")
  (ilen, jlen) = velocity.shape
  norm=0.0
  for i in range(ilen):
      diff = pts[i][3] - velocity[i][1]
      norm = norm + diff*diff
  
  norm = math.sqrt(norm/ilen)
  print "erturk_v_norm:", norm

  return norm
Пример #51
0
def botella_v(NN):
    #Botella and Peyret (1998) Table 10.
    filelist_not_sorted = glob.glob('driven_cavity-%d/*.vtu' % NN)
    vtu_nos_not_sorted = [
        int(file.split('.vtu')[0].split('_')[-1])
        for file in filelist_not_sorted
    ]
    filelist = [
        filelist_not_sorted[i] for i in numpy.argsort(vtu_nos_not_sorted)
    ]
    file = filelist[-1]
    print file
    try:
        os.stat(file)
    except:
        print "No such file: %s" % file
        sys.exit(1)

    u = vtktools.vtu(file)
    pts = vtktools.arr([[1.0000, 0.5, 0.0, 0.0000000],
                        [0.9688, 0.5, 0.0, -0.2279225],
                        [0.9609, 0.5, 0.0, -0.2936869],
                        [0.9531, 0.5, 0.0, -0.3553213],
                        [0.9453, 0.5, 0.0, -0.4103754],
                        [0.9063, 0.5, 0.0, -0.5264392],
                        [0.8594, 0.5, 0.0, -0.4264545],
                        [0.8047, 0.5, 0.0, -0.3202137],
                        [0.5000, 0.5, 0.0, 0.0257995],
                        [0.2344, 0.5, 0.0, 0.3253592],
                        [0.2266, 0.5, 0.0, 0.3339924],
                        [0.1563, 0.5, 0.0, 0.3769189],
                        [0.0938, 0.5, 0.0, 0.3330442],
                        [0.0781, 0.5, 0.0, 0.3099097],
                        [0.0703, 0.5, 0.0, 0.2962703],
                        [0.0625, 0.5, 0.0, 0.2807056],
                        [0.0000, 0.5, 0.0, 0.0000000]])

    velocity = u.ProbeData(pts, "Velocity")
    (ilen, jlen) = velocity.shape

    norm = 0.0
    for i in range(ilen):
        diff = pts[i][3] - velocity[i][1]
        norm = norm + diff * diff

    norm = math.sqrt(norm / ilen)
    print "botella_v_norm:", norm

    return norm
def botella_p2(NN):
#Botella and Peyret (1998) Table 10. 
  filelist_not_sorted = glob.glob('driven_cavity-%d/*.vtu'%NN)
  vtu_nos_not_sorted = [int(file.split('.vtu')[0].split('_')[-1]) for file in filelist_not_sorted]
  filelist = [filelist_not_sorted[i] for i in numpy.argsort(vtu_nos_not_sorted)]
  file = filelist[-1]
  print file
  try:
    os.stat(file)
  except:
    print "No such file: %s" % file
    sys.exit(1)

  u=vtktools.vtu(file)
  pts=vtktools.arr([
  [1.0000, 0.5, 0.0,  0.077455],
  [0.9688, 0.5, 0.0,  0.078837],
  [0.9609, 0.5, 0.0,  0.078685],
  [0.9531, 0.5, 0.0,  0.078148],
  [0.9453, 0.5, 0.0,  0.077154],
  [0.9063, 0.5, 0.0,  0.065816],
  [0.8594, 0.5, 0.0,  0.049029],
  [0.8047, 0.5, 0.0,  0.034552],
  [0.5000, 0.5, 0.0,  0.000000],
  [0.2344, 0.5, 0.0,  0.044848],
  [0.2266, 0.5, 0.0,  0.047260],
  [0.1563, 0.5, 0.0,  0.069511],
  [0.0938, 0.5, 0.0,  0.084386],
  [0.0781, 0.5, 0.0,  0.086716],
  [0.0703, 0.5, 0.0,  0.087653],
  [0.0625, 0.5, 0.0,  0.088445],
  [0.0000, 0.5, 0.0,  0.090477]])

  velocity = u.ProbeData(pts, "Velocity")
  (ilen, jlen) = velocity.shape
  pressure = u.ProbeData(pts, "Pressure")

  pts0=vtktools.arr([[0.5, 0.5, 0.0]])  # We're going to subtract off the pressure at the centre point
  press0 = u.ProbeData(pts0, "Pressure")

  norm=0.0
  for i in range(ilen):
      diff = pts[i][3] - (pressure[i][0]-press0[0][0])
      norm = norm + diff*diff

  norm = math.sqrt(norm/ilen)
  print "botella_p2_norm:", norm

  return norm
def botella_p1(NN):
#Botella and Peyret (1998) Table 9. 
  filelist_not_sorted = glob.glob('driven_cavity-%d/*.vtu'%NN)
  vtu_nos_not_sorted = [int(file.split('.vtu')[0].split('_')[-1]) for file in filelist_not_sorted]
  filelist = [filelist_not_sorted[i] for i in numpy.argsort(vtu_nos_not_sorted)]
  file = filelist[-1]
  print file
  try:
    os.stat(file)
  except:
    print "No such file: %s" % file
    sys.exit(1)

  u=vtktools.vtu(file)
  pts=vtktools.arr([
  [0.5, 0.0000, 0.0,  0.110591],
  [0.5, 0.0547, 0.0,  0.109689],
  [0.5, 0.0625, 0.0,  0.109200],
  [0.5, 0.0703, 0.0,  0.108566],
  [0.5, 0.1016, 0.0,  0.104187],
  [0.5, 0.1719, 0.0,  0.081925],
  [0.5, 0.2813, 0.0,  0.040377],
  [0.5, 0.4531, 0.0,  0.004434],
  [0.5, 0.5000, 0.0,  0.000000],
  [0.5, 0.6172, 0.0, -0.000827],
  [0.5, 0.7344, 0.0,  0.012122],
  [0.5, 0.8516, 0.0,  0.034910],
  [0.5, 0.9531, 0.0,  0.050329],
  [0.5, 0.9609, 0.0,  0.050949],
  [0.5, 0.9688, 0.0,  0.051514],
  [0.5, 0.9766, 0.0,  0.052009],
  [0.5, 1.0000, 0.0,  0.052987]])

  velocity = u.ProbeData(pts, "Velocity")
  (ilen, jlen) = velocity.shape
  pressure = u.ProbeData(pts, "Pressure")

  pts0=vtktools.arr([[0.5, 0.5, 0.0]])  # We're going to subtract off the pressure at the centre point
  press0 = u.ProbeData(pts0, "Pressure")

  norm=0.0
  for i in range(ilen):
      diff = pts[i][3] - (pressure[i][0]-press0[0][0])
      norm = norm + diff*diff

  norm = math.sqrt(norm/ilen)
  print "botella_p1_norm:", norm

  return norm
Пример #54
0
def getElementMeshDensity(file):
  v = vtktools.vtu(file)
  l = [0.0] * v.ugrid.GetNumberOfPoints()
  a = vtktools.arr(l)
  c = v.ugrid.GetCell(1)

  for i in range(v.ugrid.GetNumberOfPoints()):
    eles = v.GetPointCells(i)
    sum = 0.0
    for ele in eles:
      points = v.ugrid.GetCell(ele).GetPoints().GetData()
      sum = sum + c.ComputeVolume(points.GetTuple3(1), points.GetTuple3(2),
                                  points.GetTuple3(3), points.GetTuple3(4))
    a[i] = sum / len(eles)
  return a
Пример #55
0
def calc_mld(files,mld_depths):
    for file in files:
        try:
            os.stat(file)
        except:
            print "No such file: %s" % file
            sys.exit(1)
        num = int(file.split(".vtu")[0].split('_')[-1])
        u=vtktools.vtu(file)
        pos = u.GetLocations()
        time = u.GetScalarField('Time')
        tt = time[0]

        # grab the data e need from the VTUs and shove in an array
        den = u.GetScalarField('Density')
        xyz_data = []
        for i in range(0,len(den)):
            if (x0-0.1 < pos[i,0] < x0+0.1 and y0-0.1 < pos[i,1] < y0+0.1):
                xyz_data.append((pos[i,0],pos[i,1],-pos[i,2]+z0,1000*den[i]))
       

        # sorted the array based on depth
        xyz_data = vtktools.arr(xyz_data)
        III = argsort(xyz_data[:,2])
        xyz_data_sorted = xyz_data[III,:]

        # Surface values
        sden = xyz_data_sorted[0,3]

        # grab any values where the UML condition is met for temperature, density and TKE
        uml_den = ((xyz_data_sorted[:,3]) <= (sden+den0)).nonzero()

        # ...on density
        if( (size(uml_den) > 0 ) ):
            LL = uml_den[-1][-1]
            zz = xyz_data_sorted[:,2]
            if (LL+1 < size(zz)):
                zza = zz[LL+1]
                kea = xyz_data_sorted[LL+1,3]
            else:
                zza = zz[LL]
                kea = xyz_data_sorted[LL,3]
            zzb = zz[LL]
            keb = xyz_data_sorted[LL,3]
            tt = tt/(24*60*60)
            time = start_datetime + timedelta(days=tt)
            key = '%04d/%02d/%02d' % (time.year, time.month, time.day)
            mld_depths[key] = (zza-(zzb-zza)*(((sden+den0)-kea)/(kea-keb)))
Пример #56
0
def get_cloud_front(path_prefix, n_files, resolution, threshold):
   
   # Size of the domain
   lx = 0.025
   ly = 4.5
   
   # Arrays to store the results
   # Note: n_files is the number of VTU files to be read.
   upper_positions = numpy.zeros(n_files)
   lower_positions = numpy.zeros(n_files)
   times = numpy.zeros(n_files)

   path = path_prefix# + "/output/"
      
   # For each vtu file...
   for i in range(0, n_files, 20):
      # Open the VTU files one by one
      try:
         file = vtktools.vtu(path + '/mphase_rogue_shock_tube_dense_bed_nylon_' + str(i) + '.pvtu')  
      except:
         print "WARNING: Could not open VTU file!"
         front_position[i] = 0
         times[i] = 0
         continue
      file.GetFieldNames()
      
      time = max(file.GetScalarField('Gas::Time'))
      print "At time t = %f s" % time
      
      # Generate a set of probe positions
      probes = numpy.linspace(1.35, 1.7, (ly/resolution))
      
      # Loop over each of the probes in the y direction, from the top down
      for j in range(len(probes)-1, -1, -1):
         vfrac = vtktools.vtu.ProbeData(file, numpy.array([[0.0, probes[j], 0]]), 'Particles::PhaseVolumeFraction')
         if(vfrac >= 0.3):
            upper_positions[i] = probes[j]
            break
            
      for j in range(0, len(probes)):
         vfrac = vtktools.vtu.ProbeData(file, numpy.array([[0.0, probes[j], 0]]), 'Particles::PhaseVolumeFraction')
         if(vfrac >= 0.01):
            lower_positions[i] = probes[j]
            break

      times[i] = time - 0.0008
         
   return times, upper_positions, lower_positions
Пример #57
0
def plot_tracer(vtu_file, line=None):
    
    u=vtktools.vtu(vtu_file)
    pos = u.GetLocations()
    time = u.GetScalarField('Time')[0]
    t = u.GetScalarField('Tracer')
    ind = get_1d_indices(pos)
    distance = vtktools.arr([pos[i,0] for i in ind])
    tracer = vtktools.arr( [t[i] for i in ind] )

    if (line):
        line.set_ydata(tracer)  # update the data
        draw()
    else:
        line, = plot(distance,tracer,color='k')
        
    return line
Пример #58
0
 def testVtuBoundingBox(self):
   import vtktools
   vtu = vtktools.vtu()    
   points = vtk.vtkPoints()
   points.SetDataTypeToDouble()
   points.InsertNextPoint(-1.0, 2.0, -3.0)
   points.InsertNextPoint(1.0, -2.0, 3.0)
   vtu.ugrid.SetPoints(points)
   lbound, ubound = VtuBoundingBox(vtu).GetBounds()
   self.assertAlmostEquals(lbound[0], -1.0)
   self.assertAlmostEquals(lbound[1], -2.0)
   self.assertAlmostEquals(lbound[2], -3.0)
   self.assertAlmostEquals(ubound[0], 1.0)
   self.assertAlmostEquals(ubound[1], 2.0)
   self.assertAlmostEquals(ubound[2], 3.0)
   
   return
def botella_v(NN):
#Botella and Peyret (1998) Table 10. 
  filelist_not_sorted = glob.glob('driven_cavity-%d/*.vtu'%NN)
  vtu_nos_not_sorted = [int(file.split('.vtu')[0].split('_')[-1]) for file in filelist_not_sorted]
  filelist = [filelist_not_sorted[i] for i in numpy.argsort(vtu_nos_not_sorted)]
  file = filelist[-1]
  print file
  try:
    os.stat(file)
  except:
    print "No such file: %s" % file
    sys.exit(1)

  u=vtktools.vtu(file)
  pts=vtktools.arr([
  [1.0000, 0.5, 0.0,  0.0000000],
  [0.9688, 0.5, 0.0, -0.2279225],
  [0.9609, 0.5, 0.0, -0.2936869],
  [0.9531, 0.5, 0.0, -0.3553213],
  [0.9453, 0.5, 0.0, -0.4103754],
  [0.9063, 0.5, 0.0, -0.5264392],
  [0.8594, 0.5, 0.0, -0.4264545],
  [0.8047, 0.5, 0.0, -0.3202137],
  [0.5000, 0.5, 0.0,  0.0257995],
  [0.2344, 0.5, 0.0,  0.3253592],
  [0.2266, 0.5, 0.0,  0.3339924],
  [0.1563, 0.5, 0.0,  0.3769189],
  [0.0938, 0.5, 0.0,  0.3330442],
  [0.0781, 0.5, 0.0,  0.3099097],
  [0.0703, 0.5, 0.0,  0.2962703],
  [0.0625, 0.5, 0.0,  0.2807056],
  [0.0000, 0.5, 0.0,  0.0000000]])

  velocity = u.ProbeData(pts, "Velocity")
  (ilen, jlen) = velocity.shape

  norm=0.0
  for i in range(ilen):
      diff = pts[i][3] - velocity[i][1]
      norm = norm + diff*diff

  norm = math.sqrt(norm/ilen)
  print "botella_v_norm:", norm

  return norm