Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
112 changes: 55 additions & 57 deletions crates/engine/src/cmd/workflows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,8 +126,9 @@ fn raster_of(s: &Session, name: &str) -> Result<Input, String> {
#[derive(Clone)]
pub(crate) struct Input {
held: std::sync::Arc<Raster>,
/// The layer's name and its file, for one read in place from a file on this computer.
file: Option<(String, String)>,
layer_name: String,
/// The local file, for a raster read in place.
file: Option<String>,
}

impl Input {
Expand All @@ -137,8 +138,8 @@ impl Input {
let rl = context.map().layer_by_name(name).and_then(|l| Some((l, l.raster.as_ref()?)));
let (l, rl) = rl.ok_or_else(|| format!("no raster layer '{name}'"))?;
let held = rl.data.clone().ok_or_else(|| format!("no raster layer '{name}'"))?;
let file = rl.path.clone().filter(|_| rl.tiled).map(|path| (l.name.clone(), path));
Ok(Input { held, file })
let file = rl.path.clone().filter(|_| rl.tiled);
Ok(Input { held, layer_name: l.name.clone(), file })
}

/// The raster the layer holds: for one read in place from a file, its overview, with the
Expand All @@ -150,7 +151,7 @@ impl Input {
/// The layer's name and its file, for a layer read in place from a file on this computer.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn file(&self) -> Option<(&str, &str)> {
self.file.as_ref().map(|(name, path)| (name.as_str(), path.as_str()))
self.file.as_deref().map(|path| (self.layer_name.as_str(), path))
}

/// The raster the work reads: within a run ([`reading_files`]), a layer read in place from a
Expand All @@ -159,11 +160,11 @@ impl Input {
/// any other layer, the raster the layer holds.
pub(crate) fn read(&self) -> Result<Read, String> {
#[cfg(not(target_arch = "wasm32"))]
if let Some((name, path)) = &self.file
if let Some((name, path)) = self.file()
&& RUN_READS.with(|r| r.borrow().is_some())
{
let kept = RUN_READS.with(|r| {
r.borrow().as_ref().and_then(|read| read.iter().find(|k| k.path.as_ref() == Some(path)).and_then(|k| k.kept.clone()))
r.borrow().as_ref().and_then(|read| read.iter().find(|k| k.path.as_deref() == Some(path)).and_then(|k| k.kept.clone()))
});
let (raster, count) = match kept {
Some(k) => k,
Expand All @@ -172,7 +173,7 @@ impl Input {
let note = super::gp::ReadNote::of(name, &raster);
RUN_READS.with(|r| {
if let Some(read) = r.borrow_mut().as_mut() {
read.push(RunRead { path: Some(path.clone()), kept: Some((raster.clone(), count.clone())), note });
read.push(RunRead { path: Some(path.to_owned()), kept: Some((raster.clone(), count.clone())), note });
}
});
(raster, count)
Expand Down Expand Up @@ -201,7 +202,7 @@ impl Input {
/// other layer, give [`Input::read`].
pub(crate) fn read_part(&self, part: rustgis_data::raster::Part, share: usize) -> Result<Read, String> {
#[cfg(not(target_arch = "wasm32"))]
if let Some((name, path)) = &self.file
if let Some((name, path)) = self.file()
&& RUN_READS.with(|r| r.borrow().is_some())
&& let Some((read, count)) = super::gp::read_tiled_part(name, path, part, share, &self.held)?
{
Expand Down Expand Up @@ -1789,7 +1790,7 @@ fn raster_function(s: &mut Session, p: &Value) -> CmdResult {
fn function_work(s: &Session, p: &Value) -> Result<Work, String> {
let src = raster_of(s, ps(p, "layer").ok_or("layer is required")?)?;
let target = resample_target(s, p)?;
let name = out_name(p, format!("{}_{}", src.held().name, ps(p, "function").unwrap_or("")))?;
let name = out_name(p, format!("{}_{}", src.layer_name, ps(p, "function").unwrap_or("")))?;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The output name now comes from the visible layer name here, but the same default is still built from the raster's internal name in other raster commands. After a rename, a DEM loaded from exportImage.tif still yields exportImage_… in them. Examples I checked by grep: index_work (imagery.rs:1667, format!("{}_{idx}", r.held().name)), and imagery.rs:197, 1311, 1551, 1731, 1854, 1886 and deeplearning.rs:307, 348. All read their input through Input::of, so the layer_name field would be available to them.

The PR body limits the fix to Visibility Analysis, raster functions and chains, but the title says "workflow outputs". Either extend the change to these, or say in the PR body why they stay as they are. The new test covers only the three commands in this diff.

Category: quality

let defaults = s.raster_defaults.clone();
let mut p = p.clone();
// Read here, on the command's thread, where an unreadable value is said (#1600); only a remap
Expand Down Expand Up @@ -1984,60 +1985,58 @@ fn function_chain_work(s: &Session, p: &Value) -> Result<Work, String> {
.enumerate()
.map(|(i, st)| resample_target(s, st).map_err(|e| format!("step {} ({}): {e}", i + 1, func(st))))
.collect::<Result<_, _>>()?;
let named = Some(out_name(p, String::new())?).filter(|n| !n.is_empty());
let names: Vec<_> = steps.iter().map(func).collect();
let out = out_name(p, format!("{}_{}", src.layer_name, names.join("_")))?;
let defaults = s.raster_defaults.clone();
// A file too large to read whole at its full size: a block at a time (#2865), with the cells
// around each that its steps over a cell's neighbours read, one each; a chain that can't be
// made so ([`super::in_blocks::chain_halo`]) reads the file as before.
#[cfg(not(target_arch = "wasm32"))]
if let Some(halo) = super::in_blocks::chain_halo(&steps) {
let names: Vec<String> = steps.iter().map(func).collect();
let out = named.clone().unwrap_or_else(|| format!("{}_{}", src.held().name, names.join("_")));
if let Some(blocks) = super::in_blocks::plan(s, &src, &out)? {
let last = steps.last().cloned().unwrap_or_default();
let shape = function_shape(&last);
return Ok(Box::new(move || {
let met = std::cell::RefCell::new(BlockRemaps::default());
let made = blocks.with_halo(halo).run_window(
|block, ground, core| {
let mut remaps = Remaps::default();
let mut cur: Option<Raster> = None;
for (i, st) in steps.iter().enumerate() {
let input = cur.as_ref().unwrap_or(block);
// Earlier outputs in the remaining halo feed later terrain steps.
let halo: usize = steps
.iter()
.skip(i + 1)
.filter_map(|st| ps(st, "function").and_then(super::in_blocks::function_halo))
.map(|v| v as usize)
.sum();
let kept = [
core[0].saturating_sub(halo),
core[1].saturating_sub(halo),
core[2].saturating_add(halo).min(input.width as usize),
core[3].saturating_add(halo).min(input.height as usize),
];
let pixels = apply_function(input, st, None, &mut remaps, Some(ground), Some((kept, halo > 0)))
.map_err(|e| format!("step {} ({}): {e}", i + 1, func(st)))?;
cur = Some(derive_function(input, &input.name, st, pixels)?);
}
met.borrow_mut().add(remaps);
let cur = cur.ok_or("the chain made no raster")?;
Ok(cur.bands.into_iter().next().map(|b| b.data).unwrap_or_default())
},
shape,
)?;
let made = also(made, met.into_inner().met().then());
Ok(if is_hillshade(&last) { hillshade_look(made, &defaults) } else { made })
}));
}
if let Some(halo) = super::in_blocks::chain_halo(&steps)
&& let Some(blocks) = super::in_blocks::plan(s, &src, &out)?
{
let last = steps.last().cloned().unwrap_or_default();
let shape = function_shape(&last);
return Ok(Box::new(move || {
let met = std::cell::RefCell::new(BlockRemaps::default());
let made = blocks.with_halo(halo).run_window(
|block, ground, core| {
let mut remaps = Remaps::default();
let mut cur: Option<Raster> = None;
for (i, st) in steps.iter().enumerate() {
let input = cur.as_ref().unwrap_or(block);
// Earlier outputs in the remaining halo feed later terrain steps.
let halo: usize = steps
.iter()
.skip(i + 1)
.filter_map(|st| ps(st, "function").and_then(super::in_blocks::function_halo))
.map(|v| v as usize)
.sum();
let kept = [
core[0].saturating_sub(halo),
core[1].saturating_sub(halo),
core[2].saturating_add(halo).min(input.width as usize),
core[3].saturating_add(halo).min(input.height as usize),
];
let pixels = apply_function(input, st, None, &mut remaps, Some(ground), Some((kept, halo > 0)))
.map_err(|e| format!("step {} ({}): {e}", i + 1, func(st)))?;
cur = Some(derive_function(input, &input.name, st, pixels)?);
}
met.borrow_mut().add(remaps);
let cur = cur.ok_or("the chain made no raster")?;
Ok(cur.bands.into_iter().next().map(|b| b.data).unwrap_or_default())
},
shape,
)?;
let made = also(made, met.into_inner().met().then());
Ok(if is_hillshade(&last) { hillshade_look(made, &defaults) } else { made })
}));
}
Ok(Box::new(move || {
let src = src.read()?;
// Each step's output, the next step's input; the first step reads the raster itself, not
// a copy of it.
let mut cur: Option<Raster> = None;
let mut names = Vec::new();
let mut remaps = Remaps::default();
for (i, (st, target)) in steps.iter().zip(&targets).enumerate() {
let f = func(st);
Expand All @@ -2048,10 +2047,9 @@ fn function_chain_work(s: &Session, p: &Value) -> Result<Work, String> {
// Only a resample takes another raster's grid; otherwise the grid is the current one.
let next = derive_function(target.as_deref().unwrap_or(input), &input.name, st, pixels)?;
cur = Some(next);
names.push(f);
}
let mut cur = cur.ok_or("the chain made no raster")?;
cur.name = named.unwrap_or_else(|| format!("{}_{}", cur.name, names.join("_")));
cur.name = out;
// A chain that ends in a hillshade is drawn as one.
let mut m = match steps.last() {
Some(last) if is_hillshade(last) => made_hillshade(cur, &defaults)?,
Expand Down Expand Up @@ -2154,8 +2152,8 @@ fn viewshed_work(s: &Session, p: &Value) -> Result<Work, String> {
}
Some(other) => return Err(format!("heights must be \"nearest\" or \"bilinear\", not {other}")),
};
let name = out_name(p, format!("{}_viewshed", dem.held().name))?;
let dem_name = dem.held().name.clone();
let name = out_name(p, format!("{}_viewshed", dem.layer_name))?;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The default name is built with format! and is not checked against the 200-character limit that out_name applies to a name the user gives (#1888). A layer name at that limit gives a default up to 209 characters long, since _viewshed adds 9. function_work and function_chain_work have the same pattern. This is probably harmless, because in_blocks shortens file stems, but it is inconsistent with the cap. I did not confirm whether renaming a layer enforces the same 200-character cap, so my confidence is low.

Category: quality

let dem_name = dem.layer_name.clone();
Ok(Box::new(move || {
let dem = dem.read()?;
let (cx, cy) = dem.cell_size_ground_m();
Expand Down
22 changes: 22 additions & 0 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20595,6 +20595,28 @@ fn remap_reports_empty_ranges_and_no_valid_cells() {
assert_eq!(said, ["Apart: no cell is scored by every criterion, so the result has no cells with values"]);
}

#[test]
fn raster_workflow_outputs_use_the_visible_layer_name() {
let mut s = world();
s.run("layer.addDataBytes", &json!({"fileName": "exportImage.tif", "data": dem_b64()})).unwrap();
s.run("layer.rename", &json!({"layer": "exportImage", "name": "MDT Bogotá 2025"})).unwrap();
for (command, mut p, expected) in [
("analysis.viewshed", json!({"lon": 10.0055, "lat": 45.0395}), "MDT Bogotá 2025_viewshed"),
("raster.function", json!({"function": "slope"}), "MDT Bogotá 2025_slope"),
("raster.functionChain", json!({"steps": [{"function": "slope"}, {"function": "aspect"}]}), "MDT Bogotá 2025_slope_aspect"),
] {
p["layer"] = json!("mdt Bogotá 2025");
let mut run = |params: &Value| {
let result = s.run(command, params).unwrap();
s.map().layer(result["layer"].as_u64().unwrap() as u32).unwrap().name.clone()
};
assert_eq!(run(&p), expected, "{command}");
let custom = format!("Custom {command}");
p["name"] = json!(custom);
assert_eq!(run(&p), custom, "{command}");
}
}

#[test]
fn analysis_workflows_models_scripts_and_raster_functions() {
let mut s = world();
Expand Down
Loading