Beispiel #1
0
 def setUp(self):
     self.ntw = network.Network(in_data=examples.get_path('streets.shp'))
     pt_str = 'crimes'
     in_data = examples.get_path('{}.shp'.format(pt_str))
     self.ntw.snapobservations(in_data, pt_str, attribute=True)
     npts = self.ntw.pointpatterns['crimes'].npoints
     self.ntw.simulate_observations(npts)
Beispiel #2
0
 def setUp(self):
     self.ntw = network.Network(in_data=examples.get_path('streets.shp'))
     for obs in ['schools', 'crimes']:
         in_data = examples.get_path('{}.shp'.format(obs))
         self.ntw.snapobservations(in_data, obs, attribute=True)
         #setattr(self, obs, obs)
         setattr(self, obs, self.ntw.pointpatterns[obs])
 def setUp(self):
     path_to_shp = examples.get_path('streets.shp')
     gdf = geopandas.read_file(path_to_shp)
     self.ntw = spgh.Network(in_data=gdf)
     for obs in ['schools', 'crimes']:
         in_data = examples.get_path('{}.shp'.format(obs))
         self.ntw.snapobservations(in_data, obs, attribute=True)
         setattr(self, obs, self.ntw.pointpatterns[obs])
Beispiel #4
0
 def setUp(self):
     path_to_shp = examples.get_path('streets.shp')
     self.ntw = spgh.Network(in_data=path_to_shp)
     self.pt_str = 'schools'
     path_to_shp = examples.get_path('%s.shp' % self.pt_str )
     self.ntw.snapobservations(path_to_shp, self.pt_str , attribute=True)
     npts = self.ntw.pointpatterns[self.pt_str].npoints
     self.ntw.simulate_observations(npts)
     self.test_permutations = 3
     self.test_steps = 5
Beispiel #5
0
 def setUp(self):
     path_to_shp = examples.get_path('streets.shp')
     gdf = geopandas.read_file(path_to_shp)
     self.ntw = network.Network(in_data=gdf)
     pt_str = 'crimes'
     path_to_shp = examples.get_path('{}.shp'.format(pt_str))
     in_data = geopandas.read_file(path_to_shp)
     self.ntw.snapobservations(in_data, pt_str, attribute=True)
     npts = self.ntw.pointpatterns['crimes'].npoints
     self.ntw.simulate_observations(npts)
Beispiel #6
0
 def setUp(self):
     path_to_shp = examples.get_path("streets.shp")
     self.ntw = spgh.Network(in_data=path_to_shp)
     self.pp1_str = "schools"
     self.pp2_str = "crimes"
     iterator = [(self.pp1_str, "pp1"), (self.pp2_str, "pp2")]
     for (obs, idx) in iterator:
         path_to_shp = examples.get_path("%s.shp" % obs)
         self.ntw.snapobservations(path_to_shp, obs, attribute=True)
         setattr(self, idx, self.ntw.pointpatterns[obs])
     self.known_pp1_npoints = 8
Beispiel #7
0
 def setUp(self):
     path_to_shp = examples.get_path('streets.shp')
     self.ntw = spgh.Network(in_data=path_to_shp)
     self.pp1_str = 'schools'
     self.pp2_str = 'crimes'
     iterator = [(self.pp1_str, 'pp1'), (self.pp2_str, 'pp2')]
     for (obs, idx) in iterator:
         path_to_shp = examples.get_path('%s.shp' % obs)
         self.ntw.snapobservations(path_to_shp, obs, attribute=True)
         setattr(self, idx, self.ntw.pointpatterns[obs])
     self.known_pp1_npoints = 8
Beispiel #8
0
def test_moran_facet():
    f = lp.io.open(examples.get_path("sids2.dbf"))
    varnames = ['SIDR74', 'SIDR79', 'NWR74', 'NWR79']
    vars = [np.array(f.by_col[var]) for var in varnames]
    w = lp.io.open(examples.get_path("sids2.gal")).read()
    # calculate moran matrix
    moran_matrix = Moran_BV_matrix(vars, w, varnames=varnames)
    # plot
    fig, axarr = moran_facet(moran_matrix)
    plt.close(fig)
    # customize
    fig, axarr = moran_facet(moran_matrix,
                             scatter_glob_kwds=dict(color='r'),
                             fitline_bv_kwds=dict(color='y'))
    plt.close(fig)
