示例#1
0
def _find_bcs():
    classes = dict()
    bcs = dict()
    ucs = dict()
    submods = dict()
    for obname, ob in diter(pysal.spreg.__dict__):
        if isinstance(ob, ty.ModuleType):
            if ob.__package__.startswith("pysal"):
                submods.update({obname: ob})
        elif isinstance(ob, clstypes):
            classes.update({obname: ob})
            if ob.__name__.startswith('Base'):
                bcs.update({obname: ob})
    for modname, mod in diter(submods):
        basecands = dict()
        for clname in dir(mod):
            cl = mod.__dict__[clname]
            if isinstance(cl, clstypes):
                try:
                    if cl.__name__.startswith('Base'):
                        if cl not in bcs:
                            bcs.update({cl.__name__: cl})
                        else:
                            classes.update({cl.__name__: cl})
                except:
                    pass
    ucs.update({
        k: v
        for k, v in diter(classes)
        if (any([issubclass(v, bc) for bc in list(bcs.values())]) and
            (k not in bcs)) or k.endswith('Regimes')
    })
    return bcs, ucs
示例#2
0
def _find_bcs():
    classes = dict()
    bcs = dict()
    ucs = dict()
    submods = dict()
    for obname, ob in diter(pysal.spreg.__dict__):
        if isinstance(ob, ty.ModuleType):
            if ob.__package__.startswith("pysal"):
                submods.update({obname:ob})
        elif isinstance(ob, clstypes):
            classes.update({obname:ob})
            if ob.__name__.startswith('Base'):
                bcs.update({obname:ob})
    for modname, mod in diter(submods):
        basecands = dict()
        for clname in dir(mod):
            cl = mod.__dict__[clname]
            if isinstance(cl, clstypes):
                try:
                    if cl.__name__.startswith('Base'):
                        if cl not in bcs:
                            bcs.update({cl.__name__:cl})
                        else:
                            classes.update({cl.__name__:cl})
                except:
                    pass
    ucs.update({k:v for k,v in diter(classes) if (
                any([issubclass(v, bc) for bc in bcs.values()])
                and (k not in bcs))
                or k.endswith('Regimes')})
    return bcs, ucs
示例#3
0
def lag_categorical(w, y, ties='tryself'):
    """
    Spatial lag operator for categorical variables.

    Constructs the most common categories of neighboring observations, weighted
    by their weight strength.

    Parameters
    ----------

    w                   : W
                          PySAL spatial weightsobject
    y                   : iterable
                          iterable collection of categories (either int or
                          string) with dimensionality conforming to w (see examples)
    ties                : str
                          string describing the method to use when resolving
                          ties. By default, the option is "tryself",
                          and the category of the focal observation
                          is included with its neighbors to try
                          and break a tie. If this does not resolve the tie,
                          a winner is chosen randomly. To just use random choice to
                          break ties, pass "random" instead.
                          Also supported are selecting the ``lowest'' class in the 
                          sorted list of ties or the ``highest'' class. 
    Returns
    -------
    an (n x k) column vector containing the most common neighboring observation

    Notes
    -----
    This works on any array where the number of unique elements along the column
    axis is less than the number of elements in the array, for any dtype.
    That means the routine should work on any dtype that np.unique() can
    compare.

    Examples
    --------

    Set up a 9x9 weights matrix describing a 3x3 regular lattice. Lag one list of
    categorical variables with no ties.

    >>> import pysal
    >>> import numpy as np
    >>> np.random.seed(12345)
    >>> w = pysal.lat2W(3, 3)
    >>> y = ['a','b','a','b','c','b','c','b','c']
    >>> y_l = pysal.weights.spatial_lag.lag_categorical(w, y)
    >>> np.array_equal(y_l, np.array(['b', 'a', 'b', 'c', 'b', 'c', 'b', 'c', 'b']))
    True

    Explicitly reshape y into a (9x1) array and calculate lag again

    >>> yvect = np.array(y).reshape(9,1)
    >>> yvect_l = pysal.weights.spatial_lag.lag_categorical(w,yvect)
    >>> check = np.array( [ [i] for i in  ['b', 'a', 'b', 'c', 'b', 'c', 'b', 'c', 'b']] )
    >>> np.array_equal(yvect_l, check)
    True

    compute the lag of a 9x2 matrix of categories

    >>> y2 = ['a', 'c', 'c', 'd', 'b', 'a', 'd', 'd', 'c']
    >>> ym = np.vstack((y,y2)).T
    >>> ym_lag = pysal.weights.spatial_lag.lag_categorical(w,ym)
    >>> check = np.array([['b', 'b'], ['a', 'c'], ['b', 'c'], ['c', 'd'], ['b', 'd'], ['c', 'c'], ['b', 'd'], ['c', 'd'], ['b', 'b']])
    >>> np.array_equal(check, ym_lag)
    True

    """
    if isinstance(y, list):
        y = np.array(y)
    orig_shape = y.shape
    if len(orig_shape) > 1:
        if orig_shape[1] > 1:
            return np.vstack([lag_categorical(w, col) for col in y.T]).T
    y = y.flatten()
    output = np.zeros_like(y)
    keys = np.unique(y)
    inty = np.zeros(y.shape, dtype=np.int)
    for i, key in enumerate(keys):
        inty[y == key] = i
    for idx, neighbors in w:
        vals = np.zeros(keys.shape)
        for neighb, weight in diter(neighbors):
            vals[inty[w.id2i[neighb]]] += weight
        outidx = _resolve_ties(idx, inty, vals, neighbors, ties, w)
        output[w.id2i[int(idx)]] = keys[int(outidx)]
    return output.reshape(orig_shape)
