Ejemplo n.º 1
0
def read_ascii_t(frame, path="./", file_prefix="fort"):
    r"""Read only the fort.t file and return the data

    :Input:
     - *frame* - (int) Frame number to be read in
     - *path* - (string) Path to the current directory of the file
     - *file_prefix* - (string) Prefix of the files to be read in.
       ``default = 'fort'``

    :Output:
     - (list) List of output variables
      - *t* - (int) Time of frame
      - *meqn* - (int) Number of equations in the frame
      - *ngrids* - (int) Number of grids
      - *maux* - (int) Auxillary value in the frame
      - *ndim* - (int) Number of dimensions in q and aux

    """

    base_path = os.path.join(path, )
    path = os.path.join(base_path, "%s.t" % file_prefix) + str(frame).zfill(4)
    try:
        logger.debug("Opening %s file." % path)
        f = open(path, "r")

        t = read_data_line(f)
        meqn = read_data_line(f, type="int")
        ngrids = read_data_line(f, type="int")
        maux = read_data_line(f, type="int")
        ndim = read_data_line(f, type="int")

        f.close()
    except (IOError):
        raise
    except:
        logger.error("File " + t_fname +
                     " should contain t, meqn, ngrids, maux, ndim")
        print(("File " + t_fname +
               " should contain t, meqn, ngrids, maux, ndim"))
        raise

    return t, meqn, ngrids, maux, ndim
Ejemplo n.º 2
0
def read_ascii_t(frame, path='./', file_prefix='fort'):
    r"""Read only the fort.t file and return the data
    
    :Input:
     - *frame* - (int) Frame number to be read in
     - *path* - (string) Path to the current directory of the file
     - *file_prefix* - (string) Prefix of the files to be read in.  
       ``default = 'fort'``
     
    :Output:
     - (list) List of output variables
     - *t* - (int) Time of frame
     - *num_eqn* - (int) Number of equations in the frame
     - *nstates* - (int) Number of states
     - *num_aux* - (int) Auxillary value in the frame
     - *num_dim* - (int) Number of dimensions in q and aux
    
    """

    base_path = os.path.join(path, )
    path = os.path.join(base_path, '%s.t' % file_prefix) + str(frame).zfill(4)
    try:
        logger.debug("Opening %s file." % path)
        f = open(path, 'r')

        t = read_data_line(f)
        num_eqn = read_data_line(f, type='int')
        nstates = read_data_line(f, type='int')
        num_aux = read_data_line(f, type='int')
        num_dim = read_data_line(f, type='int')

        f.close()
    except (IOError):
        raise
    except:
        logger.error("File " + path +
                     " should contain t, num_eqn, nstates, num_aux, num_dim")
        print "File " + path + " should contain t, num_eqn, nstates, num_aux, num_dim"
        raise

    return t, num_eqn, nstates, num_aux, num_dim
Ejemplo n.º 3
0
def read_ascii_t(frame,path='./',file_prefix='fort'):
    r"""Read only the fort.t file and return the data
    
    :Input:
     - *frame* - (int) Frame number to be read in
     - *path* - (string) Path to the current directory of the file
     - *file_prefix* - (string) Prefix of the files to be read in.  
       ``default = 'fort'``
     
    :Output:
     - (list) List of output variables
     - *t* - (int) Time of frame
     - *meqn* - (int) Number of equations in the frame
     - *nstates* - (int) Number of states
     - *maux* - (int) Auxillary value in the frame
     - *ndim* - (int) Number of dimensions in q and aux
    
    """

    base_path = os.path.join(path,)
    path = os.path.join(base_path, '%s.t' % file_prefix) + str(frame).zfill(4)
    try:
        logger.debug("Opening %s file." % path)
        f = open(path,'r')
        
        t = read_data_line(f)
        meqn = read_data_line(f,type='int')
        nstates = read_data_line(f,type='int')
        maux = read_data_line(f,type='int')
        ndim = read_data_line(f,type='int')
        
        f.close()
    except(IOError):
        raise
    except:
        logger.error("File " + t_fname + " should contain t, meqn, nstates, maux, ndim")
        print "File " + t_fname + " should contain t, meqn, nstates, maux, ndim"
        raise
        
    return t,meqn,nstates,maux,ndim
