Skip to content

PySAL

Spatial weights, autocorrelation tests, map classification, inequality measures, and spatial regression from PySAL, callable from SQL

Connector software
Free and open source
Service credentials
Not needed
Use with an agent

Install the Orchard skill in your project to help your agent find connectors, configure them, and verify SQL results.

npx skills add Query-farm/vgi-skills --skill orchard

Copy this request into your coding agent to get started.

Use https://query.farm/products/orchard/connectors/pysal/index.md to help me query PySAL with DuckDB or Haybarn 2.0.1 and VGI protocol 3.4. Ask only for missing details about the result I need or whether I want local execution, self-hosting or Query Farm hosting. Check the connector's actual hosting availability, credentials and input requirements. Read one format of each needed reference and the exact object declarations before writing SQL. Use a released connector, and distinguish a saved example result from anything you actually execute. If you cannot run the query, tell me what remains to verify.

Compare neighborhood crime with nearby areas

Example output · captured
Connector release
v0.2.1
Engine
2.0.1
VGI protocol
3.4.0
WITH c AS (SELECT id, crime FROM pysal.main.columbus()) SELECT w.focal::BIGINT AS id, own.crime AS crime, round(sum(w.weight * nb.crime), 2) AS neighbour_crime, count(*) AS neighbours
FROM pysal.main.weights((SELECT id, geom FROM pysal.main.columbus()), w_type => 'queen', id => 'id') AS w
JOIN c AS own ON own.id = w.focal::BIGINT
JOIN c AS nb ON nb.id = w.neighbor::BIGINT
GROUP BY w.focal, own.crime
ORDER BY neighbour_crime DESC, id
LIMIT 5
Result
id crime neighbour_crime neighbours
23 38.2979 54.91 7
15 54.8387 52.37 8
28 60.7504 51.79 7
17 43.9625 51.18 4
36 42.4451 50.99 6

Quick start

Choose where to run PySAL, then follow the steps below.

The connector runs alongside DuckDB or Haybarn. No Query Farm account is needed.

1. Install the vgi extension

Run this in your SQL client. On DuckDB, keep FROM query_farm on LOAD in later sessions.

setup.sql
SET allow_extension_repositories = 'allowed';

CREATE EXTENSION REPOSITORY IF NOT EXISTS query_farm
    WITH PREFIX 'https://duckdb-extensions.query.farm';

INSTALL vgi FROM query_farm;
LOAD vgi FROM query_farm;

2. Attach the connector

Attach with uvx

Needs uv. uvx builds the worker from its release tag on first attach and reuses the cached environment after that.

ATTACH 'pysal' AS pysal (
  TYPE vgi,
  LOCATION 'uvx --from git+https://github.com/Query-farm/[email protected] vgi-pysal'
);

3. Run a query

query.sql
WITH c AS (SELECT id, crime FROM pysal.main.columbus()) SELECT w.focal::BIGINT AS id, own.crime AS crime, round(sum(w.weight * nb.crime), 2) AS neighbour_crime, count(*) AS neighbours
FROM pysal.main.weights((SELECT id, geom FROM pysal.main.columbus()), w_type => 'queen', id => 'id') AS w
JOIN c AS own ON own.id = w.focal::BIGINT
JOIN c AS nb ON nb.id = w.neighbor::BIGINT
GROUP BY w.focal, own.crime
ORDER BY neighbour_crime DESC, id
LIMIT 5
More example queries →
Technical details
Verified connector release
v0.2.1
Engine
2.0.1
VGI protocol
3.4.0
Verified on
December 1, 2026
Release notes on GitHub
Pin a version for production

When running the connector yourself, keep a specific release until you’re ready to upgrade. Replace the ATTACH statement above with this one and follow the same extension and credential setup.

Attach with uvx

Needs uv. uvx builds the worker from its release tag on first attach and reuses the cached environment after that.

ATTACH 'pysal' AS pysal (
  TYPE vgi,
  LOCATION 'uvx --from git+https://github.com/Query-farm/[email protected] vgi-pysal'
);

Overview

PySAL spatial statistics for SQL: datasets, weights, autocorrelation, classification, and regression.

Catalog

Everything pysal exposes once attached — read straight from the worker's released build.

pysal 1 schema
main 28 functions

PySAL spatial datasets, weights, autocorrelation, classification, and regression for SQL

Schema examples (3)
Examples (3)

Spatial lag of columbus crime: join the row-standardised queen weights edge list to the dataset and average each neighbourhood's neighbours' crime; the five highest-lag neighbourhoods, with their own crime and neighbour count

