Esempio n. 1
0
def _test4():
    from numpy import sin, zeros, exp
    # check vectorization evaluation:
    g = UniformBoxGrid(min=(0, 0), max=(1, 1), division=(3, 3))
    try:
        g.vectorized_eval(lambda x, y: 2)
    except TypeError as msg:
        # fine, expect to arrive here
        print '*** Expected error in this test:', msg
    try:
        g.vectorized_eval(lambda x, y: zeros((2, 2)) + 2)
    except IndexError as msg:
        # fine, expect to arrive here
        print '*** Expected error in this test:', msg

    a = g.vectorized_eval(lambda x, y: sin(x) * exp(y - x))
    print a
    a = g.vectorized_eval(lambda x, y: zeros(g.shape) + 2)
    print a
Esempio n. 2
0
def _test4():
    from numpy import sin, zeros, exp
    # check vectorization evaluation:
    g = UniformBoxGrid(min=(0,0), max=(1,1), division=(3,3))
    try:
        g.vectorized_eval(lambda x,y: 2)
    except TypeError as msg:
        # fine, expect to arrive here
        print '*** Expected error in this test:', msg
    try:
        g.vectorized_eval(lambda x,y: zeros((2,2))+2)
    except IndexError as msg:
        # fine, expect to arrive here
        print '*** Expected error in this test:', msg

    a = g.vectorized_eval(lambda x,y: sin(x)*exp(y-x))
    print a
    a = g.vectorized_eval(lambda x,y: zeros(g.shape)+2)
    print a
Esempio n. 3
0
    def __init__(
        self,
        min=(0, 0),  # minimum coordinates
        max=(1, 1),  # maximum coordinates
        division=(4, 4),  # cell divisions
        dirnames=('x', 'y', 'z')):  # names of the directions
        """
        Initialize a BoxGrid by giving domain range (minimum and
        maximum coordinates: min and max tuples/lists/arrays)
        and number of cells in each space direction (division tuple/list/array).
        The dirnames tuple/list holds the names of the coordinates in
        the various spatial directions.

        >>> g = UniformBoxGrid(min=0, max=1, division=10)
        >>> g = UniformBoxGrid(min=(0,-1), max=(1,1), division=(10,4))
        >>> g = UniformBoxGrid(min=(0,0,-1), max=(2,1,1), division=(2,3,5))
        """
        # Allow int/float specifications in one-dimensional grids
        # (just turn to lists for later multi-dimensional processing)
        if isinstance(min, (int, float)):
            min = [min]
        if isinstance(max, (int, float)):
            max = [max]
        if isinstance(division, (int, float)):
            division = [division]
        if isinstance(dirnames, str):
            dirnames = [dirnames]

        self.nsd = len(min)
        # strip dirnames down to right space dim (in case the default
        # with three components were unchanged by the user):
        dirnames = dirnames[:self.nsd]

        # check consistent lengths:
        for a in max, division:
            if len(a) != self.nsd:
                raise ValueError(
                    'Incompatible lengths of arguments to constructor'\
                    ' (%d != %d)' % (len(a), self.nsd))

        self.min_coor = array(min, float)
        self.max_coor = array(max, float)
        self.dirnames = dirnames
        self.division = division
        self.coor = [None] * self.nsd
        self.shape = [0] * self.nsd
        self.delta = zeros(self.nsd)

        for i in range(self.nsd):
            self.delta[i] = \
                 (self.max_coor[i] -  self.min_coor[i])/float(self.division[i])
            self.shape[i] = self.division[i] + 1  # no of grid points
            self.coor[i] = \
                 linspace(self.min_coor[i], self.max_coor[i], self.shape[i])
        self._more_init()
