### Install Momepy Directly from GitHub Source: https://github.com/pysal/momepy/blob/main/docs/install.rst Installs the latest development version of Momepy directly from its GitHub repository using pip. This is a convenient way to get the most recent updates. ```shell pip install git+https://github.com/pysal/momepy.git ``` -------------------------------- ### Install Momepy from GitHub Repository Source: https://github.com/pysal/momepy/blob/main/docs/install.rst Clones the Momepy GitHub repository and installs it from the local directory using pip. This method is useful for working with the latest development version but may encounter similar dependency issues as pip installations. ```shell git clone https://github.com/pysal/momepy.git cd momepy pip install . ``` -------------------------------- ### Install Momepy via Pip Source: https://github.com/pysal/momepy/blob/main/docs/install.rst Installs Momepy from the Python Package Index (PyPI) using pip. Users should ensure that all C dependencies are properly installed beforehand, as pip-only installations can sometimes lead to issues. ```shell pip install momepy ``` -------------------------------- ### Create and Activate Momepy Conda Environment Source: https://github.com/pysal/momepy/blob/main/docs/install.rst Creates a new conda environment named 'momepy_env', activates it, configures conda-forge, and installs momepy. This isolates Momepy and its dependencies from other projects. ```shell conda create -n momepy_env conda activate momepy_env conda config --env --add channels conda-forge conda config --env --set channel_priority strict conda install momepy ``` -------------------------------- ### Install Momepy Development Dependencies via Conda Source: https://github.com/pysal/momepy/blob/main/docs/install.rst Installs essential dependencies for Momepy development, including geopandas, networkx, libpysal, and tqdm, using conda from the conda-forge channel. This ensures a robust environment for contributing to Momepy. ```shell conda install -c conda-forge geopandas networkx libpysal tqdm ``` -------------------------------- ### Install Momepy via Conda Source: https://github.com/pysal/momepy/blob/main/docs/install.rst Installs Momepy and its dependencies using conda from the conda-forge channel. It's recommended to add conda-forge to your channels and set strict channel priority for a stable environment. ```shell conda install -c conda-forge momepy ``` -------------------------------- ### Install Black Formatter Source: https://github.com/pysal/momepy/blob/main/docs/contributing.rst Install the Black code formatter using pip. This is necessary if Black is not already installed on your system. ```shell pip install black ``` -------------------------------- ### Import Libraries and Load Data Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/migration.ipynb Initializes GeoPandas, momepy, and libpysal graph, then loads sample building and tessellation data from momepy datasets. ```python import geopandas as gpd import momepy from libpysal import graph buildings = gpd.read_file( momepy.datasets.get_path("bubenec"), layer="buildings" ) tessellation = gpd.read_file( momepy.datasets.get_path("bubenec"), layer="tessellation" ) ``` -------------------------------- ### Make a Development Build of momepy Source: https://github.com/pysal/momepy/blob/main/docs/contributing.rst Command to install momepy in an editable mode from the source directory, allowing for immediate changes without reinstallation. ```bash pip install -e . ``` -------------------------------- ### Configure Conda Channels for Momepy Source: https://github.com/pysal/momepy/blob/main/docs/install.rst Adds the conda-forge channel to your conda configuration and sets strict channel priority. This ensures that dependencies are resolved from the preferred, community-maintained channel. ```shell conda config --add channels conda-forge conda config --env --set channel_priority strict ``` -------------------------------- ### Install Momepy with Pip Source: https://github.com/pysal/momepy/blob/main/paper/paper.md Installs Momepy using pip. This method is possible but requires that all dependency requirements are manually met beforehand to ensure compatibility. ```shell pip install momepy ``` -------------------------------- ### Install momepy Dependencies Source: https://github.com/pysal/momepy/blob/main/docs/contributing.rst Commands to configure conda channels and install all necessary dependencies for momepy development, ensuring compatibility. ```bash conda config --env --add channels conda-forge conda config --env --set channel_priority strict conda install geopandas networkx libpysal tqdm pysal mapclassify pytest ``` -------------------------------- ### Run Momepy Tests Source: https://github.com/pysal/momepy/blob/main/docs/contributing.rst Execute the project's test suite using pytest. This command can be run directly from the Git clone without installing momepy. ```shell pytest ``` -------------------------------- ### Install Momepy with Conda Source: https://github.com/pysal/momepy/blob/main/paper/paper.md Installs Momepy and its dependencies using the conda-forge channel, which is recommended for ensuring compatibility of all required geospatial libraries. ```shell conda install -c conda-forge momepy ``` -------------------------------- ### Calculate Neighbors using libpysal W (Old API) Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/migration.ipynb Shows the legacy approach to building spatial contiguity using momepy's `sw_high` (which relies on libpysal W) and calculating neighbors. ```python # Old API (deprecated) # contiguity_k2 = momepy.sw_high(k=2, gdf=tessellation, ids="uID") # tessellation["neighbours"] = momepy.Neighbors( # tessellation, contiguity_k2, "uID", weighted=True # ).series ``` -------------------------------- ### Geometry and Graph Mapping via Index (New API) Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/migration.ipynb Demonstrates how the new momepy API maps geometries to libpysal Graphs using the GeoPandas index, ensuring data integrity. ```python contiguity = graph.Graph.build_contiguity(geometry) momepy.neighbor_distance(geometry, contiguity) ``` -------------------------------- ### Calculate Equivalent Rectangular Index (New vs. Old API) Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/migration.ipynb Demonstrates calculating the equivalent rectangular index for buildings using the new functional API and compares it to the deprecated class-based API. ```python # New API buildings["eri"] = momepy.equivalent_rectangular_index(buildings) # Old API (deprecated) # buildings["eri"] = momepy.EquivalentRectangularIndex(buildings).series ``` -------------------------------- ### Calculate Neighbors using libpysal Graph (New API) Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/migration.ipynb Illustrates building spatial contiguity using libpysal's Graph and calculating weighted neighbors for tessellation data with the new momepy API. ```python # build contiguity of order 2 contiguity_k2 = graph.Graph.build_contiguity(tessellation).higher_order( 2, lower_order=True ) # measure neighbors tessellation["neighbours_weighted"] = momepy.neighbors( tessellation, contiguity_k2, weighted=True ) ``` -------------------------------- ### Measure Area (New vs. Old API) Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/migration.ipynb Shows how to measure the area of buildings using the new API's direct GeoPandas integration and contrasts it with the legacy momepy wrapper class. ```python # New API buildings["area"] = buildings.area # Old API (deprecated) # buildings["area"] = momepy.Area(buildings).series ``` -------------------------------- ### Series and Graph Mapping via Index (New API) Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/migration.ipynb Explains linking a pandas Series to a libpysal Graph using the index, assuming the Series index matches the original geometry's index. ```python # typically, the Series is taken directly from the DataFrame contiguity = graph.Graph.build_contiguity(geometry) momepy.alignment(geometry["orientation"], contiguity) ``` -------------------------------- ### Link Geometry to Two Graphs Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/migration.ipynb Demonstrates linking geometric data to two distinct graph structures. This approach is suitable when both graphs share a common index derived from the same geometry. ```Python import momepy import libpysal.graph as graph # Assuming 'geometry' is a GeoDataFrame or similar # Build adjacency graph based on contiguity adjacency_graph = graph.Graph.build_contiguity(geometry) # Build neighborhood graph based on distance band neighborhood_graph = graph.Graph.build_distance_band( geometry, threshold=400, ) # Calculate mean interbuilding distance using the geometry and both graphs momepy.mean_interbuilding_distance( geometry, adjacency_graph, neighborhood_graph, ) ``` -------------------------------- ### Link Geometry to Street Network Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/migration.ipynb Explains how to associate geometric features, like buildings, with street segments. This involves finding the nearest street for each building and then aligning geometric attributes like orientation. ```Python import momepy # Assuming 'buildings' and 'street_edges' are GeoDataFrames # Assign the index of the nearest street segment to each building buildings["street_index"] = momepy.get_nearest_street( buildings, street_edges, ) # Align orientation attributes between buildings and street segments using the network index momepy.street_alignment( buildings["orientation"], street_edges["orientation"], network_id="street_index", ) ``` -------------------------------- ### Get Nearest Street Edge Index for Buildings Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/elements/links.ipynb Links building footprints to the nearest street network edge by calculating the index of the closest street. It takes building and street GeoDataFrames as input and returns a Series of street indices. A `max_distance` parameter can limit the search radius to improve performance. ```Python import geopandas as gpd import momepy # Load example data path = momepy.datasets.get_path("bubenec") buildings = gpd.read_file(path, layer="buildings") streets = gpd.read_file(path, layer="streets") # Link buildings to nearest street edge index buildings["street_index"] = momepy.get_nearest_street(buildings, streets) ``` -------------------------------- ### Get Nearest Street Node Index for Buildings Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/elements/links.ipynb Links building footprints to the nearest street network node. This function requires building GeoDataFrame, nodes GeoDataFrame, edges GeoDataFrame, and the edge index for each building. It ensures the nearest node is an endpoint of the nearest edge, returning a Series of node indices. ```Python import geopandas as gpd import momepy # Load example data path = momepy.datasets.get_path("bubenec") buildings = gpd.read_file(path, layer="buildings") streets = gpd.read_file(path, layer="streets") # Convert streets to graph and then to GeoDataFrames graph = momepy.gdf_to_nx(streets) nodes, edges = momepy.nx_to_gdf(graph) # First, link buildings to nearest edge buildings["edge_index"] = momepy.get_nearest_street(buildings, edges) # Then, link buildings to the nearest node on that edge buildings["node_index"] = momepy.get_nearest_node( buildings, nodes, edges, buildings["edge_index"] ) ``` -------------------------------- ### Build Momepy Documentation (Local) Source: https://github.com/pysal/momepy/blob/main/docs/contributing.rst Build the HTML documentation for momepy locally. Navigate to the 'docs' folder and run the make command. This process uses Sphinx and reStructuredText. ```shell make html ``` -------------------------------- ### Fork and Clone momepy Repository Source: https://github.com/pysal/momepy/blob/main/docs/contributing.rst Commands to fork the momepy repository, clone it locally, and set up the upstream remote for tracking the main project. ```bash git clone git@github.com:your-user-name/momepy.git momepy-yourname cd momepy-yourname git remote add upstream git://github.com/pysal/momepy.git ``` -------------------------------- ### Build Momepy Documentation (Conda Environment) Source: https://github.com/pysal/momepy/blob/main/docs/contributing.rst Build the HTML documentation for momepy using a specific conda environment. This ensures all dependencies are correctly set up for the documentation build process. ```shell conda env create -f environment.yml conda activate geopandas_docs make html ``` -------------------------------- ### Activate momepy Development Environment Source: https://github.com/pysal/momepy/blob/main/docs/contributing.rst Commands to activate the created conda environment on Windows, macOS, and Linux systems. ```bash # Windows users: activate momepy_dev # macOS and Linux users: conda activate momepy_dev ``` -------------------------------- ### Create momepy Development Environment Source: https://github.com/pysal/momepy/blob/main/docs/contributing.rst Steps to create a dedicated conda environment for momepy development, ensuring isolation from other projects. ```bash conda create -n momepy_dev ``` -------------------------------- ### Create GeoDataFrame and Plot Original Network Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/preprocessing/simple_preprocessing.ipynb Creates a GeoDataFrame from the defined LineStrings and visualizes the initial disconnected network. ```python df = gpd.GeoDataFrame(["a", "b", "c", "d", "e"], geometry=[l1, l2, l3, l4, l5]) df.plot(figsize=(10, 10)).set_axis_off() ``` -------------------------------- ### Import Libraries Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/preprocessing/simple_preprocessing.ipynb Imports necessary libraries for geospatial data handling (geopandas) and network preprocessing (momepy, shapely). ```python import geopandas as gpd import momepy from shapely.geometry import LineString ``` -------------------------------- ### Create GeoDataFrame and Plot for Extension Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/preprocessing/simple_preprocessing.ipynb Creates a GeoDataFrame from the defined LineStrings and visualizes them before applying the line extension function. ```python df = gpd.GeoDataFrame(["a", "b", "c", "d", "e"], geometry=[l1, l2, l3, l4, l5]) df.plot(figsize=(10, 10)).set_axis_off() ``` -------------------------------- ### Load and Preprocess Building Data Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/weights/two.ipynb Fetches building data for a specified location using osmnx, projects it to a suitable CRS, and generates a tessellation based on a buffered limit. This prepares the data for subsequent spatial analyses. ```Python gdf = ox.features_from_place("Kahla, Germany", tags={"building": True}) buildings = ox.projection.project_gdf(gdf).reset_index() limit = momepy.buffered_limit(buildings) tessellation = momepy.morphological_tessellation(buildings, clip=limit) ``` -------------------------------- ### Compare Original and Extended Network Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/preprocessing/simple_preprocessing.ipynb Compares the original LineStrings with the extended network, illustrating the effect of `momepy.extend_lines` in closing gaps by extension. ```python ax = extended.plot(figsize=(10, 10), color="r") df.plot(ax=ax) ax.set_axis_off() ``` -------------------------------- ### Import Libraries Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/weights/two.ipynb Imports necessary libraries for spatial analysis, including momepy for urban morphology, osmnx for geospatial data retrieval, and libpysal for graph building. ```Python import momepy import osmnx as ox from libpysal import graph ``` -------------------------------- ### Visualize Dual Graph Conversion Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/graph/convert.ipynb Illustrates the conversion of street data to a dual NetworkX graph. It shows the original streets, the generated dual graph nodes, and an overlay of both for comparison. ```python f, ax = plt.subplots(1, 3, figsize=(18, 6), sharex=True, sharey=True) streets.plot(color="#e32e00", ax=ax[0]) for i, facet in enumerate(ax): facet.set_title(("Streets", "Dual graph", "Overlay")[i]) facet.axis("off") nx.draw( dual, {n: [n[0], n[1]] for n in list(dual.nodes)}, ax=ax[1], node_size=15 ) streets.plot(color="#e32e00", ax=ax[2], zorder=-1) nx.draw( dual, {n: [n[0], n[1]] for n in list(dual.nodes)}, ax=ax[2], node_size=15 ) ``` -------------------------------- ### Plot Extended Network Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/preprocessing/simple_preprocessing.ipynb Visualizes the network after applying `momepy.extend_lines`, showing how the LineStrings have been extended to meet each other. ```python extended.plot(figsize=(10, 10)).set_axis_off() ``` -------------------------------- ### Manage Conda Environments Source: https://github.com/pysal/momepy/blob/main/docs/contributing.rst Commands to view all available conda environments and to deactivate the current active environment. ```bash conda info -e deactivate ``` -------------------------------- ### Import Libraries Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/graph/convert.ipynb Imports essential libraries for geospatial data manipulation, plotting, and network analysis, including geopandas, matplotlib, momepy, and networkx. ```python import geopandas as gpd import matplotlib.pyplot as plt import momepy import networkx as nx ``` -------------------------------- ### Load Network Data for False Node Removal Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/preprocessing/simple_preprocessing.ipynb Loads a sample network dataset ('broken_network') from momepy datasets, which contains topological errors like false nodes. ```python from mapclassify import greedy df = gpd.read_file(momepy.datasets.get_path("tests"), layer="broken_network") ``` -------------------------------- ### Visualize Primal Graph Conversion Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/graph/convert.ipynb Illustrates the conversion of street data to a primal NetworkX graph. It displays the original streets, the generated primal graph nodes, and an overlay of both. ```python f, ax = plt.subplots(1, 3, figsize=(18, 6), sharex=True, sharey=True) streets.plot(color="#e32e00", ax=ax[0]) for i, facet in enumerate(ax): facet.set_title(("Streets", "Primal graph", "Overlay")[i]) facet.axis("off") nx.draw( graph, {n: [n[0], n[1]] for n in list(graph.nodes)}, ax=ax[1], node_size=15 ) streets.plot(color="#e32e00", ax=ax[2], zorder=-1) nx.draw( graph, {n: [n[0], n[1]] for n in list(graph.nodes)}, ax=ax[2], node_size=15 ) ``` -------------------------------- ### Plot Network with False Nodes Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/preprocessing/simple_preprocessing.ipynb Visualizes the loaded network data, using `mapclassify.greedy` to color-code segments and highlight the presence of false nodes and incorrect topology. ```python df.plot( greedy(df), categorical=True, figsize=(10, 10), cmap="Set3" ).set_axis_off() ``` -------------------------------- ### Data Preprocessing Functions Source: https://github.com/pysal/momepy/blob/main/docs/api.rst Functions to adapt input data and fix common issues, ensuring data quality for urban analysis algorithms. ```APIDOC close_gaps - Closes gaps in geometric features. extend_lines - Extends lines to meet certain criteria. remove_false_nodes - Removes spurious nodes from geometric networks. consolidate_intersections - Consolidates intersection points. roundabout_simplification - Simplifies roundabout geometries. ``` -------------------------------- ### Format Momepy Code with Black Source: https://github.com/pysal/momepy/blob/main/docs/contributing.rst Auto-format the momepy project's Python code according to the Black formatter. This command checks for files that would be auto-formatted and can be used before submitting code. ```shell black momepy ``` -------------------------------- ### Compare Original and Fixed Network (Close Gaps) Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/preprocessing/simple_preprocessing.ipynb Compares the original disconnected LineStrings (in red) with the network after closing gaps, highlighting the effect of the `close_gaps` function. ```python ax = df.plot(alpha=0.5, figsize=(10, 10)) gpd.GeoDataFrame(geometry=[l1, l2, l3, l4, l5]).plot( ax=ax, color="r", alpha=0.5 ) ax.set_axis_off() ``` -------------------------------- ### Define LineStrings for Extension Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/preprocessing/simple_preprocessing.ipynb Defines several LineString geometries that are close but not connected, suitable for demonstrating line extension. ```python l1 = LineString([(0, 0), (2, 0)]) l2 = LineString([(2.1, -1), (2.1, 1)]) l3 = LineString([(3.1, 2), (4, 0.1)]) l4 = LineString([(3.5, 0), (5, 0)]) l5 = LineString([(2.2, 0), (3.5, 1)]) ``` -------------------------------- ### Network Conversion Utilities Source: https://github.com/pysal/momepy/blob/main/docs/api.rst Utilities for converting between networkx graph objects and GeoPandas GeoDataFrame objects, facilitating interoperability. ```APIDOC gdf_to_nx - Converts a GeoDataFrame to a networkx graph. nx_to_gdf - Converts a networkx graph to a GeoDataFrame. ``` -------------------------------- ### Apply momepy.close_gaps Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/preprocessing/simple_preprocessing.ipynb Applies the `momepy.close_gaps` function to snap nearby endpoints and close gaps in the network, using a specified tolerance. ```python df.geometry = momepy.close_gaps(df, 0.25) ``` -------------------------------- ### Connectivity Measurement Functions Source: https://github.com/pysal/momepy/blob/main/docs/api.rst Functions for analyzing the connectivity and configuration of street networks, including centrality measures, density, and ratios. ```APIDOC betweenness_centrality - Calculates betweenness centrality for nodes. cds_length - Calculates the length of cyclic dependency structures. closeness_centrality - Calculates closeness centrality for nodes. clustering - Computes clustering coefficients. cyclomatic - Calculates the cyclomatic number of the network. edge_node_ratio - Computes the ratio of edges to nodes. gamma - Calculates the gamma index of network connectivity. mean_node_degree - Computes the mean degree of nodes. mean_node_dist - Calculates the mean distance between nodes. mean_nodes - Computes the mean number of nodes. meshedness - Measures the meshedness of the network. node_degree - Calculates the degree of nodes. node_density - Computes the density of nodes. proportion - Calculates the proportion of certain features. straightness_centrality - Calculates straightness centrality. subgraph - Extracts subgraph information. COINS - Calculates COINS (Connectivity Index for Street Networks). ``` -------------------------------- ### Plot Fixed Network (Close Gaps) Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/preprocessing/simple_preprocessing.ipynb Visualizes the network after applying `momepy.close_gaps` to show the corrected topology with connected endpoints. ```python df.plot(figsize=(10, 10)).set_axis_off() ``` -------------------------------- ### Data Assessment Tools Source: https://github.com/pysal/momepy/blob/main/docs/api.rst Tools for assessing the quality and characteristics of input data, particularly for tessellation processes. ```APIDOC CheckTessellationInput - A class for checking tessellation input data. FaceArtifacts - Identifies and handles artifacts within faces of tessellations. ``` -------------------------------- ### Convert NetworkX Graph to GeoDataFrames (Nodes and Edges) Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/elements/links.ipynb Transforms a NetworkX graph, typically derived from street data, into separate GeoDataFrames for nodes and edges. This allows for spatial analysis and visualization of network components. It requires a NetworkX graph as input and returns two GeoDataFrames. ```Python import momepy import geopandas as gpd import networkx as nx # Assume 'graph' is a NetworkX graph object # For example, created from streets GeoDataFrame: # path = momepy.datasets.get_path("bubenec") # streets = gpd.read_file(path, layer="streets") # graph = momepy.gdf_to_nx(streets) # Placeholder for graph object if not defined above # In a real scenario, 'graph' would be populated from gdf_to_nx if 'graph' not in locals(): # Create a dummy graph for demonstration if needed graph = nx.Graph() graph.add_edge(0, 1, geometry=None) graph.add_edge(1, 2, geometry=None) # Convert graph to GeoDataFrames nodes, edges = momepy.nx_to_gdf(graph) ``` -------------------------------- ### Morphological Element Management Functions Source: https://github.com/pysal/momepy/blob/main/docs/api.rst Functions for creating and managing bespoke morphological geometric features, including tessellations and block generation, along with tools for verification and linking elements. ```APIDOC morphological_tessellation - Creates a tessellation of a GeoDataFrame. enclosed_tessellation - Creates a tessellation of a GeoDataFrame within specified enclosures. enclosures - Identifies and creates enclosures from a GeoDataFrame. generate_blocks - Generates building blocks from a GeoDataFrame. buffered_limit - Applies a buffer to limit geometric features. verify_tessellation - Verifies the integrity of a tessellation. get_nearest_street - Finds the nearest street segment for each feature. get_nearest_node - Finds the nearest node in a network for each feature. get_network_ratio - Calculates the network ratio for features. ``` -------------------------------- ### Shape Measurement Functions Source: https://github.com/pysal/momepy/blob/main/docs/api.rst A collection of functions designed to quantify the shape characteristics of geometric elements, including compactness, convexity, and aspect ratios. ```APIDOC centroid_corner_distance - Measures the distance from the centroid to corners. circular_compactness - Calculates circular compactness of shapes. compactness_weighted_axis - Computes compactness weighted by axis length. convexity - Measures the convexity of shapes. corners - Identifies and quantifies corners in shapes. courtyard_index - Calculates an index for courtyards. elongation - Measures the elongation of shapes. equivalent_rectangular_index - Computes the equivalent rectangular index. facade_ratio - Calculates the facade ratio of buildings. form_factor - Measures the form factor of shapes. fractal_dimension - Computes the fractal dimension of shapes. linearity - Measures the linearity of shapes. rectangularity - Calculates the rectangularity of shapes. shape_index - Computes the shape index. square_compactness - Measures the square compactness of shapes. squareness - Calculates the squareness of shapes. sunlight_optimised - Assesses sunlight optimization of shapes. ``` -------------------------------- ### Plot Network After Removing False Nodes Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/preprocessing/simple_preprocessing.ipynb Visualizes the network after applying `momepy.remove_false_nodes`, demonstrating the corrected topology with fewer features and proper intersections. ```python fixed.plot( greedy(fixed), categorical=True, figsize=(10, 10), cmap="Set3" ).set_axis_off() ``` -------------------------------- ### Define Disconnected LineStrings Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/preprocessing/simple_preprocessing.ipynb Defines several LineString geometries with small gaps between their endpoints, representing a disconnected network. ```python l1 = LineString([(1, 0), (2, 1)]) l2 = LineString([(2.1, 1), (3, 2)]) l3 = LineString([(3.1, 2), (4, 0)]) l4 = LineString([(4.1, 0), (5, 0)]) l5 = LineString([(5.1, 0), (6, 0)]) ``` -------------------------------- ### Plot Nodes with Degree Attribute Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/graph/convert.ipynb Visualizes the nodes of the street network, coloring them based on their calculated 'degree' attribute and scaling marker size accordingly. Edges are plotted in the background. ```python ax = nodes.plot( column="degree", cmap="tab20b", markersize=(nodes["degree"] * 100), zorder=2, figsize=(8, 8), ) edges.plot(ax=ax, color="lightgrey", zorder=1) ax.set_axis_off() ``` -------------------------------- ### Convert Street Network GeoDataFrame to NetworkX Graph Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/elements/links.ipynb Converts a GeoDataFrame representing street edges into a NetworkX graph object. This is a prerequisite for many graph-based analyses within momepy. The function takes the street GeoDataFrame and returns a NetworkX graph. ```Python import momepy import geopandas as gpd # Load street data path = momepy.datasets.get_path("bubenec") streets = gpd.read_file(path, layer="streets") # Convert to NetworkX graph graph = momepy.gdf_to_nx(streets) ``` -------------------------------- ### Display Head of Edges GeoDataFrame Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/graph/convert.ipynb Displays the first few rows of the GeoDataFrame representing the edges of the street network, showing their geometry and connectivity information. ```python edges.head(3) ``` -------------------------------- ### Apply momepy.extend_lines Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/preprocessing/simple_preprocessing.ipynb Applies the `momepy.extend_lines` function to extend LineStrings until they meet other geometry within a specified tolerance, closing gaps. ```python extended = momepy.extend_lines(df, tolerance=0.2) ``` -------------------------------- ### Transfer Street Network IDs to Tessellation Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/elements/links.ipynb Copies street network-related indices (like edge_index and node_index) from a buildings GeoDataFrame to a tessellation GeoDataFrame. This assumes both GeoDataFrames share the same index, allowing for seamless transfer of spatial linkage information. ```Python import geopandas as gpd import momepy # Assume 'buildings' and 'tessellation' GeoDataFrames are loaded # and 'buildings' has 'edge_index' and 'node_index' columns # For example: # path = momepy.datasets.get_path("bubenec") # buildings = gpd.read_file(path, layer="buildings") # streets = gpd.read_file(path, layer="streets") # tessellation = gpd.read_file(path, layer="tessellation") # graph = momepy.gdf_to_nx(streets) # nodes, edges = momepy.nx_to_gdf(graph) # buildings["edge_index"] = momepy.get_nearest_street(buildings, edges) # buildings["node_index"] = momepy.get_nearest_node(buildings, nodes, edges, buildings["edge_index"]) # Placeholder for GeoDataFrames if not defined above if 'buildings' not in locals() or 'tessellation' not in locals(): # Create dummy GeoDataFrames for demonstration from shapely.geometry import Polygon, Point buildings = gpd.GeoDataFrame({'geometry': [Polygon([(0,0),(1,0),(1,1),(0,1)])], 'edge_index': [0]}) tessellation = gpd.GeoDataFrame({'geometry': [Polygon([(0,0),(1,0),(1,1),(0,1)])]}) buildings['node_index'] = 1 # Transfer IDs from buildings to tessellation tessellation["edge_index"] = buildings["edge_index"] tessellation["node_index"] = buildings["node_index"] ``` -------------------------------- ### Display Head of Nodes GeoDataFrame Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/graph/convert.ipynb Shows the first few rows of the GeoDataFrame representing the nodes of the street network, including their geometry and attributes like 'degree'. ```python nodes.head(3) ``` -------------------------------- ### Convert NetworkX Graph back to GeoDataFrames Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/graph/convert.ipynb Converts a NetworkX graph back into GeoDataFrames for nodes, edges, and spatial weights. It allows specifying which components to export. ```python nodes, edges, sw = momepy.nx_to_gdf( graph, points=True, lines=True, spatial_weights=True ) ``` -------------------------------- ### Intensity Measurement Functions Source: https://github.com/pysal/momepy/blob/main/docs/api.rst Functions to measure intensity characters of urban elements. Additional intensity characters can be derived using libpysal. ```APIDOC courtyards - Measures intensity characters related to courtyards. Note: Additional intensity characters can be directly derived using :meth:`libpysal.graph.Graph.describe` and functions :func:`describe_agg` and :func:`describe_reached_agg`. ``` -------------------------------- ### Streetscape Analysis Class Source: https://github.com/pysal/momepy/blob/main/docs/api.rst Specialized class for advanced streetscape analysis, including computation of plots, slopes, and level analysis. ```APIDOC Streetscape - A class for performing streetscape analysis. Streetscape.compute_plots - Computes plots related to streetscape analysis. Streetscape.compute_slope - Computes the slope for streetscape elements. Streetscape.street_level - Analyzes street-level features. Streetscape.point_level - Analyzes point-level features within the streetscape. ``` -------------------------------- ### Plot Mean Interbuilding Distance Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/weights/two.ipynb Displays the mean interbuilding distance values on a map using a quantile classification scheme. This visualization helps understand the spatial distribution of average distances between buildings within their neighborhoods. ```Python ax = buildings.plot( column="mean_ib_dist", scheme="quantiles", k=10, legend=True, figsize=(8, 8) ) ax.set_axis_off() ``` -------------------------------- ### Read Street Network GeoDataFrame Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/graph/convert.ipynb Loads street network data from a shapefile into a GeoDataFrame using geopandas. It specifies the dataset path and layer name for reading the geospatial data. ```python streets = gpd.read_file(momepy.datasets.get_path("bubenec"), layer="streets") ``` -------------------------------- ### Spatial Distribution Measurement Functions Source: https://github.com/pysal/momepy/blob/main/docs/api.rst Functions for analyzing the spatial distribution and relationships between geometric elements, such as adjacency, alignment, and distances. ```APIDOC alignment - Measures the alignment of features. building_adjacency - Analyzes building adjacency. cell_alignment - Measures cell alignment. mean_interbuilding_distance - Calculates the mean distance between buildings. neighbor_distance - Measures the distance to nearest neighbors. neighbors - Identifies neighboring features. orientation - Measures the orientation of features. shared_walls - Analyzes shared walls between features. street_alignment - Measures street alignment. ``` -------------------------------- ### Diversity Measurement Functions Source: https://github.com/pysal/momepy/blob/main/docs/api.rst Functions for measuring spatial diversity of elements and their values, including entropy and concentration measures. Underlying components for Shannon and Simpson diversity are also exposed. ```APIDOC describe_agg - Aggregates descriptive statistics. describe_reached_agg - Aggregates descriptive statistics for reached elements. gini - Calculates the Gini coefficient. percentile - Computes percentile values. shannon - Calculates Shannon diversity. simpson - Calculates Simpson diversity. theil - Calculates Theil index. values_range - Computes the range of values. mean_deviation - Calculates the mean deviation. shannon_diversity - Underlying component for Shannon diversity calculation. simpson_diversity - Underlying component for Simpson diversity calculation. Note: Additional diversity characters can be directly derived using :meth:`libpysal.graph.Graph.describe`. ``` -------------------------------- ### Convert GeoDataFrame to NetworkX Graph (Dual) Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/graph/convert.ipynb Converts a GeoDataFrame of street segments into a NetworkX graph using the 'dual' approach. This method is useful for capturing connectivity and angular relationships between segments. ```python dual = momepy.gdf_to_nx(streets, approach="dual") ``` -------------------------------- ### Convert GeoDataFrame to NetworkX Graph (Primal) Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/graph/convert.ipynb Converts a GeoDataFrame of street segments into a NetworkX graph using the 'primal' approach. This method preserves segment lengths as edge weights, suitable for distance-based analysis. ```python graph = momepy.gdf_to_nx(streets, approach="primal") ``` -------------------------------- ### Plot Street Network Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/graph/convert.ipynb Visualizes the street network GeoDataFrame using matplotlib. It plots the data and turns off the axis for a cleaner display of the street layout. ```python ax = streets.plot(figsize=(8, 8)) ax.set_axis_off() ``` -------------------------------- ### Convert Graph to GeoDataFrame (Default Index Handling) Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/graph/convert.ipynb Converts a NetworkX graph back to a GeoDataFrame without preserving the original index or order. This demonstrates the default behavior when `preserve_index` is not explicitly set. ```python graph = momepy.gdf_to_nx(streets) edges = momepy.nx_to_gdf(graph, points=False) edges.head() ``` -------------------------------- ### Dimension Measurement Functions Source: https://github.com/pysal/momepy/blob/main/docs/api.rst A set of functions to measure various dimensions of geometric elements, such as area, length, perimeter, and volume. ```APIDOC courtyard_area - Measures the area of courtyards. floor_area - Calculates the floor area of buildings. longest_axis_length - Determines the length of the longest axis of a geometric shape. perimeter_wall - Measures the perimeter of walls. street_profile - Analyzes the profile of street segments. volume - Calculates the volume of geometric elements. weighted_character - Computes a weighted character based on geometric properties. ``` -------------------------------- ### Apply momepy.remove_false_nodes Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/preprocessing/simple_preprocessing.ipynb Applies the `momepy.remove_false_nodes` function to the network GeoDataFrame to correct topological errors by removing unnecessary intermediate nodes. ```python fixed = momepy.remove_false_nodes(df) ``` -------------------------------- ### Calculate Building Adjacency Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/weights/two.ipynb Calculates building adjacency by constructing two spatial graphs: a contiguity graph (rook's case) representing directly adjacent buildings and a neighborhood graph based on a distance band. The adjacency ratio is then computed using momepy's building_adjacency function. ```Python # contiguity_graph rook = graph.Graph.build_contiguity(buildings) # neighborhood_graph dist200 = graph.Graph.build_distance_band(buildings.centroid, 200) buildings["adjacency"] = momepy.building_adjacency( contiguity_graph=rook, neighborhood_graph=dist200 ) ``` -------------------------------- ### Plot Building Adjacency Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/weights/two.ipynb Visualizes the calculated building adjacency values on a map. The plot uses a natural breaks classification scheme to display the distribution of adjacency ratios across the buildings. ```Python ax = buildings.plot( column="adjacency", legend=True, scheme="naturalbreaks", k=10, figsize=(8, 8), ) ax.set_axis_off() ``` -------------------------------- ### Measure Local Simpson's Diversity with Momepy Source: https://github.com/pysal/momepy/blob/main/docs/index.rst Calculates the local Simpson's diversity index for a given dataset, likely related to urban morphology features. It utilizes the `momepy.simpson` function and requires a contiguity measure like `contiguity_k3` as input. ```python tessellation['area_simpson'] = momepy.simpson(tessellation.area, contiguity_k3) ``` -------------------------------- ### Convert Graph to GeoDataFrame (Preserving Index) Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/graph/convert.ipynb Converts a NetworkX graph back to a GeoDataFrame while preserving the original index and row order. This is achieved by setting `preserve_index=True` during conversion. ```python graph = momepy.gdf_to_nx(streets, preserve_index=True) edges = momepy.nx_to_gdf(graph, points=False) edges.head() ``` -------------------------------- ### Calculate and Set Node Degree Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/graph/convert.ipynb Calculates the degree for each node in a NetworkX graph and sets it as a node attribute. This is useful for analyzing node importance based on connectivity. ```python degree = dict(nx.degree(graph)) nx.set_node_attributes(graph, degree, "degree") ``` -------------------------------- ### Calculate Mean Interbuilding Distance Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/weights/two.ipynb Computes the mean interbuilding distance, considering contiguity relationships and a defined neighborhood distance. This involves building a contiguity graph for the tessellation and using it along with the previously defined neighborhood graph. ```Python queen_tess = graph.Graph.build_contiguity(tessellation, rook=False) buildings["mean_ib_dist"] = momepy.mean_interbuilding_distance( buildings, adjacency_graph=queen_tess, neighborhood_graph=dist200 ) ``` -------------------------------- ### Calculate Straightness Centrality Source: https://github.com/pysal/momepy/blob/main/README.md Computes the straightness centrality for nodes in a network graph. This metric quantifies how directly connected a node is to all other nodes in the network, useful for analyzing street network efficiency. ```Python G = momepy.straightness_centrality(G) ``` -------------------------------- ### Add Original Position Column Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/graph/convert.ipynb Adds a 'position' column to the original streets GeoDataFrame to track the row order, which is useful for preserving index during graph conversion. ```python streets["position"] = range(len(streets)) streets.head() ``` -------------------------------- ### Calculate Node Degree using Momepy Source: https://github.com/pysal/momepy/blob/main/docs/user_guide/graph/convert.ipynb Calculates the node degree directly using a momepy function and adds it as a 'degree' attribute to the graph nodes. This offers a convenient way to compute this common metric. ```python graph = momepy.node_degree(graph, name="degree") ``` -------------------------------- ### Calculate Simpson's Diversity of Area Source: https://github.com/pysal/momepy/blob/main/README.md Calculates the Simpson's diversity index for the area attribute of tessellation data, using a specified contiguity measure. This function is useful for quantifying the diversity of urban form characteristics. ```Python tessellation['area_simpson'] = momepy.simpson(tessellation.area, contiguity_k3) ``` -------------------------------- ### Calculate Straightness Centrality with Momepy Source: https://github.com/pysal/momepy/blob/main/docs/index.rst Computes the straightness centrality for nodes in a graph, typically representing a street network. This function is part of the momepy library and is applied to a networkX graph object `G`. ```python G = momepy.straightness_centrality(G) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.