WITH c AS (SELECT id, crime FROM pysal.main.columbus()) SELECT w.focal::BIGINT AS id, own.crime AS crime, round(sum(w.weight * nb.crime), 2) AS neighbour_crime, count(*) AS neighbours
FROM pysal.main.weights((SELECT id, geom FROM pysal.main.columbus()), w_type => 'queen', id => 'id') AS w
JOIN c AS own ON own.id = w.focal::BIGINT
JOIN c AS nb ON nb.id = w.neighbor::BIGINT
GROUP BY w.focal, own.crime
ORDER BY neighbour_crime DESC, id
LIMIT 5;
Result
id crime neighbour_crime neighbours
23 38.2979 54.91 7
15 54.8387 52.37 8
28 60.7504 51.79 7
17 43.9625 51.18 4
36 42.4451 50.99 6

Profile local Moran crime clusters: join local_moran back to columbus by id and compare average crime, income, and house value per cluster type (high-high clusters are the poorer, lower-value neighbourhoods)

SELECT lm.cluster, count(*) AS neighbourhoods,
  round(avg(c.crime), 1) AS avg_crime, round(avg(c.inc), 1) AS avg_income,
  round(avg(c.hoval), 1) AS avg_house_value
FROM pysal.main.local_moran((SELECT id, crime AS y, geom FROM pysal.main.columbus()), w_type => 'queen', id => 'id') AS lm
JOIN pysal.main.columbus() AS c USING (id)
GROUP BY lm.cluster
ORDER BY avg_crime DESC;

Average columbus crime per household-income quintile: classify income with quantiles, join the classes back to the dataset by id, and aggregate crime per class

SELECT q.class AS income_quintile,
  round(max(q.upper_bound), 2) AS income_upper_bound,
  count(*) AS neighbourhoods, round(avg(c.crime), 1) AS avg_crime
FROM pysal.main.quantiles((SELECT id, inc AS y FROM pysal.main.columbus()), value => 'y', k => 5, id => 'id') AS q
JOIN pysal.main.columbus() AS c USING (id)
GROUP BY q.class
ORDER BY income_quintile;
Table functions
baltim () 1 example

Baltimore house sales prices and hedonic attributes (211 points)

No arguments
Example

Load the baltim dataset

SELECT * FROM pysal.baltim();
Link
columbus () 1 example

Columbus, OH neighbourhood crime, income and home value (49 polygons)

No arguments
Example

Load the columbus dataset

SELECT * FROM pysal.columbus();
Link
drop_model (model_name VARCHAR) 1 example

Delete a model from the registry

Arguments
model_name VARCHAR
Name of the model to delete.
Example

Delete a stored model

SELECT * FROM pysal.drop_model('columbus_err');
Link
georgia () 1 example

Georgia counties educational attainment and demographics (159 polygons)

No arguments
Example

Load the georgia dataset

SELECT * FROM pysal.georgia();
Link
list_models () 1 example

List all spatial-regression models in the registry

No arguments
Example

List stored models

SELECT * FROM pysal.list_models();
Link
mexico () 1 example

Mexican states regional per-capita GDP, 1940-2000 (32 polygons)

No arguments
Example

Load the mexico dataset

SELECT * FROM pysal.mexico();
Link
model_info (model_name VARCHAR) 1 example

Describe a single stored model (one row, empty if absent)

Arguments
model_name VARCHAR
Name of a stored model.
Example

Show one model's metadata

SELECT * FROM pysal.model_info('columbus_err');
Link
sids () 1 example

North Carolina SIDS (sudden infant death) counts and rates by county (100 polygons)

No arguments
Example

Load the sids dataset

SELECT * FROM pysal.sids();
Link
us_states () 1 example

Lower-48 US states boundaries and identifiers (48 polygons)

No arguments
Example

Load the us_states dataset

SELECT * FROM pysal.us_states();
Link
Aggregate functions
gini (value DOUBLE) 1 example

Gini coefficient of inequality (0 = perfect equality, 1 = maximal inequality)

Arguments
value DOUBLE
Numeric value whose distribution is measured
ReturnsDOUBLE
Example

Gini coefficient of Mexican state per-capita GDP in 2000

SELECT pysal.gini(pcgdp2000) FROM pysal.mexico();
Link
theil (value DOUBLE) 1 example

Theil's T entropy index of inequality