Esempio n. 4
0
    def __init__(self,
                 min=(0,0),                  # minimum coordinates
                 max=(1,1),                  # maximum coordinates
                 division=(4,4),             # cell divisions
                 dirnames=('x', 'y', 'z')):  # names of the directions
        """
        Initialize a BoxGrid by giving domain range (minimum and
        maximum coordinates: min and max tuples/lists/arrays)
        and number of cells in each space direction (division tuple/list/array).
        The dirnames tuple/list holds the names of the coordinates in
        the various spatial directions.

        >>> g = UniformBoxGrid(min=0, max=1, division=10)
        >>> g = UniformBoxGrid(min=(0,-1), max=(1,1), division=(10,4))
        >>> g = UniformBoxGrid(min=(0,0,-1), max=(2,1,1), division=(2,3,5))
        """
        # Allow int/float specifications in one-dimensional grids
        # (just turn to lists for later multi-dimensional processing)
        if isinstance(min, (int,float)):
            min = [min]
        if isinstance(max, (int,float)):
            max = [max]
        if isinstance(division, (int,float)):
            division = [division]
        if isinstance(dirnames, str):
            dirnames = [dirnames]

        self.nsd = len(min)
        # strip dirnames down to right space dim (in case the default
        # with three components were unchanged by the user):
        dirnames = dirnames[:self.nsd]

        # check consistent lengths:
        for a in max, division:
            if len(a) != self.nsd:
                raise ValueError(
                    'Incompatible lengths of arguments to constructor'\
                    ' (%d != %d)' % (len(a), self.nsd))

        self.min_coor = array(min, float)
        self.max_coor = array(max, float)
        self.dirnames = dirnames
        self.division = division
        self.coor = [None]*self.nsd
        self.shape = [0]*self.nsd
        self.delta = zeros(self.nsd)

        for i in range(self.nsd):
            self.delta[i] = \
                 (self.max_coor[i] -  self.min_coor[i])/float(self.division[i])
            self.shape[i] = self.division[i] + 1  # no of grid points
            self.coor[i] = \
                 linspace(self.min_coor[i], self.max_coor[i], self.shape[i])
        self._more_init()
Esempio n. 5
0
def _test(g, points=None):
    print 'g=%s' % str(g)
    # dump all the contents of a grid object:
    import scitools.misc
    scitools.misc.dump(g, hide_nonpublic=False)
    from numpy import zeros

    def fv(*args):
        # vectorized evaluation function
        return zeros(g.shape) + 2

    def fs(*args):
        # scalar version
        return 2

    fv_arr = g.vectorized_eval(fv)
    fs_arr = zeros(g.shape)

    coor = [0.0] * g.nsd
    itparts = [
        'all', 'interior', 'all_boundary', 'interior_boundary', 'corners'
    ]
    if g.nsd == 3:
        itparts += ['all_edges', 'interior_edges']
    for domain_part in itparts:
        print '\niterator over "%s"' % domain_part
        for i in g.iter(domain_part, vectorized_version=False):
            if isinstance(i, int): i = [i]  # wrap index as list (if 1D)
            for k in range(g.nsd):
                coor[k] = g.coor[k][i[k]]
            print i, coor
            if domain_part == 'all':  # fs_arr shape corresponds to all points
                fs_arr[i] = fs(*coor)
        print 'vectorized iterator over "%s":' % domain_part
        for slices in g.iter(domain_part, vectorized_version=True):
            if domain_part == 'all':
                fs_arr[slices] = fv(*g.coor)
            # else: more complicated
            print slices
    # boundary slices...

    if points is not None:
        print '\n\nInterpolation in', g, '\n', g.coor
        for p in points:
            index, distance = g.locate_cell(p)
            print 'point %s is in cell %s, distance=%s' % (p, index, distance)
