Esempio n. 1
0
def get_lisa(gdf, indicator, w):
    '''
    This function takes a year and a variable
    and returns the all the quadrants for local moran analysis
    ...
    Args:

    '''
    gdf = gdf.copy()
    quadrant_labels = {1: 'HH',
                       2: 'HL',
                       3: 'LL',
                       4: 'LH'
                       }

    moran = Moran(gdf[indicator].values, w)
    moran_loc = Moran_Local(gdf[indicator].values, w, transformation="r")

    significant = pd.Series(moran_loc.p_sim < 0.05)
    quadrant = pd.Series(moran_loc.q)
    quadrant = quadrant.replace(quadrant_labels)
    quadrant[~significant] = 'Non-significant'

    gdf['lisa_cluster'] = quadrant
    return gdf
Esempio n. 2
0
 def setup(self):
     from pysal.explore.esda.moran import Moran
     self.w = pysal.lib.io.open(pysal.lib.examples.get_path("stl.gal")).read()
     f = pysal.lib.io.open(pysal.lib.examples.get_path("stl_hom.txt"))
     self.y = np.array(f.by_col['HR8893'])
     self.rho = Moran(self.y, self.w).I
     self.n = len(self.y)
     self.k = int(self.n/2)
Esempio n. 3
0
def test_plot_moran_simulation():
    # Load data and apply statistical analysis
    link_to_data = examples.get_path('Guerry.shp')
    gdf = gpd.read_file(link_to_data)
    y = gdf['Donatns'].values
    w = Queen.from_dataframe(gdf)
    w.transform = 'r'
    # Calc Global Moran
    w = Queen.from_dataframe(gdf)
    moran = Moran(y, w)
    # plot
    fig, _ = plot_moran_simulation(moran)
    plt.close(fig)
    # customize
    fig, _ = plot_moran_simulation(moran, fitline_kwds=dict(color='#4393c3'))
    plt.close(fig)
Esempio n. 4
0
def test_moran_scatterplot():
    link_to_data = examples.get_path('Guerry.shp')
    gdf = gpd.read_file(link_to_data)
    x = gdf['Suicids'].values
    y = gdf['Donatns'].values
    w = Queen.from_dataframe(gdf)
    w.transform = 'r'
    # Calculate `esda.moran` Objects
    moran = Moran(y, w)
    moran_bv = Moran_BV(y, x, w)
    moran_loc = Moran_Local(y, w)
    moran_loc_bv = Moran_Local_BV(y, x, w)
    # try with p value so points are colored or warnings apply
    fig, _ = moran_scatterplot(moran, p=0.05, aspect_equal=False)
    plt.close(fig)
    fig, _ = moran_scatterplot(moran_loc, p=0.05)
    plt.close(fig)
    fig, _ = moran_scatterplot(moran_bv, p=0.05)
    plt.close(fig)
    fig, _ = moran_scatterplot(moran_loc_bv, p=0.05)
    plt.close(fig)
Esempio n. 5
0
def get_lisa_legacy(path, indicator, w, grid_id):
    '''
    This function takes a year and a variable
    and returns the all the quadrants for local moran analysis
    ...
    Args:

    '''
    carto = gpd.read_file(path)

    moran = Moran(carto[indicator].values, w)
    moran_loc = Moran_Local(carto[indicator].values, w, transformation="r",
                            permutations=99)

    carto['significant'] = moran_loc.p_sim < 0.05
    carto['quadrant'] = moran_loc.q

    return {'gdf': carto,
            'moran': moran,
            'value': moran.I,
            'significance': moran.p_sim,
            'local': moran_loc}