Ejemplo n.º 4
0
def read_ascii(solution,frame,path='./',file_prefix='fort',read_aux=False,
                options={}):
    r"""
    Read in a set of ascii formatted files
    
    This routine reads the ascii formatted files corresponding to the classic
    clawpack format 'fort.txxxx', 'fort.qxxxx', and 'fort.axxxx' or 'fort.aux'
    Note that the fort prefix can be changed.
    
    :Input:
     - *solution* - (:class:`~pyclaw.solution.Solution`) Solution object to 
       read the data into.
     - *frame* - (int) Frame number to be read in
     - *path* - (string) Path to the current directory of the file
     - *file_prefix* - (string) Prefix of the files to be read in.  
       ``default = 'fort'``
     - *read_aux* (bool) Whether or not an auxillary file will try to be read 
       in.  ``default = False``
     - *options* - (dict) Dictionary of options particular to this format 
       which in the case of ``ascii`` files is empty.
    
    """
    
    import numpy as np

    # Option parsing
    option_defaults = {}
    
    for (k,v) in option_defaults.iteritems():
        if options.has_key(k):
            exec("%s = options['%s']" % (k,k))
        else:
            exec('%s = v' % k)

    if frame < 0:
        # Don't construct file names with negative frameno values.
        raise IOError("Frame " + str(frame) + " does not exist ***")

    # Construct path names
    base_path = os.path.join(path,)
    # t_fname = os.path.join(base_path, '%s.t' % file_prefix) + str(frame).zfill(4)
    q_fname = os.path.join(base_path, '%s.q' % file_prefix) + str(frame).zfill(4)

    # Read in values from fort.t file:
    [t,meqn,nstates,maux,ndim] = read_ascii_t(frame,path,file_prefix)
    
    # Read in values from fort.q file:
    try:
        f = open(q_fname,'r')
    
        # Loop through every grid setting the appropriate information
        # for ng in range(len(solution.grids)):
        for m in xrange(nstates):
        
            # Read in base header for this grid
            gridno = read_data_line(f,type='int')
            level = read_data_line(f,type='int')
            n = np.zeros((ndim))
            lower = np.zeros((ndim))
            d = np.zeros((ndim))
            for i in xrange(ndim):
                n[i] = read_data_line(f,type='int')
            for i in xrange(ndim):
                lower[i] = read_data_line(f)
            for i in xrange(ndim):
                d[i] = read_data_line(f)
        
            blank = f.readline()
        
            # Construct the grid
            # Since we do not have names here, we will construct the grid with
            # the assumed dimensions x,y,z
            names = ['x','y','z']
            dimensions = []
            for i in xrange(ndim):
                dimensions.append(
                    pyclaw.grid.Dimension(names[i],lower[i],lower[i] + n[i]*d[i],n[i]))
            grid = pyclaw.grid.Grid(dimensions)
            state= pyclaw.state.State(grid,meqn,maux)
            state.t = t


            # RJL 1/8/10:  Changed empty_aux to zeros_aux below so aux won't
            # be filled with random values if aux arrays not read in.  Would
            # like to delete this and initialize grid.aux only if it will be
            # read in below, but for some reason that doesn't work.

            if maux > 0:   
                state.aux[:]=0.
            
            # Fill in q values
            if grid.ndim == 1:
                for i in xrange(grid.dimensions[0].n):
                    l = []
                    while len(l)<state.meqn:
                        line = f.readline()
                        l = l + line.split()
                    for m in xrange(state.meqn):
                        state.q[m,i] = float(l[m])
            elif grid.ndim == 2:
                for j in xrange(grid.dimensions[1].n):
                    for i in xrange(grid.dimensions[0].n):
                        l = []
                        while len(l)<state.meqn:
                            line = f.readline()
                            l = l + line.split()
                        for m in xrange(state.meqn):
                            state.q[m,i,j] = float(l[m])
                    blank = f.readline()
            elif grid.ndim == 3:
                raise NotImplementedError("3d still does not work!")
                for k in xrange(grid.dimensions[2].n):
                    for j in xrange(grid.dimensions[1].n):
                        for i in xrange(grid.dimensions[0].n):
                            l=[]
                            while len(l) < state.meqn:
                                line = f.readline()
                                l = l + line.split()
                            for m in xrange(state.meqn):
                                state.q[m,i,j,k] = float(l[m])
                        blank = f.readline()
                    blank = f.readline()
            else:
                msg = "Read only supported up to 3d."
                logger.critical(msg)
                raise Exception(msg)
        
            # Add AMR attributes:
            grid.gridno = gridno
            grid.level = level

            # Add new grid to solution
            solution.states.append(state)
            
    except(IOError):
        raise
    except:
        logger.error("File %s was not able to be read." % q_fname)
        raise

    # Read auxillary file if available and requested
    if solution.states[0].maux > 0 and read_aux:
        # Check for aux file
        fname1 = os.path.join(base_path,'%s.a' % file_prefix)+str(frame).zfill(4)
        fname2 = os.path.join(base_path,'%s.a' % file_prefix)
        if os.path.exists(fname1):
            fname = fname1
        elif os.path.exists(fname2):
            fname = fname2
        else:
            logger.info("Unable to open auxillary file %s or %s" % (fname1,fname2))
            return
            
        # Found a valid path, try to open and read it
        try:
            f = open(fname,'r')
            
            # Read in aux file
            for n in xrange(len(solution.states)):
                # Fetch correct grid
                gridno = read_data_line(f,type='int')
                grid = solution.states[gridno-1].grid
        
                # These should match this grid already, raise exception otherwise
                if not (grid.level == read_data_line(f,type='int')):
                    raise IOError("Grid level in aux file header did not match grid no %s." % grid.gridno)
                for dim in grid.dimensions:
                    if not (dim.n == read_data_line(f,type='int')):
                        raise IOError("Dimension %s's n in aux file header did not match grid no %s." % (dim.name,grid.gridno))
                for dim in grid.dimensions:
                    if not (dim.lower == read_data_line(f,type='float')):
                        raise IOError("Dimension %s's lower in aux file header did not match grid no %s." % (dim.name,grid.gridno))
                for dim in grid.dimensions:
                    if not (dim.d == read_data_line(f,type='float')):
                        raise IOError("Dimension %s's d in aux file header did not match grid no %s." % (dim.name,grid.gridno))

                f.readline()
        
                # Read in auxillary array
                if grid.ndim == 1:
                    for i in xrange(grid.dimensions[0].n):
                        l = []
                        while len(l)<state.maux:
                            line = f.readline()
                            l = l + line.split()
                        for m in xrange(state.maux):
                            state.aux[i,m] = float(l[m])
                elif grid.ndim == 2:
                    for j in xrange(grid.dimensions[1].n):
                        for i in xrange(grid.dimensions[0].n):
                            l = []
                            while len(l)<state.maux:
                                line = f.readline()
                                l = l + line.split()
                            for m in xrange(state.maux):
                                state.aux[i,j,m] = float(l[m])
                        blank = f.readline()
                elif grid.ndim == 3:
                    for k in xrange(grid.dimensions[2].n):
                        for j in xrange(grid.dimensions[1].n):
                            for i in xrange(grid.dimensions[0].n):
                                l = []
                                while len(l)<state.maux:
                                    line = f.readline()
                                    l = l + line.split()
                                for m in xrange(state.maux):
                                    state.aux[i,j,k,m] = float(l[m])
                            blank = f.readline()
                        blank = f.readline()
                else:
                    logger.critical("Read aux only up to 3d is supported.")
                    raise Exception("Read aux only up to 3d is supported.")
        except(IOError):
            raise
        except:
            logger.error("File %s was not able to be read." % q_fname)
            raise