def test_mapclassify_bin():
    # data
    link_to_data = examples.get_path('columbus.shp')
    gdf = gpd.read_file(link_to_data)
    x = gdf['HOVAL'].values
    # quantiles
    mapclassify_bin(x, 'quantiles')
    mapclassify_bin(x, 'quantiles', k=3)
    # box_plot
    mapclassify_bin(x, 'box_plot')
    mapclassify_bin(x, 'box_plot', hinge=2)
    # headtail_breaks
    mapclassify_bin(x, 'headtail_breaks')
    # percentiles
    mapclassify_bin(x, 'percentiles')
    mapclassify_bin(x, 'percentiles', pct=[25, 50, 75, 100])
    # std_mean
    mapclassify_bin(x, 'std_mean')
    mapclassify_bin(x, 'std_mean', multiples=[-1, -0.5, 0.5, 1])
    # maximum_breaks
    mapclassify_bin(x, 'maximum_breaks')
    mapclassify_bin(x, 'maximum_breaks', k=3, mindiff=0.1)
    # natural_breaks, max_p_classifier
    mapclassify_bin(x, 'natural_breaks')
    mapclassify_bin(x, 'max_p_classifier', k=3, initial=50)
    # user_defined
    mapclassify_bin(x, 'user_defined', bins=[20, max(x)])
Beispiel #10
0
def test_moran_loc_bv_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 Univariate and Bivariate Moran
    moran_loc = Moran_Local(y, w)
    moran_loc_bv = Moran_Local_BV(x, y, w)
    # try with p value so points are colored
    fig, _ = _moran_loc_bv_scatterplot(moran_loc_bv)
    plt.close(fig)

    # try with p value and different figure size
    fig, _ = _moran_loc_bv_scatterplot(moran_loc_bv,
                                       p=0.05,
                                       aspect_equal=False)
    plt.close(fig)

    assert_raises(ValueError, _moran_loc_bv_scatterplot, moran_loc, p=0.5)
    assert_warns(UserWarning,
                 _moran_loc_bv_scatterplot,
                 moran_loc_bv,
                 p=0.5,
                 scatter_kwds=dict(c='r'))
Beispiel #11
0
def test_vba_choropleth():
    # data
    link_to_data = examples.get_path('columbus.shp')
    gdf = gpd.read_file(link_to_data)
    x = gdf['HOVAL'].values
    y = gdf['CRIME'].values
    # plot
    fig, _ = vba_choropleth(x, y, gdf)
    plt.close(fig)
    # plot with divergent and reverted alpha
    fig, _ = vba_choropleth(x,
                            y,
                            gdf,
                            cmap='RdBu',
                            divergent=True,
                            revert_alpha=True)
    plt.close(fig)
    # plot with classified alpha and rgb
    fig, _ = vba_choropleth(x,
                            y,
                            gdf,
                            cmap='RdBu',
                            alpha_mapclassify=dict(classifier='quantiles'),
                            rgb_mapclassify=dict(classifier='quantiles'))
    plt.close(fig)
    # plot classified with legend
    fig, _ = vba_choropleth(x,
                            y,
                            gdf,
                            alpha_mapclassify=dict(classifier='std_mean'),
                            rgb_mapclassify=dict(classifier='std_mean'),
                            legend=True)
    plt.close(fig)
Beispiel #12
0
def test_plot_spatial_weights():
    # get data
    gdf = gpd.read_file(examples.get_path('43MUE250GC_SIR.shp'))
    gdf.head()
    # calculate weights
    weights = Queen.from_dataframe(gdf)
    # plot weights
    fig, _ = plot_spatial_weights(weights, gdf)
    plt.close(fig)
    # calculate nonplanar_joins
    wnp = libpysal.weights.util.nonplanar_neighbors(weights, gdf)
    # plot new joins
    fig2, _ = plot_spatial_weights(wnp, gdf)
    plt.close(fig2)
    #customize
    fig3, _ = plot_spatial_weights(wnp,
                                   gdf,
                                   nonplanar_edge_kws=dict(color='#4393c3'))
    plt.close(fig3)
    # plot in existing figure
    fig4, axs = plt.subplots(1, 3)
    plot_spatial_weights(wnp, gdf, ax=axs[0])
    plt.close(fig4)

    # uses a column as the index for spatial weights object
    weights_index = Queen.from_dataframe(gdf, idVariable="CD_GEOCMU")
    fig, _ = plot_spatial_weights(weights_index, gdf, indexed_on="CD_GEOCMU")
    plt.close(fig)
Beispiel #13
0
 def setUp(self):
     self.path_to_shp = examples.get_path('streets.shp')
     
     # network instantiated from shapefile
     self.ntw_from_shp = spgh.Network(in_data=self.path_to_shp,
                                      weightings=True,
                                      w_components=True)
     self.n_known_arcs, self.n_known_vertices = 303, 230
Beispiel #14
0
def test_plot_choropleth():
    link = examples.get_path("columbus.shp")
    df = gpd.read_file(link)

    w = Queen.from_dataframe(df)
    w.transform = "r"

    TOOLS = "tap,help"
    fig = plot_choropleth(
        df, "HOVAL", title="columbus", reverse_colors=True, tools=TOOLS
    )
