How to use the pysal.lib.weights.weights.W function in pysal

To help you get started, we’ve selected a few pysal examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github pysal / pysal / pysal / explore / esda / smoothing.py View on Github external
return new
        if isinstance(e, str):
            e = [e]
        if isinstance(b, str):
            b = [b]
        if w is None:
            found = False
            for k in df._metadata:
                w = df.__dict__.get(w, None)
                if isinstance(w, W):
                    found = True
            if not found:
                raise Exception('Weights not provided and no weights attached to frame!'
                                    ' Please provide a weight or attach a weight to the'
                                    ' dataframe')
        if isinstance(w, W):
            w = [w] * len(e)
        if len(b) == 1 and len(e) > 1:
            b = b * len(e)
        try:
            assert len(e) == len(b)
        except AssertionError:
            raise ValueError('There is no one-to-one mapping between event'
                             ' variable and population at risk variable!')
        for ei, bi, wi in zip(e, b, w):
            ename = ei
            bname = bi
            ei = df[ename]
            bi = df[bname]
            outcol = '_'.join(('-'.join((ename, bname)), cls.__name__.lower()))
            df[outcol] = cls(ei, bi, w=wi, **kwargs).r
github pysal / pysal / pysal / lib / weights / util.py View on Github external
if id_type == 'string':
        ids = ['id' + str(i) for i in ids]
    elif id_type == 'float':
        ids = [i * 1. for i in ids]
    if id_type == 'string' or id_type == 'float':
        id_dict = dict(list(zip(list(range(n)), ids)))
        alt_w = {}
        alt_weights = {}
        for i in w:
            values = [id_dict[j] for j in w[i]]
            key = id_dict[i]
            alt_w[key] = values
            alt_weights[key] = weights[i]
        w = alt_w
        weights = alt_weights
    return W(w, weights, ids=ids, id_order=ids[:], **kwargs)
github pysal / pysal / pysal / lib / io / iohandlers / arcgis_dbf.py View on Github external
weights = {}
        neighbors = {}
        for row in self.file:
            i, j, w = tuple(row)[startPos:]
            i = id_type(i)
            j = id_type(j)
            w = float(w)
            if i not in weights:
                weights[i] = []
                neighbors[i] = []
            weights[i].append(w)
            neighbors[i].append(j)
            self.pos = self.file.pos

        return W(neighbors, weights)
github pysal / pysal / pysal / lib / io / iohandlers / gwt.py View on Github external
warn("ID_VAR:'%s' was not in the DBF header, proceeding with unordered string ids." % (id_var), RuntimeWarning)
            else:
                warn("DBF relating to GWT was not found, proceeding with unordered string ids.", RuntimeWarning)
        except:
            warn("Exception occurred will reading DBF, proceeding with unordered string ids.", RuntimeWarning)
        self.flag = flag
        self.n = n
        self.shp = shp
        self.id_var = id_var
        if id_order is None:
            weights, neighbors, id_order = self._readlines(id_type, True)
        else:
            weights, neighbors = self._readlines(id_type)

        self.pos += 1
        w = W(neighbors, weights, id_order)
        #w.transform = 'b'
        #set meta data
        w._shpName = self.shpName
        w._varName = self.varName
        #warn("Weights have been converted to binary. To retrieve original values use w.transform='o'", RuntimeWarning)
        return w
github pysal / pysal / pysal / lib / weights / Distance.py View on Github external
# If not, we can use the same kdtree we have
            data = self.kdtree
            ids = self.id_order
        elif (new_data is None) and (new_ids is not None):
            Warn('Remapping ids must be done using w.remap_ids')
        if k is None:
            k = self.k
        if p is None:
            p = self.p
        if inplace:
            self._reset()
            self.__init__(data, ids=ids, k=k, p=p)
        else:
            return KNN(data, ids=ids, k=k, p=p)

class Kernel(W):
    """
    Spatial weights based on kernel functions.

    Parameters
    ----------

    data        : array
                  (n,k) or KDTree where KDtree.data is array (n,k)
                  n observations on k characteristics used to measure
                  distances between the n objects
    bandwidth   : float
                  or array-like (optional)
                  the bandwidth :math:`h_i` for the kernel.
    fixed       : binary
                  If true then :math:`h_i=h \\forall i`. If false then
                  bandwidth is adaptive across observations.
github pysal / pysal / pysal / lib / weights / Contiguity.py View on Github external
from ..io.fileio import FileIO
from .weights import W, WSP
from ._contW_lists import ContiguityWeightsLists
from .util import get_ids
WT_TYPE = {'rook': 2, 'queen': 1}  # for _contW_Binning

__author__ = "Sergio J. Rey  , Levi John Wolf "

__all__ = ['Rook', 'Queen', 'Voronoi']

class Rook(W):
    """
    Construct a weights object from a collection of pysal polygons that share at least one edge.

    Parameters
    ----------
    polygons    : list
                a collection of PySAL shapes to build weights from
    ids         : list
                a list of names to use to build the weights
    **kw        : keyword arguments
                optional arguments for :class:`pysal.weights.W`

    See Also
    ---------
    :class:`pysal.lib.weights.weights.W`
    """
github pysal / pysal / pysal / lib / weights / contiguity.py View on Github external
def __init__(self, polygons, **kw):
        criterion = 'queen'
        ids = kw.pop('ids', None)
        neighbors, ids = _build(polygons, ids=ids, 
                                criterion=criterion)
        W.__init__(self, neighbors, ids=ids, **kw)
github pysal / pysal / pysal / lib / weights / weights.py View on Github external
id_order = self.id_order
        if id_order:
            # replace indices with user IDs
            indices = [id_order[i] for i in indices]
        else:
            id_order = list(range(self.n))
        neighbors, weights = {}, {}
        start = indptr[0]
        for i in range(self.n):
            oid = id_order[i]
            end = indptr[i + 1]
            neighbors[oid] = indices[start:end]
            weights[oid] = data[start:end]
            start = end
        ids = copy.copy(self.id_order)
        w = W(neighbors, weights, ids,
                    silence_warnings=silence_warnings)
        w._sparse = copy.deepcopy(self.sparse)
        w._cache['sparse'] = w._sparse
        return w
github pysal / pysal / pysal / lib / io / iohandlers / gwt.py View on Github external
Read in the newly created gwt file

        >>> wnew =  pysal.lib.io.open(fname,'r').read()

        Compare values from old to new

        >>> wnew.pct_nonzero == w.pct_nonzero
        True

        Clean up temporary file created for this example

        >>> os.remove(fname)
        """
        self._complain_ifclosed(self.closed)
        if issubclass(type(obj), W):
            #transform = obj.transform
            #obj.transform = 'o'
            if hasattr(obj, '_shpName'):
                self.shpName = obj._shpName
            if hasattr(obj, '_varName'):
                self.varName = obj._varName
            header = '%s %i %s %s\n' % ('0', obj.n, self.shpName, self.varName)
            self.file.write(header)
            self._writelines(obj)
            #obj.transform = transform

        else:
            raise TypeError("Expected a pysal weights object, got: %s" % (
                type(obj)))