Ejemplo n.º 5
0
def read_ascii(solution,
               frame,
               path='./',
               file_prefix='fort',
               read_aux=False,
               options={}):
    r"""
    Read in a set of ascii formatted files
    
    This routine reads the ascii formatted files corresponding to the classic
    clawpack format 'fort.txxxx', 'fort.qxxxx', and 'fort.axxxx' or 'fort.aux'
    Note that the fort prefix can be changed.
    
    :Input:
     - *solution* - (:class:`~pyclaw.solution.Solution`) Solution object to 
       read the data into.
     - *frame* - (int) Frame number to be read in
     - *path* - (string) Path to the current directory of the file
     - *file_prefix* - (string) Prefix of the files to be read in.  
       ``default = 'fort'``
     - *read_aux* (bool) Whether or not an auxillary file will try to be read 
       in.  ``default = False``
     - *options* - (dict) Dictionary of options particular to this format 
       which in the case of ``ascii`` files is empty.
    
    """

    # Option parsing
    option_defaults = {}

    for (k, v) in option_defaults.iteritems():
        if options.has_key(k):
            exec("%s = options['%s']" % (k, k))
        else:
            exec('%s = v' % k)

    if frame < 0:
        # Don't construct file names with negative frameno values.
        raise IOError("Frame " + str(frame) + " does not exist ***")

    # Construct path names
    base_path = os.path.join(path, )
    # t_fname = os.path.join(base_path, '%s.t' % file_prefix) + str(frame).zfill(4)
    q_fname = os.path.join(base_path,
                           '%s.q' % file_prefix) + str(frame).zfill(4)

    # Read in values from fort.t file:
    [t, meqn, ngrids, maux, ndim] = read_ascii_t(frame, path, file_prefix)

    # Read in values from fort.q file:
    try:
        f = open(q_fname, 'r')

        # Loop through every grid setting the appropriate information
        # for ng in range(len(solution.grids)):
        for m in xrange(ngrids):

            # Read in base header for this grid
            gridno = read_data_line(f, type='int')
            level = read_data_line(f, type='int')
            n = np.zeros((ndim))
            lower = np.zeros((ndim))
            d = np.zeros((ndim))
            for i in xrange(ndim):
                n[i] = read_data_line(f, type='int')
            for i in xrange(ndim):
                lower[i] = read_data_line(f)
            for i in xrange(ndim):
                d[i] = read_data_line(f)

            blank = f.readline()

            # Construct the grid
            # Since we do not have names here, we will construct the grid with
            # the assumed dimensions x,y,z
            names = ['x', 'y', 'z']
            dimensions = []
            for i in xrange(ndim):
                dimensions.append(
                    pyclaw.solution.Dimension(names[i], lower[i],
                                              lower[i] + n[i] * d[i], n[i]))
            grid = pyclaw.solution.Grid(dimensions)
            grid.t = t
            grid.meqn = meqn

            # RJL 1/8/10:  Changed empty_aux to zeros_aux below so aux won't
            # be filled with random values if aux arrays not read in.  Would
            # like to delete this and initialize grid.aux only if it will be
            # read in below, but for some reason that doesn't work.

            if maux > 0:
                grid.zeros_aux(maux)

            # Fill in q values
            grid.empty_q()
            if grid.ndim == 1:
                for i in xrange(grid.dimensions[0].n):
                    l = []
                    while len(l) < grid.meqn:
                        line = f.readline()
                        l = l + line.split()
                    for m in xrange(grid.meqn):
                        grid.q[i, m] = float(l[m])
            elif grid.ndim == 2:
                for j in xrange(grid.dimensions[1].n):
                    for i in xrange(grid.dimensions[0].n):
                        l = []
                        while len(l) < grid.meqn:
                            line = f.readline()
                            l = l + line.split()
                        for m in xrange(grid.meqn):
                            grid.q[i, j, m] = float(l[m])
                    blank = f.readline()
            elif grid.ndim == 3:
                raise NotImplementedError("3d still does not work!")
                for k in xrange(grid.dimensions[2].n):
                    for j in xrange(grid.dimensions[1].n):
                        for i in xrange(grid.dimensions[0].n):
                            l = []
                            while len(l) < grid.meqn:
                                line = f.readline()
                                l = l + line.split()
                            for m in xrange(grid.meqn):
                                grid.q[i, j, k, m] = float(l[m])
                        blank = f.readline()
                    blank = f.readline()
            else:
                msg = "Read only supported up to 3d."
                logger.critical(msg)
                raise Exception(msg)

            # Add AMR attributes:
            grid.gridno = gridno
            grid.level = level

            # Add new grid to solution
            solution.grids.append(grid)

    except (IOError):
        raise
    except:
        logger.error("File %s was not able to be read." % q_fname)
        raise

    # Read auxillary file if available and requested
    if solution.grids[0].maux > 0 and read_aux:
        # Check for aux file
        fname1 = os.path.join(base_path,
                              '%s.a' % file_prefix) + str(frame).zfill(4)
        fname2 = os.path.join(base_path, '%s.a' % file_prefix)
        if os.path.exists(fname1):
            fname = fname1
        elif os.path.exists(fname2):
            fname = fname2
        else:
            logger.info("Unable to open auxillary file %s or %s" %
                        (fname1, fname2))
            return

        # Found a valid path, try to open and read it
        try:
            f = open(fname, 'r')

            # Read in aux file
            for n in xrange(len(solution.grids)):
                # Fetch correct grid
                gridno = read_data_line(f, type='int')
                grid = solution.grids[gridno - 1]

                # These should match this grid already, raise exception otherwise
                if not (grid.level == read_data_line(f, type='int')):
                    raise IOError(
                        "Grid level in aux file header did not match grid no %s."
                        % grid.gridno)
                for dim in grid.dimensions:
                    if not (dim.n == read_data_line(f, type='int')):
                        raise IOError(
                            "Dimension %s's n in aux file header did not match grid no %s."
                            % (dim.name, grid.gridno))
                for dim in grid.dimensions:
                    if not (dim.lower == read_data_line(f, type='float')):
                        raise IOError(
                            "Dimension %s's lower in aux file header did not match grid no %s."
                            % (dim.name, grid.gridno))
                for dim in grid.dimensions:
                    if not (dim.d == read_data_line(f, type='float')):
                        raise IOError(
                            "Dimension %s's d in aux file header did not match grid no %s."
                            % (dim.name, grid.gridno))

                f.readline()

                # Read in auxillary array
                if grid.ndim == 1:
                    for i in xrange(grid.dimensions[0].n):
                        l = []
                        while len(l) < grid.maux:
                            line = f.readline()
                            l = l + line.split()
                        for m in xrange(grid.maux):
                            grid.aux[i, m] = float(l[m])
                elif grid.ndim == 2:
                    for j in xrange(grid.dimensions[1].n):
                        for i in xrange(grid.dimensions[0].n):
                            l = []
                            while len(l) < grid.maux:
                                line = f.readline()
                                l = l + line.split()
                            for m in xrange(grid.maux):
                                grid.aux[i, j, m] = float(l[m])
                        blank = f.readline()
                elif grid.ndim == 3:
                    for k in xrange(grid.dimensions[2].n):
                        for j in xrange(grid.dimensions[1].n):
                            for i in xrange(grid.dimensions[0].n):
                                l = []
                                while len(l) < grid.maux:
                                    line = f.readline()
                                    l = l + line.split()
                                for m in xrange(grid.maux):
                                    grid.aux[i, j, k, m] = float(l[m])
                            blank = f.readline()
                        blank = f.readline()
                else:
                    logger.critical("Read aux only up to 3d is supported.")
                    raise Exception("Read aux only up to 3d is supported.")
        except (IOError):
            raise
        except:
            logger.error("File %s was not able to be read." % q_fname)
            raise