示例#4
0
def lag_categorical(w, y, ties='tryself'):
    """
    Spatial lag operator for categorical variables.

    Constructs the most common categories of neighboring observations, weighted
    by their weight strength.

    Parameters
    ----------

    w                   : W
                          PySAL spatial weightsobject
    y                   : iterable
                          iterable collection of categories (either int or
                          string) with dimensionality conforming to w (see examples)
    ties                : str
                          string describing the method to use when resolving
                          ties. By default, the option is "tryself",
                          and the category of the focal observation
                          is included with its neighbors to try
                          and break a tie. If this does not resolve the tie,
                          a winner is chosen randomly. To just use random choice to
                          break ties, pass "random" instead.
                          Also supported are selecting the ``lowest'' class in the 
                          sorted list of ties or the ``highest'' class. 
    Returns
    -------
    an (n x k) column vector containing the most common neighboring observation

    Notes
    -----
    This works on any array where the number of unique elements along the column
    axis is less than the number of elements in the array, for any dtype.
    That means the routine should work on any dtype that np.unique() can
    compare.

    Examples
    --------

    Set up a 9x9 weights matrix describing a 3x3 regular lattice. Lag one list of
    categorical variables with no ties.

    >>> import pysal
    >>> import numpy as np
    >>> np.random.seed(12345)
    >>> w = pysal.lat2W(3, 3)
    >>> y = ['a','b','a','b','c','b','c','b','c']
    >>> y_l = pysal.weights.spatial_lag.lag_categorical(w, y)
    >>> np.array_equal(y_l, np.array(['b', 'a', 'b', 'c', 'b', 'c', 'b', 'c', 'b']))
    True

    Explicitly reshape y into a (9x1) array and calculate lag again

    >>> yvect = np.array(y).reshape(9,1)
    >>> yvect_l = pysal.weights.spatial_lag.lag_categorical(w,yvect)
    >>> check = np.array( [ [i] for i in  ['b', 'a', 'b', 'c', 'b', 'c', 'b', 'c', 'b']] )
    >>> np.array_equal(yvect_l, check)
    True

    compute the lag of a 9x2 matrix of categories

    >>> y2 = ['a', 'c', 'c', 'd', 'b', 'a', 'd', 'd', 'c']
    >>> ym = np.vstack((y,y2)).T
    >>> ym_lag = pysal.weights.spatial_lag.lag_categorical(w,ym)
    >>> check = np.array([['b', 'b'], ['a', 'c'], ['b', 'c'], ['c', 'd'], ['b', 'd'], ['c', 'c'], ['b', 'd'], ['c', 'd'], ['b', 'b']])
    >>> np.array_equal(check, ym_lag)
    True

    """
    if isinstance(y, list):
        y = np.array(y)
    orig_shape = y.shape
    if len(orig_shape) > 1:
        if orig_shape[1] > 1:
            return np.vstack([lag_categorical(w,col) for col in y.T]).T
    y = y.flatten()
    output = np.zeros_like(y)
    keys = np.unique(y)
    inty = np.zeros(y.shape, dtype=np.int)
    for i,key in enumerate(keys):
       inty[y == key] = i
    for idx,neighbors in w:
        vals = np.zeros(keys.shape)
        for neighb, weight in diter(neighbors):
            vals[inty[w.id2i[neighb]]] += weight
        outidx = _resolve_ties(idx,inty,vals,neighbors,ties, w)
        output[w.id2i[int(idx)]] = keys[int(outidx)]
    return output.reshape(orig_shape)