Esempio n. 6
0
def _test(g, points=None):
    print 'g=%s' % str(g)
    # dump all the contents of a grid object:
    import scitools.misc;  scitools.misc.dump(g, hide_nonpublic=False)
    from numpy import zeros
    def fv(*args):
        # vectorized evaluation function
        return zeros(g.shape)+2
    def fs(*args):
        # scalar version
        return 2
    fv_arr = g.vectorized_eval(fv)
    fs_arr = zeros(g.shape)

    coor = [0.0]*g.nsd
    itparts = ['all', 'interior', 'all_boundary', 'interior_boundary',
               'corners']
    if g.nsd == 3:
        itparts += ['all_edges', 'interior_edges']
    for domain_part in itparts:
        print '\niterator over "%s"' % domain_part
        for i in g.iter(domain_part, vectorized_version=False):
            if isinstance(i, int):  i = [i]  # wrap index as list (if 1D)
            for k in range(g.nsd):
                coor[k] = g.coor[k][i[k]]
            print i, coor
            if domain_part == 'all':  # fs_arr shape corresponds to all points
                fs_arr[i] = fs(*coor)
        print 'vectorized iterator over "%s":' % domain_part
        for slices in g.iter(domain_part, vectorized_version=True):
            if domain_part == 'all':
                fs_arr[slices] = fv(*g.coor)
            # else: more complicated
            print slices
    # boundary slices...

    if points is not None:
        print '\n\nInterpolation in', g, '\n', g.coor
        for p in points:
            index, distance = g.locate_cell(p)
            print 'point %s is in cell %s, distance=%s' % (p, index, distance)
Esempio n. 7
0
def flow(*args):
    # xx,yy,zz,vv = flow()
    # xx,yy,zz,vv = flow(n)
    # xx,yy,zz,vv = flow(xx,yy,zz)
    if len(args) == 0:
        xx, yy, zz = ndgrid(linspace(0.1, 10, 50),
                            linspace(-3, 3, 25),
                            linspace(-3, 3, 25),
                            sparse=False)
    elif len(args) == 1:
        n = int(args[0])
        xx, yy, zz = ndgrid(linspace(0.1, 10, 2 * n),
                            linspace(-3, 3, n),
                            linspace(-3, 3, n),
                            sparse=False)
    elif len(args) == 3:
        xx, yy, zz = args
    else:
        raise SyntaxError("Invalid number of arguments.")

    # convert to spherical coordinates:
    theta = arctan2(zz, yy)
    phi = arctan2(xx, sqrt(yy**2 + zz**2))
    r = sqrt(xx**2 + yy**2 + zz**2)

    rv = 2 / r * (3 / (2 - cos(phi))**2 - 1)
    phiv = -2 * sin(phi) / (2 - cos(phi)) / r
    thetav = zeros(shape(r))

    # convert back to cartesian coordinates:
    xv = rv * cos(phiv) * cos(thetav)
    yv = rv * cos(phiv) * sin(thetav)
    zv = rv * sin(phiv)

    vv = log(sqrt(xv**2 + yv**2 + zv**2))

    return xx, yy, zz, vv
Esempio n. 8
0
def flow(*args):
    # xx,yy,zz,vv = flow()
    # xx,yy,zz,vv = flow(n)
    # xx,yy,zz,vv = flow(xx,yy,zz)
    if len(args) == 0:
        xx, yy, zz = ndgrid(linspace(0.1, 10, 50),
                            linspace(-3, 3, 25),
                            linspace(-3, 3, 25),
                            sparse=False)
    elif len(args) == 1:
        n = int(args[0])
        xx, yy, zz = ndgrid(linspace(0.1, 10, 2*n),
                            linspace(-3, 3, n),
                            linspace(-3, 3, n),
                            sparse=False)
    elif len(args) == 3:
        xx, yy, zz = args
    else:
        raise SyntaxError("Invalid number of arguments.")
    
    # convert to spherical coordinates:
    theta = arctan2(zz, yy)
    phi = arctan2(xx, sqrt(yy**2 + zz**2))
    r = sqrt(xx**2 + yy**2 + zz**2)

    rv = 2/r*(3/(2-cos(phi))**2 - 1)
    phiv = -2*sin(phi)/(2-cos(phi))/r
    thetav = zeros(shape(r))

    # convert back to cartesian coordinates:
    xv = rv*cos(phiv)*cos(thetav)
    yv = rv*cos(phiv)*sin(thetav)
    zv = rv*sin(phiv)

    vv = log(sqrt(xv**2 + yv**2 + zv**2))

    return xx, yy, zz, vv