Beispiel #15
0
def test_moran_scatterplot():
    link = examples.get_path('columbus.shp')
    df = gpd.read_file(link)

    y = df['HOVAL'].values
    w = lp.Queen.from_dataframe(df)
    w.transform = 'r'

    moran_loc = esda.moran.Moran_Local(y, w)

    fig = moran_scatterplot(moran_loc, p=0.05)
Beispiel #16
0
def test_plot_local_autocorrelation():
    link = examples.get_path("columbus.shp")
    df = gpd.read_file(link)

    y = df["HOVAL"].values
    w = Queen.from_dataframe(df)
    w.transform = "r"

    moran_loc = esda.moran.Moran_Local(y, w)

    fig = plot_local_autocorrelation(moran_loc, df, "HOVAL")
Beispiel #17
0
def test_plot_local_autocorrelation():
    link = examples.get_path('columbus.shp')
    df = gpd.read_file(link)

    y = df['HOVAL'].values
    w = lp.Queen.from_dataframe(df)
    w.transform = 'r'

    moran_loc = esda.moran.Moran_Local(y, w)

    fig = plot_local_autocorrelation(moran_loc, df, 'HOVAL')
def _data_generation():
    # get csv and shp
    shp_link = examples.get_path('us48.shp')
    df = gpd.read_file(shp_link)
    income_table = pd.read_csv(examples.get_path("usjoin.csv"))
    # calculate relative values
    for year in range(1969, 2010):
        income_table[str(year) + '_rel'] = (
            income_table[str(year)] / income_table[str(year)].mean())
    # merge
    gdf = df.merge(income_table,left_on='STATE_NAME',right_on='Name')
    # retrieve spatial weights and data for two points in time
    w = Queen.from_dataframe(gdf)
    w.transform = 'r'
    y1 = gdf['1969_rel'].values
    y2 = gdf['2000_rel'].values
    #calculate rose Object
    Y = np.array([y1, y2]).T
    rose = Rose(Y, w, k=5)
    return gdf, y1, rose
def test_vba_legend():
    # data
    link_to_data = examples.get_path('columbus.shp')
    gdf = gpd.read_file(link_to_data)
    x = gdf['HOVAL'].values
    y = gdf['CRIME'].values
    # classify data
    rgb_bins = mapclassify_bin(x, 'quantiles')
    alpha_bins = mapclassify_bin(y, 'quantiles')
    # plot legend
    fig, _ = vba_legend(rgb_bins, alpha_bins, cmap='RdBu')
    plt.close(fig)
Beispiel #20
0
    def test_pp_from_geopandas(self):
        self.gdf_pp1_str = "schools"
        self.gdf_pp2_str = "crimes"
        iterator = [(self.gdf_pp1_str, "gdf_pp1"), (self.gdf_pp2_str, "gdf_pp2")]
        for (obs, idx) in iterator:
            path_to_shp = examples.get_path("%s.shp" % obs)
            in_data = geopandas.read_file(path_to_shp)
            self.ntw.snapobservations(in_data, obs, attribute=True)
            setattr(self, idx, self.ntw.pointpatterns[obs])

        self.assertEqual(self.pp1.npoints, self.gdf_pp1.npoints)
        self.assertEqual(self.pp2.npoints, self.gdf_pp2.npoints)
def test_value_by_alpha_cmap():
    # data
    link_to_data = examples.get_path('columbus.shp')
    gdf = gpd.read_file(link_to_data)
    x = gdf['HOVAL'].values
    y = gdf['CRIME'].values
    # create cmap
    rgba, cmap = value_by_alpha_cmap(x, y)
    # create divergent rgba
    div_rgba, _ = value_by_alpha_cmap(x, y, cmap='seismic', divergent=True)
    # create reverted rgba
    rev_rgba, _ = value_by_alpha_cmap(x, y, cmap='RdBu', revert_alpha=True)
Beispiel #22
0
def test_lisa_cluster():
    link = examples.get_path('columbus.shp')
    df = gpd.read_file(link)

    y = df['HOVAL'].values
    w = Queen.from_dataframe(df)
    w.transform = 'r'

    moran_loc = Moran_Local(y, w)

    fig, _ = lisa_cluster(moran_loc, df)
    plt.close(fig)
Beispiel #23
0
def test_lisa_cluster():
    link = examples.get_path('columbus.shp')
    df = gpd.read_file(link)

    y = df['HOVAL'].values
    w = lp.Queen.from_dataframe(df)
    w.transform = 'r'

    moran_loc = esda.moran.Moran_Local(y, w)

    TOOLS = "tap,reset,help"
    fig = lisa_cluster(moran_loc, df, p=0.05, tools=TOOLS)