Esempio n. 6
0
def moran_facet(moran_matrix,
                figsize=(16, 12),
                scatter_bv_kwds=None,
                fitline_bv_kwds=None,
                scatter_glob_kwds=dict(color='#737373'),
                fitline_glob_kwds=None):
    """
    Moran Facet visualization.
    Includes BV Morans and Global Morans on the diagonal.
    
    Parameters
    ----------
    moran_matrix : esda.moran.Moran_BV_matrix instance
        Dictionary of Moran_BV objects
    figsize : tuple, optional
        W, h of figure. Default =(16,12)
    scatter_bv_kwds : keyword arguments, optional
        Keywords used for creating and designing the scatter points of
        off-diagonal Moran_BV plots.
        Default =None.
    fitline_bv_kwds : keyword arguments, optional
        Keywords used for creating and designing the moran fitline of
        off-diagonal Moran_BV plots.
        Default =None.
    scatter_glob_kwds : keyword arguments, optional
        Keywords used for creating and designing the scatter points of
        diagonal Moran plots.
        Default =None.
    fitline_glob_kwds : keyword arguments, optional
        Keywords used for creating and designing the moran fitline of
        diagonal Moran plots.
        Default =None.

    Returns
    -------
    fig : Matplotlib Figure instance
        Bivariate Moran Local scatterplot figure
    axarr : matplotlib Axes instance
        Axes in which the figure is plotted

    Examples
    --------
    Imports
    
    >>> import matplotlib.pyplot as plt
    >>> import pysal.lib as lp
    >>> import numpy as np
    >>> import geopandas as gpd
    >>> from pysal.explore.esda.moran import Moran_BV_matrix
    >>> from pysal.viz.splot.esda import moran_facet
    
    Load data and calculate Moran Local statistics
    
    >>> f = gpd.read_file(lp.examples.get_path("sids2.dbf"))
    >>> varnames = ['SIDR74',  'SIDR79',  'NWR74',  'NWR79']
    >>> vars = [np.array(f[var]) for var in varnames]
    >>> w = lp.io.open(lp.examples.get_path("sids2.gal")).read()
    >>> moran_matrix = Moran_BV_matrix(vars,  w,  varnames = varnames)
    
    Plot
    
    >>> fig, axarr = moran_facet(moran_matrix)
    >>> plt.show()
    
    Customize plot
    
    >>> fig, axarr = moran_facet(moran_matrix,
    ...                          fitline_bv_kwds=dict(color='#4393c3'))
    >>> plt.show()
    
    """
    nrows = int(np.sqrt(len(moran_matrix))) + 1
    ncols = nrows

    fig, axarr = plt.subplots(nrows,
                              ncols,
                              figsize=figsize,
                              sharey=True,
                              sharex=True)
    fig.suptitle('Moran Facet')

    for row in range(nrows):
        for col in range(ncols):
            if row == col:
                global_m = Moran(moran_matrix[row, (row + 1) % 4].zy,
                                 moran_matrix[row, (row + 1) % 4].w)
                _moran_global_scatterplot(global_m,
                                          ax=axarr[row, col],
                                          scatter_kwds=scatter_glob_kwds,
                                          fitline_kwds=fitline_glob_kwds)
                axarr[row, col].set_facecolor('#d9d9d9')
            else:
                _moran_bv_scatterplot(moran_matrix[row, col],
                                      ax=axarr[row, col],
                                      scatter_kwds=scatter_bv_kwds,
                                      fitline_kwds=fitline_bv_kwds)

            axarr[row, col].spines['bottom'].set_visible(False)
            axarr[row, col].spines['left'].set_visible(False)
            if row == nrows - 1:
                axarr[row, col].set_xlabel(
                    str(moran_matrix[(col + 1) % 4,
                                     col].varnames['x']).format(col))
                axarr[row, col].spines['bottom'].set_visible(True)
            else:
                axarr[row, col].set_xlabel('')

            if col == 0:
                axarr[row, col].set_ylabel(('Spatial Lag of ' + str(
                    moran_matrix[row,
                                 (row + 1) % 4].varnames['y'])).format(row))
                axarr[row, col].spines['left'].set_visible(True)
            else:
                axarr[row, col].set_ylabel('')

            axarr[row, col].set_title('')
    plt.tight_layout()
    return fig, axarr
def morans_plot_fine_and_precinct():
    w = Queen.from_dataframe(imd2)
    mi = Moran( nycplot['fine'], w)
    fig ,ax = moran_scatterplot(mi)
from pysal.lib import examples
import geopandas as gpd
from pysal.explore.esda.moran import (Moran, Moran_BV, Moran_Local,
                                      Moran_Local_BV)
from pysal.viz.splot.esda import moran_scatterplot

# Load data and calculate weights

link_to_data = examples.get_path('Guerry.shp')
gdf = gpd.read_file(link_to_data)
x = gdf['Suicids'].values
y = gdf['Donatns'].values
w = Queen.from_dataframe(gdf)
w.transform = 'r'

# Calculate esda.moran Objects

moran = Moran(y, w)
moran_bv = Moran_BV(y, x, w)
moran_loc = Moran_Local(y, w)
moran_loc_bv = Moran_Local_BV(y, x, w)

# Plot

fig, axs = plt.subplots(2, 2, figsize=(10, 10), subplot_kw={'aspect': 'equal'})
moran_scatterplot(moran, p=0.05, ax=axs[0, 0])
moran_scatterplot(moran_loc, p=0.05, ax=axs[1, 0])
moran_scatterplot(moran_bv, p=0.05, ax=axs[0, 1])
moran_scatterplot(moran_loc_bv, p=0.05, ax=axs[1, 1])
plt.show()
Esempio n. 9
0
def pool_wrapper(args):
    mi_ = Moran(*args)
    return mi_.I, mi_.p_norm