achubaty / grainscape

Efficient Modelling of Landscape Connectivity, Habitat, and Protected Area Networks
https://alexchubaty.com/grainscape
19 stars 2 forks source link

Manually adding an attribute to nodes/vertices results in an error when exporting #71

Open Klemet opened 3 months ago

Klemet commented 3 months ago

Hello there ! Thank you for the amazing package and documentation, it's great 😄 !

I don't know if this is intended or not, but I've stumbled on what seems like an issue.

When one tries to add an attribute to the vertices of the graph (for example, after computing the betweenness of each vertex), the export function returns an error.

Here is a sample code :

## Load raster landscape
tiny <- raster::raster(system.file("extdata/tiny.asc", package = "grainscape"))
## Create a resistance surface from a raster using an is-becomes reclassification
tinyCost <- raster::reclassify(tiny, rcl = cbind(c(1, 2, 3, 4), c(1, 5, 10, 12)))
## Produce a patch-based MPG where patches are resistance features=1
tinyPatchMPG <- MPG(cost = tinyCost, patch = tinyCost == 1)

# Computes the betweenness
tiny_mpg_graph <- tinyPatchMPG$mpg
ig <- graph_from_adjacency_matrix(as_adjacency_matrix(tiny_mpg_graph), mode = "undirected")
betweenness_scores <- betweenness(ig)

V(tinyPatchMPG$mpg)$betweenness = betweenness_scores

## Export raster and vectors to a specified directory
exportPath <- tempdir()
export(tinyPatchMPG, dirname = "tiny_mpg", path = exportPath, vorBound = TRUE, overwrite = TRUE)

The error is the following :

Error in if (any(nchar(fld_names) > 10)) { : 
  missing value where TRUE/FALSE needed

It seems that the problem happens in the function that writes the shapefile, where the sf package tries to shorten the field names for the shapefile but seems to stumble onto a NULL object somewhere.

Again, I don't know if this is intended; but I would think that adding measures to the nodes during the script and then exporting everything could be desirable user-wise ? One could always export to shapefile first and edit the shapefiles manually, of course !

Anyway, I hope this helps !

achubaty commented 3 months ago

Thanks for this - I agree that catching this earlier and providing a meaningful message to the user is the way to go. I'll try to get to this as soon as I can.