Arguments
value DOUBLE
Numeric value whose distribution is measured
ReturnsDOUBLE
Example

Theil index of Mexican state per-capita GDP in 2000

SELECT pysal.theil(pcgdp2000) FROM pysal.mexico();
Link
Table in-out functions
box_plot (data TABLE, id := VARCHAR, k := BIGINT, value := VARCHAR) 1 example

Box-plot classification (quartiles and whiskers; flags outliers)

Positional arguments
data TABLE
Input rows containing the value column (and optional id).
Named arguments
id := VARCHAR
Optional id column to carry through to the output. · default ""
k := BIGINT
Number of classes (ignored by schemes with data-driven class counts). · default 5
value := VARCHAR
Numeric column to classify. · default "y"
Example

Classify columbus crime with box_plot

SELECT id, class, upper_bound
FROM pysal.box_plot((SELECT id, crime AS y FROM pysal.columbus()), value => 'y', id => 'id');
Link
equal_interval (data TABLE, id := VARCHAR, k := BIGINT, value := VARCHAR) 1 example

Equal-interval classification (equal value width per class)

Positional arguments
data TABLE
Input rows containing the value column (and optional id).
Named arguments
id := VARCHAR
Optional id column to carry through to the output. · default ""
k := BIGINT
Number of classes (ignored by schemes with data-driven class counts). · default 5
value := VARCHAR
Numeric column to classify. · default "y"
Example

Classify columbus crime with equal_interval

SELECT id, class, upper_bound
FROM pysal.equal_interval((SELECT id, crime AS y FROM pysal.columbus()), value => 'y', id => 'id', k => 5);
Link
fisher_jenks (data TABLE, id := VARCHAR, k := BIGINT, value := VARCHAR) 1 example

Fisher-Jenks optimal natural-breaks classification

Positional arguments
data TABLE
Input rows containing the value column (and optional id).
Named arguments
id := VARCHAR
Optional id column to carry through to the output. · default ""
k := BIGINT
Number of classes (ignored by schemes with data-driven class counts). · default 5
value := VARCHAR
Numeric column to classify. · default "y"
Example

Classify columbus crime with fisher_jenks

SELECT id, class, upper_bound
FROM pysal.fisher_jenks((SELECT id, crime AS y FROM pysal.columbus()), value => 'y', id => 'id', k => 5);
Link
fit (data TABLE, geom := VARCHAR, id := VARCHAR, k := BIGINT, kernel_function := VARCHAR, model := VARCHAR, model_name := VARCHAR, target := VARCHAR, threshold := DOUBLE, transform := VARCHAR, w_type := VARCHAR, x := VARCHAR, y := VARCHAR) 1 example

Fit a spatial regression model, store it in the registry, and return a summary + model BLOB

Positional arguments
data TABLE
Input rows with a WKB 'geom' column and/or 'x'/'y' coordinate columns.
Named arguments
geom := VARCHAR
WKB geometry column name (for queen/rook). · default "geom"
id := VARCHAR
Optional id column excluded from the explanatory variables. · default ""
k := BIGINT
Number of nearest neighbours (knn, and bandwidth for kernel). · default 4
kernel_function := VARCHAR
Kernel: triangular, uniform, quadratic, quartic, or gaussian. · default "triangular"
model := VARCHAR
Estimator: ols, ml_lag, ml_error, or gm_lag. · default "ols"
model_name := VARCHAR
Name to store the fitted model under (optional). · default ""
target := VARCHAR
Dependent-variable column name (required). · default ""
threshold := DOUBLE
Distance band threshold (distance_band; 0 = auto min-nn distance). · default 0.0
transform := VARCHAR
Weights transform: r (row-standardised), b (binary), o, d, v. · default "r"
w_type := VARCHAR
Weights type: queen, rook, knn, distance_band, or kernel. · default "queen"
x := VARCHAR
X / longitude coordinate column (for distance weights). · default "x"
y := VARCHAR
Y / latitude coordinate column (for distance weights). · default "y"
Example

Fit a spatial error model and store it as 'columbus_err'

SELECT model_name, model_type, pseudo_r2
FROM pysal.fit((SELECT crime AS target, inc, hoval, geom FROM pysal.columbus()), model => 'ml_error', target => 'target', model_name => 'columbus_err');
Link
geary (data TABLE, geom := VARCHAR, k := BIGINT, kernel_function := VARCHAR, permutations := BIGINT, seed := BIGINT, threshold := DOUBLE, transform := VARCHAR, value := VARCHAR, w_type := VARCHAR, x := VARCHAR, y := VARCHAR) 1 example