Esempio n. 9
0
 def fv(*args):
     # vectorized evaluation function
     return zeros(g.shape) + 2
Esempio n. 10
0
    def locate_cell(self, point):
        """
        Given a point (x, (x,y), (x,y,z)), locate the cell in which
        the point is located, and return
        1) the (i,j,k) vertex index
        of the "lower-left" grid point in this cell,
        2) the distances (dx, (dx,dy), or (dx,dy,dz)) from this point to
        the given point,
        3) a boolean list if point matches the
        coordinates of any grid lines. If a point matches
        the last grid point in a direction, the cell index is
        set to the max index such that the (i,j,k) index can be used
        directly for look up in an array of values. The corresponding
        element in the distance array is then set 0.
        4) the indices of the nearest grid point.

        The method only works for uniform grid spacing.
        Used for interpolation.

        >>> g1 = UniformBoxGrid(min=0, max=1, division=4)
        >>> cell_index, distance, match, nearest = g1.locate_cell(0.7)
        >>> print cell_index
        [2]
        >>> print distance
        [ 0.2]
        >>> print match
        [False]
        >>> print nearest
        [3]
        >>>
        >>> g1.locate_cell(0.5)
        ([2], array([ 0.]), [True], [2])
        >>>
        >>> g2 = UniformBoxGrid.init_fromstring('[-1,1]x[-1,2] [0:3]x[0:4]')
        >>> print g2.coor
        [array([-1.        , -0.33333333,  0.33333333,  1.        ]), array([-1.  , -0.25,  0.5 ,  1.25,  2.  ])]
        >>> g2.locate_cell((0.2,0.2))
        ([1, 1], array([ 0.53333333,  0.45      ]), [False, False], [2, 2])
        >>> g2.locate_cell((1,2))
        ([3, 4], array([ 0.,  0.]), [True, True], [3, 4])
        >>>
        >>>
        >>>
        """
        if isinstance(point, (int, float)):
            point = [point]
        nsd = len(point)
        if nsd != self.nsd:
            raise ValueError('point=%s has wrong dimension (this is a %dD grid!)' % \
                             (point, self.nsd))
        #index = zeros(nsd, int)
        index = [0] * nsd
        distance = zeros(nsd)
        grid_point = [False] * nsd
        nearest_point = [0] * nsd
        for i, coor in enumerate(point):
            # is point inside the domain?
            if coor < self.min_coor[i] or coor > self.max_coor[i]:
                raise ValueError(
                    'locate_cell: point=%s is outside the domain [%s,%s]' % \
                    point, self.min_coor[i], self.max_coor[i])
            index[i] = int((coor - self.min_coor[i]) //
                           self.delta[i])  # (need integer division)
            distance[i] = coor - (self.min_coor[i] + index[i] * self.delta[i])
            if distance[i] > self.delta[i] / 2:
                nearest_point[i] = index[i] + 1
            else:
                nearest_point[i] = index[i]
            if abs(distance[i]) < self.tolerance:
                grid_point[i] = True
                nearest_point[i] = index[i]
            if (abs(distance[i] - self.delta[i])) < self.tolerance:
                # last cell, update index such that it coincides with the point
                grid_point[i] = True
                index[i] += 1
                nearest_point[i] = index[i]
                distance[i] = 0.0

        return index, distance, grid_point, nearest_point
#!/usr/bin/env python
import sys, math
import oscillator

# default values of input parameters:
m = 1.0; b = 0.7; c = 5.0; func = 'y'; A = 5.0; w = 2*math.pi
y0 = 0.2; tstop = 30.0; dt = 0.05