Ejemplo n.º 6
0
def read_ascii(solution,
               frame,
               path='./',
               file_prefix='fort',
               read_aux=False,
               options={}):
    r"""
    Read in a set of ascii formatted files
    
    This routine reads the ascii formatted files corresponding to the classic
    clawpack format 'fort.txxxx', 'fort.qxxxx', and 'fort.axxxx' or 'fort.aux'
    Note that the fort prefix can be changed.
    
    :Input:
     - *solution* - (:class:`~pyclaw.solution.Solution`) Solution object to 
       read the data into.
     - *frame* - (int) Frame number to be read in
     - *path* - (string) Path to the current directory of the file
     - *file_prefix* - (string) Prefix of the files to be read in.  
       ``default = 'fort'``
     - *read_aux* (bool) Whether or not an auxillary file will try to be read 
       in.  ``default = False``
     - *options* - (dict) Dictionary of optional arguments dependent on 
       the format being read in.  ``default = {}``
    """

    import numpy as np

    if frame < 0:
        # Don't construct file names with negative frameno values.
        raise IOError("Frame " + str(frame) + " does not exist ***")

    # Construct path names
    base_path = os.path.join(path, )
    # t_fname = os.path.join(base_path, '%s.t' % file_prefix) + str(frame).zfill(4)
    q_fname = os.path.join(base_path,
                           '%s.q' % file_prefix) + str(frame).zfill(4)

    # Read in values from fort.t file:
    [t, num_eqn, nstates, num_aux,
     num_dim] = read_ascii_t(frame, path, file_prefix)

    patches = []

    # Read in values from fort.q file:
    try:
        f = open(q_fname, 'r')

        # Loop through every patch setting the appropriate information
        # for ng in range(len(solution.patchs)):
        for m in xrange(nstates):

            # Read in base header for this patch
            patch_index = read_data_line(f, type='int')
            level = read_data_line(f, type='int')
            n = np.zeros((num_dim))
            lower = np.zeros((num_dim))
            d = np.zeros((num_dim))
            for i in xrange(num_dim):
                n[i] = read_data_line(f, type='int')
            for i in xrange(num_dim):
                lower[i] = read_data_line(f)
            for i in xrange(num_dim):
                d[i] = read_data_line(f)

            blank = f.readline()

            # Construct the patch
            # Since we do not have names here, we will construct the patch with
            # the assumed dimensions x,y,z
            names = ['x', 'y', 'z']
            dimensions = []
            for i in xrange(num_dim):
                dimensions.append(
                    pyclaw.geometry.Dimension(names[i], lower[i],
                                              lower[i] + n[i] * d[i], n[i]))
            patch = pyclaw.geometry.Patch(dimensions)
            state = pyclaw.state.State(patch, num_eqn, num_aux)
            state.t = t

            # RJL 1/8/10:  Changed empty_aux to zeros_aux below so aux won't
            # be filled with random values if aux arrays not read in.  Would
            # like to delete this and initialize patch.aux only if it will be
            # read in below, but for some reason that doesn't work.

            if num_aux > 0:
                state.aux[:] = 0.

            # Fill in q values
            if patch.num_dim == 1:
                for i in xrange(patch.dimensions[0].num_cells):
                    l = []
                    while len(l) < state.num_eqn:
                        line = f.readline()
                        l = l + line.split()
                    for m in xrange(state.num_eqn):
                        state.q[m, i] = float(l[m])
            elif patch.num_dim == 2:
                for j in xrange(patch.dimensions[1].num_cells):
                    for i in xrange(patch.dimensions[0].num_cells):
                        l = []
                        while len(l) < state.num_eqn:
                            line = f.readline()
                            l = l + line.split()
                        for m in xrange(state.num_eqn):
                            state.q[m, i, j] = float(l[m])
                    blank = f.readline()
            elif patch.num_dim == 3:
                for k in xrange(patch.dimensions[2].num_cells):
                    for j in xrange(patch.dimensions[1].num_cells):
                        for i in xrange(patch.dimensions[0].num_cells):
                            l = []
                            while len(l) < state.num_eqn:
                                line = f.readline()
                                l = l + line.split()
                            for m in xrange(state.num_eqn):
                                state.q[m, i, j, k] = float(l[m])
                        blank = f.readline()
                    blank = f.readline()
            else:
                msg = "Read only supported up to 3d."
                logger.critical(msg)
                raise Exception(msg)

            # Add AMR attributes:
            patch.patch_index = patch_index
            patch.level = level

            # Add new patch to solution
            solution.states.append(state)
            patches.append(state.patch)
        solution.domain = pyclaw.geometry.Domain(patches)

    except (IOError):
        raise
    except:
        logger.error("File %s was not able to be read." % q_fname)
        raise

    # Read auxillary file if available and requested
    if solution.states[0].num_aux > 0 and read_aux:
        # Check for aux file
        fname1 = os.path.join(base_path,
                              '%s.a' % file_prefix) + str(frame).zfill(4)
        fname2 = os.path.join(base_path, '%s.a' % file_prefix)
        if os.path.exists(fname1):
            fname = fname1
        elif os.path.exists(fname2):
            fname = fname2
        else:
            logger.info("Unable to open auxillary file %s or %s" %
                        (fname1, fname2))
            return

        # Found a valid path, try to open and read it
        try:
            f = open(fname, 'r')

            # Read in aux file
            for n in xrange(len(solution.states)):
                # Fetch correct patch
                patch_index = read_data_line(f, type='int')
                patch = solution.states[patch_index - 1].patch

                # These should match this patch already, raise exception otherwise
                if not (patch.level == read_data_line(f, type='int')):
                    raise IOError(
                        "Patch level in aux file header did not match patch no %s."
                        % patch.patch_index)
                for dim in patch.dimensions:
                    if not (dim.num_cells == read_data_line(f, type='int')):
                        raise IOError(
                            "Dimension %s's n in aux file header did not match patch no %s."
                            % (dim.name, patch.patch_index))
                for dim in patch.dimensions:
                    if not (dim.lower == read_data_line(f, type='float')):
                        raise IOError(
                            "Dimension %s's lower in aux file header did not match patch no %s."
                            % (dim.name, patch.patch_index))
                for dim in patch.dimensions:
                    if not (dim.delta == read_data_line(f, type='float')):
                        raise IOError(
                            "Dimension %s's d in aux file header did not match patch no %s."
                            % (dim.name, patch.patch_index))

                f.readline()

                # Read in auxillary array
                if patch.num_dim == 1:
                    for i in xrange(patch.dimensions[0].num_cells):
                        l = []
                        while len(l) < state.num_aux:
                            line = f.readline()
                            l = l + line.split()
                        for m in xrange(state.num_aux):
                            state.aux[m, i] = float(l[m])
                elif patch.num_dim == 2:
                    for j in xrange(patch.dimensions[1].num_cells):
                        for i in xrange(patch.dimensions[0].num_cells):
                            l = []
                            while len(l) < state.num_aux:
                                line = f.readline()
                                l = l + line.split()
                            for m in xrange(state.num_aux):
                                state.aux[m, i, j] = float(l[m])
                        blank = f.readline()
                elif patch.num_dim == 3:
                    for k in xrange(patch.dimensions[2].num_cells):
                        for j in xrange(patch.dimensions[1].num_cells):
                            for i in xrange(patch.dimensions[0].num_cells):
                                l = []
                                while len(l) < state.num_aux:
                                    line = f.readline()
                                    l = l + line.split()
                                for m in xrange(state.num_aux):
                                    state.aux[m, i, j, k] = float(l[m])
                            blank = f.readline()
                        blank = f.readline()
                else:
                    logger.critical("Read aux only up to 3d is supported.")
                    raise Exception("Read aux only up to 3d is supported.")
        except (IOError):
            raise
        except:
            logger.error("File %s was not able to be read." % q_fname)
            raise