Global Geary's C spatial autocorrelation statistic

Positional arguments
data TABLE
Input rows with a WKB 'geom' column and/or 'x'/'y' coordinate columns.
Named arguments
geom := VARCHAR
WKB geometry column name (for queen/rook). · default "geom"
k := BIGINT
Number of nearest neighbours (knn, and bandwidth for kernel). · default 4
kernel_function := VARCHAR
Kernel: triangular, uniform, quadratic, quartic, or gaussian. · default "triangular"
permutations := BIGINT
Conditional permutations for inference. · default 999
seed := BIGINT
Random seed for reproducible permutation p-values. · default 12345
threshold := DOUBLE
Distance band threshold (distance_band; 0 = auto min-nn distance). · default 0.0
transform := VARCHAR
Weights transform: r (row-standardised), b (binary), o, d, v. · default "r"
value := VARCHAR
Numeric column to test for spatial autocorrelation. · default "y"
w_type := VARCHAR
Weights type: queen, rook, knn, distance_band, or kernel. · default "queen"
x := VARCHAR
X / longitude coordinate column (for distance weights). · default "x"
y := VARCHAR
Y / latitude coordinate column (for distance weights). · default "y"
Example

Geary's C of neighbourhood crime

SELECT *
FROM pysal.geary((SELECT crime AS y, geom FROM pysal.columbus()), w_type => 'queen');
Link
getis_ord_g (data TABLE, geom := VARCHAR, k := BIGINT, kernel_function := VARCHAR, permutations := BIGINT, seed := BIGINT, threshold := DOUBLE, transform := VARCHAR, value := VARCHAR, w_type := VARCHAR, x := VARCHAR, y := VARCHAR) 1 example

Getis-Ord General G statistic (global concentration of high/low values)

Positional arguments
data TABLE
Input rows with a WKB 'geom' column and/or 'x'/'y' coordinate columns.
Named arguments
geom := VARCHAR
WKB geometry column name (for queen/rook). · default "geom"
k := BIGINT
Number of nearest neighbours (knn, and bandwidth for kernel). · default 4
kernel_function := VARCHAR
Kernel: triangular, uniform, quadratic, quartic, or gaussian. · default "triangular"
permutations := BIGINT
Conditional permutations for inference. · default 999
seed := BIGINT
Random seed for reproducible permutation p-values. · default 12345
threshold := DOUBLE
Distance band threshold (distance_band; 0 = auto min-nn distance). · default 0.0
transform := VARCHAR
Weights transform: r (row-standardised), b (binary), o, d, v. · default "r"
value := VARCHAR
Numeric column to test for spatial autocorrelation. · default "y"
w_type := VARCHAR
Weights type: queen, rook, knn, distance_band, or kernel. · default "queen"
x := VARCHAR
X / longitude coordinate column (for distance weights). · default "x"
y := VARCHAR
Y / latitude coordinate column (for distance weights). · default "y"
Example

General G of crime using 8-nearest-neighbour weights

SELECT *
FROM pysal.getis_ord_g((SELECT crime AS y, geom FROM pysal.columbus()), w_type => 'knn', k => 8);
Link
getis_ord_g_local (data TABLE, geom := VARCHAR, id := VARCHAR, k := BIGINT, kernel_function := VARCHAR, permutations := BIGINT, seed := BIGINT, significance := DOUBLE, star := BOOLEAN, threshold := DOUBLE, transform := VARCHAR, value := VARCHAR, w_type := VARCHAR, x := VARCHAR, y := VARCHAR) 1 example

Local Getis-Ord G_i/G_i* hot-spot and cold-spot analysis

Positional arguments
data TABLE
Input rows with a WKB 'geom' column and/or 'x'/'y' coordinate columns.
Named arguments
geom := VARCHAR
WKB geometry column name (for queen/rook). · default "geom"
id := VARCHAR
Optional id column to carry through to the output. · default ""
k := BIGINT
Number of nearest neighbours (knn, and bandwidth for kernel). · default 4
kernel_function := VARCHAR
Kernel: triangular, uniform, quadratic, quartic, or gaussian. · default "triangular"
permutations := BIGINT
Conditional permutations for inference. · default 999
seed := BIGINT
Random seed for reproducible permutation p-values. · default 12345
significance := DOUBLE
Pseudo p-value cutoff for labelling a location significant. · default 0.05
star := BOOLEAN
Use G_i* (include the focal observation) rather than G_i. · default true
threshold := DOUBLE
Distance band threshold (distance_band; 0 = auto min-nn distance). · default 0.0
transform := VARCHAR
Weights transform: r (row-standardised), b (binary), o, d, v. · default "r"
value := VARCHAR
Numeric column to analyse for local autocorrelation. · default "y"
w_type := VARCHAR
Weights type: queen, rook, knn, distance_band, or kernel. · default "queen"
x := VARCHAR
X / longitude coordinate column (for distance weights). · default "x"
y := VARCHAR
Y / latitude coordinate column (for distance weights). · default "y"
Example

