Vector queries allow users to search and identify vector features based on their spatial and/or attribute data. This is useful when a user only wants to work with a limited dataset, based on specific vector attributes and features, or if multiple vector features need to be modified.
Display Vector Attributes with NumPy and Matplotlib
Note: Before running this sample, configure these variables and modules:
export_dir: the directory for resulting files to be exported toimport numpy as np
import matplotlib.pyplot as plt
A sample script that gathers all of the Arizona Biotic Communities from a shapefile and then iterates though the gathered communities and determines how many unique attributes each one has. This data is then formatted into a bar-graph using NumPy and Matplotlib and exported as a JPG.
import os
import globalmapper as gm
import numpy as np
import matplotlib.pyplot as plt
layer_path = "Z:/GM-20069/vector_attributes_to_numpy_array_sample_data/gfveg.shp"
export_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), "../misc/vector_attributes_to_numpy_array_output/")
os.makedirs(export_dir, exist_ok=True)
# A sample script that gathers all of the Arizona Biotic Communities from a shapefile and then iterates though the gathered
# communities and determines how many unique attributes each one has. This data is then formatted into a bar-graph using
# NumPy and Matplotlib and exported as a JPG.
# Closes all layers that may be open.
layers_are_open = gm.GetLoadedLayerList()
if layers_are_open:
arr_ptr, arr_size = layers_are_open
initial_layers = gm.GM_LayerHandle_array_frompointer(arr_ptr)
for i in range(arr_size):
gm.CloseLayer(initial_layers[i])
err_LoadLayerList, arr_ptr, arr_size = gm.LoadLayerList(
layer_path, gm.GM_LoadFlags_UseDefaultLoadOpts
)
layer_arr = gm.GM_LayerHandle_array_frompointer(arr_ptr)
### START SAMPLE
i = 0
feature = gm.GetAreaFeature(layer_arr[0], i)
# Will hold attributes of with value 'COMMUNITY' as python list
az_communities = []
# Iterates over area features
while feature:
# Converts from C++ pointer to an array
attr_array = gm.GM_AttrValue_array_frompointer(feature.mFeatureInfo.mAttrList)
# Converts array to a python list
attribute_values = gm.carray_to_list(attr_array, feature.mFeatureInfo.mNumAttrs)
# Iterates through python list of attribute names and attribute values
for attribute in attribute_values:
attr_name = attribute.mName
attr_val = attribute.mVal
# Places all attributes with name 'COMMUNITY' into a list
if attr_name == "COMMUNITY":
az_communities.append(attr_val)
# Frees deep copies from memory
# Without this step the script causes the program to freeze
gm.FreeAreaFeature(feature)
i += 1
feature = gm.GetAreaFeature(layer_arr[0], i)
# Example of using numpy array to display data
# az_com_array converts python list into a numpy arrary
az_com_array = np.array(az_communities)
# Converts characters in az_com_array to title case for stylistic purposes
az_com_title = np.char.title(az_com_array)
# Counts each unique attribute within attribute name "COMMUNITY"
az_coms, az_com_count = np.unique(az_com_title, return_counts=True)
# Uses Matplotlib to create a bar graph of Arizona Biotic Communities
fig, ax = plt.subplots()
fig.set_figheight(7)
fig.set_figwidth(9)
x = az_coms
y = az_com_count
ax.bar(x, y, edgecolor="white")
ax.set_ylabel("Total Number of Arizona Biotic Communities")
ax.set_title("Count of Arizona Biotic Communities")
plt.xticks(x, rotation="vertical", fontsize=8, wrap=True)
plt.savefig(export_dir + "arizona_biotic_communities.jpg")
### END SAMPLE
assert (
gm.GM_Error_None == err_LoadLayerList
), f"LoadLayerList: Expected {gm.GM_Error_None}, got {err_LoadLayerList}"
assert os.path.isdir(export_dir), f"Error creating the export directory: {export_dir}"
assert os.path.exists(layer_path), f"Sample data doesn't exist: {layer_path}"
# Expected path for file export
exported_filepath = os.path.join(export_dir, "arizona_biotic_communities.jpg")
# Assert that the final expected output file exists and is not empty
assert os.path.exists(
exported_filepath
), f"Expected output file does not exist: {exported_filepath}"
assert (
os.path.getsize(exported_filepath) > 0
), f"Exported file is empty: {exported_filepath}"
# Check variable values
# 495 area features existed in the sample when first created
assert i == 495, "Incorrect value for i"
Edit Features Based on Attribute
This script iterates through all of the area features in a shapefile. It checks for names of vector areas with a specific attribute value (GREAT BASIN CONIFER WOODLAND) and display name (COMMUNITY). It changes the area’s classification to wood and adds a label to that area.
import os
import globalmapper as gm
layer_data = "Z:/GM-20069/edit_vector_features_by_attribute_sample_data/gfveg.shp"
# This script iterates through all of the area features in a shapefile. It checks for names of vector areas with a specific
# attribute value (GREAT BASIN CONIFER WOODLAND) and display name (COMMUNITY). It changes the area's classification to wood
# and adds a label to that area.
# Closes all layers that may be open.
layers_are_open = gm.GetLoadedLayerList()
if layers_are_open:
arr_ptr, arr_size = layers_are_open
initial_layers = gm.GM_LayerHandle_array_frompointer(arr_ptr)
for i in range(arr_size):
gm.CloseLayer(initial_layers[i])
err_LoadLayerList, arr_ptr, arr_size = gm.LoadLayerList(
layer_data, gm.GM_LoadFlags_UseDefaultLoadOpts
)
layer_arr = gm.GM_LayerHandle_array_frompointer(arr_ptr)
### START SAMPLE
i = 0
modified_ct = 0
feature = gm.GetAreaFeature(layer_arr[0], i)
# Iterates over area features
while feature:
# Converts from C++ pointer to an array
attr_array = gm.GM_AttrValue_array_frompointer(feature.mFeatureInfo.mAttrList)
# Converts array to a python list
attribute_values = gm.carray_to_list(attr_array, feature.mFeatureInfo.mNumAttrs)
# Iterates through python list of attribute names and attribute values
for attribute in attribute_values:
attr_name = attribute.mName
attr_val = attribute.mVal
# If conditions are met, area feature is assigned to feature class AFC_WOODS
if attr_name == "COMMUNITY" and attr_val == "GREAT BASIN CONIFER WOODLAND":
err_SetFeatureClass = gm.SetFeatureClass(
layer_arr[0], gm.GM_FeatureClass_Area, i, gm.AFC_WOODS
)
modified_ct += 1
# If conditions are met, area feature is given a label
if attr_name == "COMMUNITY" and attr_val == "GREAT BASIN CONIFER WOODLAND":
err_SetFeatureLabel = gm.SetFeatureLabel(
layer_arr[0],
gm.GM_FeatureClass_Area,
i,
"Great Basin Conifer Woodland",
)
# Frees deep copies from memory
# Without this step the script may freeze
gm.FreeAreaFeature(feature)
i += 1
feature = gm.GetAreaFeature(layer_arr[0], i)
# Displays the number of area features that were set to the Feature Class "Area Woods".
print("Set", modified_ct, "area features to the type WOODS")
### END SAMPLE
assert (
gm.GM_Error_None == err_LoadLayerList
), f"LoadLayerList: Expected {gm.GM_Error_None}, got {err_LoadLayerList}"
assert (
gm.GM_Error_None == err_SetFeatureClass
), f"SetFeatureClass: Expected {gm.GM_Error_None}, got {err_SetFeatureClass}"
assert (
gm.GM_Error_None == err_SetFeatureLabel
), f"SetFeatureLabel: Expected {gm.GM_Error_None}, got {err_SetFeatureLabel}"
# The original amount of features modified when this sample was created
if modified_ct != 71:
assert (
False
), f"Expected 71 area features to be modified, but {modified_ct} were instead"
assert os.path.exists(layer_data), f"Sample data doesn't exist: {layer_data}"