geometrygisshapelytopologyalpha-shape

How can I fix Singular Matrix Warning when computing a concave hull with alphashape?


The actual warning printed is "WARNING:root:Singular matrix. Likely caused by all points lying in an N-1 space." This is a surprise to me, since my points clearly populate a 2D area and are not collinear, as shown in this screenshot from QGIS:

Lake with original points

I tried to drop duplicate points, since I read that could cause the warning, but the issue remains. My goal is to generate a concave hull that is not as concave as to strictly follow the zigzag pattern of my points, but for it to describe the outer concavities of the imaginary boundary.

This is my code right now:

# Read CSV Data
print("Parsing .csv file...", end=" ", flush=True)
filepath = f'output/{argv[1]}'
with open(filepath, "r") as archive:
    data = list(csv.reader(archive, delimiter=","))[1:]  # Skip header

lat = []
lon = []
z = []

for entry in data:
    lat.append(float(entry[9]))  # Keep raw latitude
    lon.append(float(entry[10])) # Keep raw longitude
    z.append(float(entry[1]) / 1000)  # Convert depth to meters

df = pd.DataFrame({'lon': lon, 'lat': lat, 'z': z})
df = df.drop_duplicates(subset=['lon', 'lat'], keep='first')
print("Done!")

print("Exporting points to .xyz file...", end=" ", flush=True)
with open(f"output/{name}.xyz", "w") as f: #export to .xyz
    f.write("LONGITUDE_(deg) LATITUDE_(deg) DEPTH_(m)\n")
    for lon, lat, z in zip(df['lon'], df['lat'], df['z']):
        f.write(f"{lon} {lat} {z}\n")
print("Done!")

print("Computing concave hull for fence boundary...", end=" ", flush=True)
points = np.column_stack((df['lon'], df['lat']))
alpha_opt = 0.01
concave_hull = alphashape.alphashape(points, alpha_opt)
hull_coords = np.array(concave_hull.exterior.coords)
hull_path = path.Path(hull_coords)
if isinstance(concave_hull, Polygon):
    print("Done!")
else:
    print("Something went wrong.")
    exit(1)

Solution

  • Apart from duplicate or near duplicate points, I found that large coordinate values can also lead to this warning. Try centering the coordinates in conjunction with dropping duplicate and near duplicate values. This might solve your problem.