Ejemplo n.º 7
0
def read_ascii(solution,frame,path='./',file_prefix='fort',read_aux=False,
                options={}):
    r"""
    Read in a set of ascii formatted files
    
    This routine reads the ascii formatted files corresponding to the classic
    clawpack format 'fort.txxxx', 'fort.qxxxx', and 'fort.axxxx' or 'fort.aux'
    Note that the fort prefix can be changed.
    
    :Input:
     - *solution* - (:class:`~pyclaw.solution.Solution`) Solution object to 
       read the data into.
     - *frame* - (int) Frame number to be read in
     - *path* - (string) Path to the current directory of the file
     - *file_prefix* - (string) Prefix of the files to be read in.  
       ``default = 'fort'``
     - *read_aux* (bool) Whether or not an auxillary file will try to be read 
       in.  ``default = False``
     - *options* - (dict) Dictionary of optional arguments dependent on 
       the format being read in.  ``default = {}``
    """
    
    import numpy as np

    if frame < 0:
        # Don't construct file names with negative frameno values.
        raise IOError("Frame " + str(frame) + " does not exist ***")

    # Construct path names
    base_path = os.path.join(path,)
    # t_fname = os.path.join(base_path, '%s.t' % file_prefix) + str(frame).zfill(4)
    q_fname = os.path.join(base_path, '%s.q' % file_prefix) + str(frame).zfill(4)

    # Read in values from fort.t file:
    [t,num_eqn,nstates,num_aux,num_dim] = read_ascii_t(frame,path,file_prefix)

    patches = []
    
    # Read in values from fort.q file:
    try:
        f = open(q_fname,'r')
    
        # Loop through every patch setting the appropriate information
        # for ng in range(len(solution.patchs)):
        for m in xrange(nstates):
        
            # Read in base header for this patch
            patch_index = read_data_line(f,type='int')
            level = read_data_line(f,type='int')
            n = np.zeros((num_dim))
            lower = np.zeros((num_dim))
            d = np.zeros((num_dim))
            for i in xrange(num_dim):
                n[i] = read_data_line(f,type='int')
            for i in xrange(num_dim):
                lower[i] = read_data_line(f)
            for i in xrange(num_dim):
                d[i] = read_data_line(f)
        
            blank = f.readline()
        
            # Construct the patch
            # Since we do not have names here, we will construct the patch with
            # the assumed dimensions x,y,z
            names = ['x','y','z']
            dimensions = []
            for i in xrange(num_dim):
                dimensions.append(
                    pyclaw.geometry.Dimension(names[i],lower[i],lower[i] + n[i]*d[i],n[i]))
            patch = pyclaw.geometry.Patch(dimensions)
            state= pyclaw.state.State(patch,num_eqn,num_aux)
            state.t = t


            # RJL 1/8/10:  Changed empty_aux to zeros_aux below so aux won't
            # be filled with random values if aux arrays not read in.  Would
            # like to delete this and initialize patch.aux only if it will be
            # read in below, but for some reason that doesn't work.

            if num_aux > 0:   
                state.aux[:]=0.
            
            # Fill in q values
            if patch.num_dim == 1:
                for i in xrange(patch.dimensions[0].num_cells):
                    l = []
                    while len(l)<state.num_eqn:
                        line = f.readline()
                        l = l + line.split()
                    for m in xrange(state.num_eqn):
                        state.q[m,i] = float(l[m])
            elif patch.num_dim == 2:
                for j in xrange(patch.dimensions[1].num_cells):
                    for i in xrange(patch.dimensions[0].num_cells):
                        l = []
                        while len(l)<state.num_eqn:
                            line = f.readline()
                            l = l + line.split()
                        for m in xrange(state.num_eqn):
                            state.q[m,i,j] = float(l[m])
                    blank = f.readline()
            elif patch.num_dim == 3:
                for k in xrange(patch.dimensions[2].num_cells):
                    for j in xrange(patch.dimensions[1].num_cells):
                        for i in xrange(patch.dimensions[0].num_cells):
                            l=[]
                            while len(l) < state.num_eqn:
                                line = f.readline()
                                l = l + line.split()
                            for m in xrange(state.num_eqn):
                                state.q[m,i,j,k] = float(l[m])
                        blank = f.readline()
                    blank = f.readline()
            else:
                msg = "Read only supported up to 3d."
                logger.critical(msg)
                raise Exception(msg)
        
            # Add AMR attributes:
            patch.patch_index = patch_index
            patch.level = level

            # Add new patch to solution
            solution.states.append(state)
            patches.append(state.patch)
        solution.domain = pyclaw.geometry.Domain(patches)
            
    except(IOError):
        raise
    except:
        logger.error("File %s was not able to be read." % q_fname)
        raise

    # Read auxillary file if available and requested
    if solution.states[0].num_aux > 0 and read_aux:
        # Check for aux file
        fname1 = os.path.join(base_path,'%s.a' % file_prefix)+str(frame).zfill(4)
        fname2 = os.path.join(base_path,'%s.a' % file_prefix)
        if os.path.exists(fname1):
            fname = fname1
        elif os.path.exists(fname2):
            fname = fname2
        else:
            logger.info("Unable to open auxillary file %s or %s" % (fname1,fname2))
            return
            
        # Found a valid path, try to open and read it
        try:
            f = open(fname,'r')
            
            # Read in aux file
            for n in xrange(len(solution.states)):
                # Fetch correct patch
                patch_index = read_data_line(f,type='int')
                patch = solution.states[patch_index-1].patch
        
                # These should match this patch already, raise exception otherwise
                if not (patch.level == read_data_line(f,type='int')):
                    raise IOError("Patch level in aux file header did not match patch no %s." % patch.patch_index)
                for dim in patch.dimensions:
                    if not (dim.num_cells == read_data_line(f,type='int')):
                        raise IOError("Dimension %s's n in aux file header did not match patch no %s." % (dim.name,patch.patch_index))
                for dim in patch.dimensions:
                    if not (dim.lower == read_data_line(f,type='float')):
                        raise IOError("Dimension %s's lower in aux file header did not match patch no %s." % (dim.name,patch.patch_index))
                for dim in patch.dimensions:
                    if not (dim.delta == read_data_line(f,type='float')):
                        raise IOError("Dimension %s's d in aux file header did not match patch no %s." % (dim.name,patch.patch_index))

                f.readline()
        
                # Read in auxillary array
                if patch.num_dim == 1:
                    for i in xrange(patch.dimensions[0].num_cells):
                        l = []
                        while len(l)<state.num_aux:
                            line = f.readline()
                            l = l + line.split()
                        for m in xrange(state.num_aux):
                            state.aux[m,i] = float(l[m])
                elif patch.num_dim == 2:
                    for j in xrange(patch.dimensions[1].num_cells):
                        for i in xrange(patch.dimensions[0].num_cells):
                            l = []
                            while len(l)<state.num_aux:
                                line = f.readline()
                                l = l + line.split()
                            for m in xrange(state.num_aux):
                                state.aux[m,i,j] = float(l[m])
                        blank = f.readline()
                elif patch.num_dim == 3:
                    for k in xrange(patch.dimensions[2].num_cells):
                        for j in xrange(patch.dimensions[1].num_cells):
                            for i in xrange(patch.dimensions[0].num_cells):
                                l = []
                                while len(l)<state.num_aux:
                                    line = f.readline()
                                    l = l + line.split()
                                for m in xrange(state.num_aux):
                                    state.aux[m,i,j,k] = float(l[m])
                            blank = f.readline()
                        blank = f.readline()
                else:
                    logger.critical("Read aux only up to 3d is supported.")
                    raise Exception("Read aux only up to 3d is supported.")
        except(IOError):
            raise
        except:
            logger.error("File %s was not able to be read." % q_fname)
            raise