Beispiel #24
0
def test_plot_choropleth():
    link = examples.get_path('columbus.shp')
    df = gpd.read_file(link)

    w = lp.Queen.from_dataframe(df)
    w.transform = 'r'

    TOOLS = "tap,help"
    fig = plot_choropleth(df,
                          'HOVAL',
                          title='columbus',
                          reverse_colors=True,
                          tools=TOOLS)
Beispiel #25
0
def _data_generation():
    from giddy.directional import Rose

    # get csv and shp
    shp_link = examples.get_path("us48.shp")
    df = gpd.read_file(shp_link)
    income_table = pd.read_csv(examples.get_path("usjoin.csv"))
    # calculate relative values
    for year in range(1969, 2010):
        income_table[str(year) + "_rel"] = (income_table[str(year)] /
                                            income_table[str(year)].mean())
    # merge
    gdf = df.merge(income_table, left_on="STATE_NAME", right_on="Name")
    # retrieve spatial weights and data for two points in time
    w = Queen.from_dataframe(gdf)
    w.transform = "r"
    y1 = gdf["1969_rel"].values
    y2 = gdf["2000_rel"].values
    # calculate rose Object
    Y = np.array([y1, y2]).T
    rose = Rose(Y, w, k=5)
    return gdf, y1, rose
Beispiel #26
0
def test_moran_bv_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 Bivariate Moran
    moran_bv = Moran_BV(x, y, w)
    # plot
    fig, _ = _moran_bv_scatterplot(moran_bv)
    plt.close(fig)
    # customize plot
    fig, _ = _moran_bv_scatterplot(moran_bv,
                                   fitline_kwds=dict(color='#4393c3'))
    plt.close(fig)
Beispiel #27
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)
Beispiel #28
0
def test_moran_loc_bv_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 Bivariate Moran
    moran_loc_bv = Moran_Local_BV(x, y, w)
    # try with p value so points are colored
    fig, _ = _moran_loc_bv_scatterplot(moran_loc_bv)
    plt.close(fig)

    # try with p value and different figure size
    fig, _ = _moran_loc_bv_scatterplot(moran_loc_bv, p=0.05)
    plt.close(fig)
Beispiel #29
0
def test_moran_loc_scatterplot():
    link = examples.get_path('columbus.shp')
    df = gpd.read_file(link)

    y = df['HOVAL'].values
    w = lp.Queen.from_dataframe(df)
    w.transform = 'r'

    moran_loc = Moran_Local(y, w)

    # try with p value so points are colored
    fig, _ = moran_loc_scatterplot(moran_loc, p=0.05)
    plt.close(fig)

    # try with p value and different figure size
    fig, _ = moran_loc_scatterplot(moran_loc, p=0.05,
                                   fitline_kwds=dict(color='#4393c3'))
    plt.close(fig)
Beispiel #30
0
def test_plot_local_autocorrelation():
    link = examples.get_path('columbus.shp')
    df = gpd.read_file(link)

    y = df['HOVAL'].values
    w = lp.Queen.from_dataframe(df)
    w.transform = 'r'

    moran_loc = Moran_Local(y, w)

    fig, _ = plot_local_autocorrelation(moran_loc, df, 'HOVAL', p=0.05)
    plt.close(fig)

    # also test with quadrant and mask
    fig, _ = plot_local_autocorrelation(moran_loc, df, 'HOVAL', p=0.05,
                                        region_column='POLYID',
                                        mask=['1', '2', '3'], quadrant=1)
    plt.close(fig)
Beispiel #31
0
#import pysal as ps
from libpysal.io import geotable
from libpysal import examples, weights
import numpy as np
from sklearn.metrics import pairwise as skm
from region.skater.skater import Spanning_Forest

import types
import os
TESTDIR = os.path.dirname(os.path.abspath(__file__))


#df = ps.pdio.read_files(ps.examples.get_path('south.shp'))
df = geotable.read_files(examples.get_path('south.shp'))
data = df[df.filter(like='90').columns.tolist()
               + df.filter(like='89').columns.tolist()].values
data_c = (data - data.mean(axis=0)) / data.std(axis=0)
W = weights.Queen.from_dataframe(df)
    
def test_init():
    default = Spanning_Forest()
    assert default.metric == skm.manhattan_distances
    assert default.center == np.mean
    assert default.reduction == np.sum
    change = Spanning_Forest(dissimilarity=skm.euclidean_distances,
                             center=np.median, reduction=np.max)
    assert change.metric == skm.euclidean_distances
    assert change.center == np.median
    assert change.reduction == np.max

    sym = Spanning_Forest(affinity=skm.cosine_similarity)