from scitools.numpyutils import seq, zeros
maxsteps = 10000
#maxsteps = 10
n = 2
y = zeros((n,maxsteps))
step = 0; time = 0.0

import Gnuplot
g1 = Gnuplot.Gnuplot(persist=1)  # (y(t),dy/dt) plot
g2 = Gnuplot.Gnuplot(persist=1)  # y(t) plot

def setprm():
    oscillator.scan2(m, b, c, A, w, y0, tstop, dt, func)

def rewind(nsteps=0):
    global step, time
    if nsteps == 0:         # start all over again?
        step = 0
        time  = 0.0
    else:                   # rewind nsteps
        step -= nsteps
        time -= nsteps*dt
Esempio n. 12
0
 def fv(*args):
     # vectorized evaluation function
     return zeros(g.shape)+2
Esempio n. 13
0
    def locate_cell(self, point):
        """
        Given a point (x, (x,y), (x,y,z)), locate the cell in which
        the point is located, and return
        1) the (i,j,k) vertex index
        of the "lower-left" grid point in this cell,
        2) the distances (dx, (dx,dy), or (dx,dy,dz)) from this point to
        the given point,
        3) a boolean list if point matches the
        coordinates of any grid lines. If a point matches
        the last grid point in a direction, the cell index is
        set to the max index such that the (i,j,k) index can be used
        directly for look up in an array of values. The corresponding
        element in the distance array is then set 0.
        4) the indices of the nearest grid point.

        The method only works for uniform grid spacing.
        Used for interpolation.

        >>> g1 = UniformBoxGrid(min=0, max=1, division=4)
        >>> cell_index, distance, match, nearest = g1.locate_cell(0.7)
        >>> print cell_index
        [2]
        >>> print distance
        [ 0.2]
        >>> print match
        [False]
        >>> print nearest
        [3]
        >>>
        >>> g1.locate_cell(0.5)
        ([2], array([ 0.]), [True], [2])
        >>>
        >>> g2 = UniformBoxGrid.init_fromstring('[-1,1]x[-1,2] [0:3]x[0:4]')
        >>> print g2.coor
        [array([-1.        , -0.33333333,  0.33333333,  1.        ]), array([-1.  , -0.25,  0.5 ,  1.25,  2.  ])]
        >>> g2.locate_cell((0.2,0.2))
        ([1, 1], array([ 0.53333333,  0.45      ]), [False, False], [2, 2])
        >>> g2.locate_cell((1,2))
        ([3, 4], array([ 0.,  0.]), [True, True], [3, 4])
        >>>
        >>>
        >>>
        """
        if isinstance(point, (int,float)):
            point = [point]
        nsd = len(point)
        if nsd != self.nsd:
            raise ValueError('point=%s has wrong dimension (this is a %dD grid!)' % \
                             (point, self.nsd))
        #index = zeros(nsd, int)
        index = [0]*nsd
        distance = zeros(nsd)
        grid_point = [False]*nsd
        nearest_point = [0]*nsd
        for i, coor in enumerate(point):
            # is point inside the domain?
            if coor < self.min_coor[i] or coor > self.max_coor[i]:
                raise ValueError(
                    'locate_cell: point=%s is outside the domain [%s,%s]' % \
                    point, self.min_coor[i], self.max_coor[i])
            index[i] = int((coor - self.min_coor[i])//self.delta[i])  # (need integer division)
            distance[i] = coor - (self.min_coor[i] + index[i]*self.delta[i])
            if distance[i] > self.delta[i]/2:
                nearest_point[i] = index[i] + 1
            else:
                nearest_point[i] = index[i]
            if abs(distance[i]) < self.tolerance:
                grid_point[i] = True
                nearest_point[i] = index[i]
            if (abs(distance[i] - self.delta[i])) < self.tolerance:
                # last cell, update index such that it coincides with the point
                grid_point[i] = True
                index[i] += 1
                nearest_point[i] = index[i]
                distance[i] = 0.0

        return index, distance, grid_point, nearest_point