Crime hot/cold spots using G_i* and 8-nearest-neighbour weights

SELECT id, z_score, hotspot
FROM pysal.getis_ord_g_local((SELECT id, crime AS y, geom FROM pysal.columbus()), w_type => 'knn', k => 8, id => 'id');
Link
head_tail_breaks (data TABLE, id := VARCHAR, k := BIGINT, value := VARCHAR) 1 example

Head/tail-breaks classification for heavy-tailed (long-tail) distributions

Positional arguments
data TABLE
Input rows containing the value column (and optional id).
Named arguments
id := VARCHAR
Optional id column to carry through to the output. · default ""
k := BIGINT
Number of classes (ignored by schemes with data-driven class counts). · default 5
value := VARCHAR
Numeric column to classify. · default "y"
Example

Classify columbus crime with head_tail_breaks

SELECT id, class, upper_bound
FROM pysal.head_tail_breaks((SELECT id, crime AS y FROM pysal.columbus()), value => 'y', id => 'id');
Link
local_moran (data TABLE, geom := VARCHAR, id := VARCHAR, k := BIGINT, kernel_function := VARCHAR, permutations := BIGINT, seed := BIGINT, significance := DOUBLE, threshold := DOUBLE, transform := VARCHAR, value := VARCHAR, w_type := VARCHAR, x := VARCHAR, y := VARCHAR) 2 examples

Local Moran's I (LISA): per-observation spatial clusters and outliers

Positional arguments
data TABLE
Input rows with a WKB 'geom' column and/or 'x'/'y' coordinate columns.
Named arguments
geom := VARCHAR
WKB geometry column name (for queen/rook). · default "geom"
id := VARCHAR
Optional id column to carry through to the output. · default ""
k := BIGINT
Number of nearest neighbours (knn, and bandwidth for kernel). · default 4
kernel_function := VARCHAR
Kernel: triangular, uniform, quadratic, quartic, or gaussian. · default "triangular"
permutations := BIGINT
Conditional permutations for inference. · default 999
seed := BIGINT
Random seed for reproducible permutation p-values. · default 12345
significance := DOUBLE
Pseudo p-value cutoff for labelling a location significant. · default 0.05
threshold := DOUBLE
Distance band threshold (distance_band; 0 = auto min-nn distance). · default 0.0
transform := VARCHAR
Weights transform: r (row-standardised), b (binary), o, d, v. · default "r"
value := VARCHAR
Numeric column to analyse for local autocorrelation. · default "y"
w_type := VARCHAR
Weights type: queen, rook, knn, distance_band, or kernel. · default "queen"
x := VARCHAR
X / longitude coordinate column (for distance weights). · default "x"
y := VARCHAR
Y / latitude coordinate column (for distance weights). · default "y"
Examples (2)

Significant local crime clusters/outliers on columbus

SELECT id, cluster, p_value
FROM pysal.local_moran((SELECT id, crime AS y, geom FROM pysal.columbus()), w_type => 'queen', id => 'id')
WHERE p_value < 0.05;

Profile local Moran crime clusters: join local_moran back to columbus by id and compare average crime, income, and house value per cluster type (high-high clusters are the poorer, lower-value neighbourhoods)

SELECT lm.cluster, count(*) AS neighbourhoods,
  round(avg(c.crime), 1) AS avg_crime, round(avg(c.inc), 1) AS avg_income,
  round(avg(c.hoval), 1) AS avg_house_value
FROM pysal.main.local_moran((SELECT id, crime AS y, geom FROM pysal.main.columbus()), w_type => 'queen', id => 'id') AS lm
JOIN pysal.main.columbus() AS c USING (id)
GROUP BY lm.cluster
ORDER BY avg_crime DESC;
Link
moran (data TABLE, geom := VARCHAR, k := BIGINT, kernel_function := VARCHAR, permutations := BIGINT, seed := BIGINT, threshold := DOUBLE, transform := VARCHAR, value := VARCHAR, w_type := VARCHAR, x := VARCHAR, y := VARCHAR) 1 example

Global Moran's I spatial autocorrelation statistic

Positional arguments
data TABLE
Input rows with a WKB 'geom' column and/or 'x'/'y' coordinate columns.
Named arguments
geom := VARCHAR
WKB geometry column name (for queen/rook). · default "geom"
k := BIGINT
Number of nearest neighbours (knn, and bandwidth for kernel). · default 4
kernel_function := VARCHAR
Kernel: triangular, uniform, quadratic, quartic, or gaussian. · default "triangular"
permutations := BIGINT
Conditional permutations for inference. · default 999
seed := BIGINT
Random seed for reproducible permutation p-values. · default 12345
threshold := DOUBLE
Distance band threshold (distance_band; 0 = auto min-nn distance). · default 0.0
transform := VARCHAR
Weights transform: r (row-standardised), b (binary), o, d, v. · default "r"
value := VARCHAR
Numeric column to test for spatial autocorrelation. · default "y"
w_type := VARCHAR
Weights type: queen, rook, knn, distance_band, or kernel. · default "queen"
x := VARCHAR
X / longitude coordinate column (for distance weights). · default "x"
y := VARCHAR
Y / latitude coordinate column (for distance weights). · default "y"
Example

Moran's I of neighbourhood crime using queen contiguity

SELECT *
FROM pysal.moran((SELECT crime AS y, geom FROM pysal.columbus()), w_type => 'queen');
Link
natural_breaks (data TABLE, id := VARCHAR, k := BIGINT, value := VARCHAR) 1 example

Jenks natural-breaks classification (k-means style)

Positional arguments
data TABLE
Input rows containing the value column (and optional id).
Named arguments
id := VARCHAR
Optional id column to carry through to the output. · default ""
k := BIGINT
Number of classes (ignored by schemes with data-driven class counts). · default 5
value := VARCHAR
Numeric column to classify. · default "y"
Example

Classify columbus crime with natural_breaks

SELECT id, class, upper_bound
FROM pysal.natural_breaks((SELECT id, crime AS y FROM pysal.columbus()), value => 'y', id => 'id', k => 5);
Link
predict (data TABLE, id := VARCHAR, model := BLOB, model_name := VARCHAR) 1 example

Predict with a stored spatial-regression model (linear/systematic predictor)

Positional arguments
data TABLE
Rows to score (must contain the model's explanatory columns).
Named arguments
id := VARCHAR
Optional id column to carry through. · default ""
model := BLOB
A model BLOB (as returned by fit). Provide this OR model_name. · default "b''"
model_name := VARCHAR
Name of a model in the registry. Provide this OR model. · default ""
Example

Linear prediction from the stored 'columbus_err' model

SELECT *
FROM pysal.predict((SELECT id, inc, hoval FROM pysal.columbus()), model_name := 'columbus_err', id := 'id');
Link
quantiles (data TABLE, id := VARCHAR, k := BIGINT, value := VARCHAR) 2 examples

Quantile classification (equal number of observations per class)

Positional arguments
data TABLE
Input rows containing the value column (and optional id).
Named arguments
id := VARCHAR
Optional id column to carry through to the output. · default ""
k := BIGINT
Number of classes (ignored by schemes with data-driven class counts). · default 5
value := VARCHAR
Numeric column to classify. · default "y"
Examples (2)

Classify columbus crime with quantiles

SELECT id, class, upper_bound
FROM pysal.quantiles((SELECT id, crime AS y FROM pysal.columbus()), value => 'y', id => 'id', k => 5);

Average columbus crime per household-income quintile: classify income with quantiles, join the classes back to the dataset by id, and aggregate crime per class

SELECT q.class AS income_quintile,
  round(max(q.upper_bound), 2) AS income_upper_bound,
  count(*) AS neighbourhoods, round(avg(c.crime), 1) AS avg_crime
FROM pysal.main.quantiles((SELECT id, inc AS y FROM pysal.main.columbus()), value => 'y', k => 5, id => 'id') AS q
JOIN pysal.main.columbus() AS c USING (id)
GROUP BY q.class
ORDER BY income_quintile;
Link
spreg (data TABLE, geom := VARCHAR, id := VARCHAR, k := BIGINT, kernel_function := VARCHAR, model := VARCHAR, target := VARCHAR, threshold := DOUBLE, transform := VARCHAR, w_type := VARCHAR, x := VARCHAR, y := VARCHAR) 1 example

Fit a spatial regression (OLS/ML_Lag/ML_Error/GM_Lag) and return the coefficient table

Positional arguments
data TABLE
Input rows with a WKB 'geom' column and/or 'x'/'y' coordinate columns.
Named arguments
geom := VARCHAR
WKB geometry column name (for queen/rook). · default "geom"
id := VARCHAR
Optional id column excluded from the explanatory variables. · default ""
k := BIGINT
Number of nearest neighbours (knn, and bandwidth for kernel). · default 4
kernel_function := VARCHAR
Kernel: triangular, uniform, quadratic, quartic, or gaussian. · default "triangular"
model := VARCHAR
Estimator: ols, ml_lag, ml_error, or gm_lag. · default "ols"
target := VARCHAR
Dependent-variable column name (required). · default ""
threshold := DOUBLE
Distance band threshold (distance_band; 0 = auto min-nn distance). · default 0.0
transform := VARCHAR
Weights transform: r (row-standardised), b (binary), o, d, v. · default "r"
w_type := VARCHAR
Weights type: queen, rook, knn, distance_band, or kernel. · default "queen"
x := VARCHAR
X / longitude coordinate column (for distance weights). · default "x"
y := VARCHAR
Y / latitude coordinate column (for distance weights). · default "y"
Example

Maximum-likelihood spatial lag model of columbus crime

SELECT *
FROM pysal.spreg((SELECT crime AS target, inc, hoval, geom FROM pysal.columbus()), model => 'ml_lag', target => 'target', w_type => 'queen');
Link
std_mean (data TABLE, id := VARCHAR, k := BIGINT, value := VARCHAR) 1 example

Standard-deviation classification (breaks at mean +/- multiples of std)

Positional arguments
data TABLE
Input rows containing the value column (and optional id).
Named arguments
id := VARCHAR
Optional id column to carry through to the output. · default ""
k := BIGINT
Number of classes (ignored by schemes with data-driven class counts). · default 5
value := VARCHAR
Numeric column to classify. · default "y"
Example

Classify columbus crime with std_mean

SELECT id, class, upper_bound
FROM pysal.std_mean((SELECT id, crime AS y FROM pysal.columbus()), value => 'y', id => 'id');
Link
weights (data TABLE, geom := VARCHAR, id := VARCHAR, k := BIGINT, kernel_function := VARCHAR, threshold := DOUBLE, transform := VARCHAR, w_type := VARCHAR, x := VARCHAR, y := VARCHAR) 3 examples

Build spatial weights and return the neighbour graph as an edge list

Positional arguments
data TABLE
Input rows with a WKB 'geom' column and/or 'x'/'y' coordinate columns.
Named arguments
geom := VARCHAR
WKB geometry column name (for queen/rook). · default "geom"
id := VARCHAR
Optional id column; focal/neighbor are mapped to its values (else 0-based position). · default ""
k := BIGINT
Number of nearest neighbours (knn, and bandwidth for kernel). · default 4
kernel_function := VARCHAR
Kernel: triangular, uniform, quadratic, quartic, or gaussian. · default "triangular"
threshold := DOUBLE
Distance band threshold (distance_band; 0 = auto min-nn distance). · default 0.0
transform := VARCHAR
Weights transform: r (row-standardised), b (binary), o, d, v. · default "r"
w_type := VARCHAR
Weights type: queen, rook, knn, distance_band, or kernel. · default "queen"
x := VARCHAR
X / longitude coordinate column (for distance weights). · default "x"
y := VARCHAR
Y / latitude coordinate column (for distance weights). · default "y"
Examples (3)

Queen-contiguity neighbour graph for the columbus polygons

SELECT *
FROM pysal.weights((SELECT polyid AS id, geom FROM pysal.columbus()), w_type => 'queen', id => 'id');

5-nearest-neighbour graph from point coordinates

SELECT *
FROM pysal.weights((SELECT polyid AS id, x, y FROM pysal.columbus()), w_type => 'knn', k => 5, id => 'id');

Spatial lag of columbus crime: join the row-standardised queen weights edge list to the dataset and average each neighbourhood's neighbours' crime; the five highest-lag neighbourhoods, with their own crime and neighbour count

WITH c AS (SELECT id, crime FROM pysal.main.columbus()) SELECT w.focal::BIGINT AS id, own.crime AS crime, round(sum(w.weight * nb.crime), 2) AS neighbour_crime, count(*) AS neighbours
FROM pysal.main.weights((SELECT id, geom FROM pysal.main.columbus()), w_type => 'queen', id => 'id') AS w
JOIN c AS own ON own.id = w.focal::BIGINT
JOIN c AS nb ON nb.id = w.neighbor::BIGINT
GROUP BY w.focal, own.crime
ORDER BY neighbour_crime DESC, id
LIMIT 5;
Result
id crime neighbour_crime neighbours
23 38.2979 54.91 7
15 54.8387 52.37 8
28 60.7504 51.79 7
17 43.9625 51.18 4
36 42.4451 50.99 6
Link
weights_summary (data TABLE, geom := VARCHAR, k := BIGINT, kernel_function := VARCHAR, threshold := DOUBLE, transform := VARCHAR, w_type := VARCHAR, x := VARCHAR, y := VARCHAR) 1 example

Structural diagnostics for a spatial weights matrix (connectivity, islands)

Positional arguments
data TABLE
Input rows with a WKB 'geom' column and/or 'x'/'y' coordinate columns.
Named arguments
geom := VARCHAR
WKB geometry column name (for queen/rook). · default "geom"
k := BIGINT
Number of nearest neighbours (knn, and bandwidth for kernel). · default 4
kernel_function := VARCHAR
Kernel: triangular, uniform, quadratic, quartic, or gaussian. · default "triangular"
threshold := DOUBLE
Distance band threshold (distance_band; 0 = auto min-nn distance). · default 0.0
transform := VARCHAR
Weights transform: r (row-standardised), b (binary), o, d, v. · default "r"
w_type := VARCHAR
Weights type: queen, rook, knn, distance_band, or kernel. · default "queen"
x := VARCHAR
X / longitude coordinate column (for distance weights). · default "x"
y := VARCHAR
Y / latitude coordinate column (for distance weights). · default "y"
Example

Connectivity summary of queen weights on columbus

SELECT *
FROM pysal.weights_summary((SELECT geom FROM pysal.columbus()), w_type => 'queen');
Link

Try these queries

Profile local Moran crime clusters: join local_moran back to columbus by id and compare average crime, income, and house value per cluster type (high-high clusters are the poorer, lower-value neighbourhoods)

SELECT lm.cluster, count(*) AS neighbourhoods,
  round(avg(c.crime), 1) AS avg_crime, round(avg(c.inc), 1) AS avg_income,
  round(avg(c.hoval), 1) AS avg_house_value
FROM pysal.main.local_moran((SELECT id, crime AS y, geom FROM pysal.main.columbus()), w_type => 'queen', id => 'id') AS lm
JOIN pysal.main.columbus() AS c USING (id)
GROUP BY lm.cluster
ORDER BY avg_crime DESC

Uses local_morancolumbus

Average columbus crime per household-income quintile: classify income with quantiles, join the classes back to the dataset by id, and aggregate crime per class

SELECT q.class AS income_quintile,
  round(max(q.upper_bound), 2) AS income_upper_bound,
  count(*) AS neighbourhoods, round(avg(c.crime), 1) AS avg_crime
FROM pysal.main.quantiles((SELECT id, inc AS y FROM pysal.main.columbus()), value => 'y', k => 5, id => 'id') AS q
JOIN pysal.main.columbus() AS c USING (id)
GROUP BY q.class
ORDER BY income_quintile

Uses quantilescolumbus

Queen-contiguity neighbour graph for the columbus polygons

SELECT *
FROM pysal.weights((SELECT polyid AS id, geom FROM pysal.columbus()), w_type => 'queen', id => 'id')

Uses weightscolumbus

Load the us_states dataset

SELECT * FROM pysal.us_states()

Uses us_states

Classify columbus crime with std_mean

SELECT id, class, upper_bound
FROM pysal.std_mean((SELECT id, crime AS y FROM pysal.columbus()), value => 'y', id => 'id')

Uses std_meancolumbus

Maximum-likelihood spatial lag model of columbus crime

SELECT *
FROM pysal.spreg((SELECT crime AS target, inc, hoval, geom FROM pysal.columbus()), model => 'ml_lag', target => 'target', w_type => 'queen')

Uses spregcolumbus

25 more examples in the Catalog, each listed under the table or function it uses.

PySAL is an independent open-source connector from Query.Farm. It is not affiliated with, endorsed by or sponsored by the services, projects or organisations it works with. Product names, logos and trademarks belong to their respective owners.