From 66493fdc665a01834dae13f9a01dcca919c9ddb9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 11:31:03 +0100 Subject: [PATCH 1/3] Prepare columnar node edits for growth and child-preserving removal --- docs/src/api.md | 17 +++ src/MultiScaleTreeGraph.jl | 3 +- src/compute_MTG/delete_nodes.jl | 81 ++++++++--- src/compute_MTG/node_funs.jl | 48 +++++-- src/compute_MTG/prepared_node_edits.jl | 52 +++++++ src/types/Attributes.jl | 183 ++++++++++++++++--------- src/types/Node.jl | 23 +++- test/runtests.jl | 1 + test/test-prepared-node-edits.jl | 28 ++++ 9 files changed, 336 insertions(+), 100 deletions(-) create mode 100644 src/compute_MTG/prepared_node_edits.jl create mode 100644 test/test-prepared-node-edits.jl diff --git a/docs/src/api.md b/docs/src/api.md index f6bbaa8..74b6610 100644 --- a/docs/src/api.md +++ b/docs/src/api.md @@ -15,3 +15,20 @@ Notable attribute APIs: ```@autodocs Modules = [MultiScaleTreeGraph] ``` + +## Repeated edits on a growing tree + +Prepare the tree once, then use the same plan for each birth. An organ can +start with just its place in the topology. + +```julia +plant = Node(1, NodeMTG(:/, :Plant, 1, 1), (;)) +plan = prepare_node_edits(plant) +leaf = addchild!(plan, plant, 2, NodeMTG(:+, :Leaf, 1, 2)) +delete_node!(plan, leaf) +``` + +The optional final named tuple of `addchild!` supplies **tree attributes**. +In a coupled simulation, variables held by the simulation can stay in its +own status. Removing a node promotes its children according to the ordinary +`delete_node!` rules. It only changes the tree. diff --git a/src/MultiScaleTreeGraph.jl b/src/MultiScaleTreeGraph.jl index a6660f0..2113338 100644 --- a/src/MultiScaleTreeGraph.jl +++ b/src/MultiScaleTreeGraph.jl @@ -39,6 +39,7 @@ include("compute_MTG/columnarize.jl") include("compute_MTG/transform.jl") include("compute_MTG/select.jl") include("compute_MTG/delete_nodes.jl") +include("compute_MTG/prepared_node_edits.jl") include("compute_MTG/prune.jl") include("compute_MTG/filter/filter-funs.jl") include("compute_MTG/summary.jl") @@ -56,7 +57,7 @@ export isleaf export isroot export children, lastchild export reparent!, rechildren! -export addchild! +export prepare_node_edits, addchild! export traverse! export traverse export transform!, transform, select!, select diff --git a/src/compute_MTG/delete_nodes.jl b/src/compute_MTG/delete_nodes.jl index a248ae9..47ce4fc 100644 --- a/src/compute_MTG/delete_nodes.jl +++ b/src/compute_MTG/delete_nodes.jl @@ -118,21 +118,20 @@ link shouldn't be modified, use the `link` function instead. The function returns the parent node (or the new root if the node is a root) """ -function delete_node!(node::Node{N,A}; child_link_fun=new_child_link) where {N<:AbstractNodeMTG,A} +delete_node!(node::Node; child_link_fun=new_child_link) = _delete_node!(node, child_link_fun, nothing) + +function _delete_node!(node::Node, child_link_fun, column_schema) + _check_deleted_row(column_schema, node) if isroot(node) if length(children(node)) == 1 # If it has only one child, make it the new root: chnode = children(node)[1] - link!(chnode, child_link_fun(chnode)) + inherited_link = child_link_fun(chnode) + values = _root_attributes_to_inherit(chnode, node, column_schema) + link!(chnode, inherited_link) reparent!(chnode, nothing) # Add to the new root the mandatory root attributes: - root_attrs = Dict( - :symbols => node[:symbols], - :scales => node[:scales], - :description => node[:description] - ) - - append!(chnode, root_attrs) + _inherit_root_attributes!(chnode, node, column_schema, values) node_return = chnode else @@ -145,27 +144,65 @@ function delete_node!(node::Node{N,A}; child_link_fun=new_child_link) where {N<: # We re-parent the children to the parent of the node. for chnode in copy(children(node)) # Updating the link of the children: - link!(chnode, child_link_fun(chnode)) - addchild!(parent_node, chnode; force=true) + _reparent!(chnode, parent_node, column_schema, Some(child_link_fun(chnode))) end end - # Delete the node as child of his parent: - parent_children = children(parent_node) - idx = _child_index_by_id(parent_children, node_id(node)) - idx === nothing || deleteat!(parent_children, idx) - idx === nothing || _mark_structure_mutation!(parent_node) - node_return = parent_node + return _detach_deleted_node!(parent_node, node, column_schema) + end + _isolate_deleted_node!(node, column_schema) + return node_return +end + +_check_deleted_row(::Nothing, node) = nothing +function _check_deleted_row(schema::_ColumnRowSchema, node) + store, bid, _ = _bucket_row(getfield(node_attributes(node), :ref)) + _check_row_columns(schema, store.buckets[bid]) +end + +_root_attributes_to_inherit(child, node, ::Nothing) = nothing +function _inherit_root_attributes!(child, node, ::Nothing, values) + append!(child, Dict(:symbols => node[:symbols], :scales => node[:scales], + :description => node[:description])) +end + +function _root_attributes_to_inherit(child, node, schema::_ColumnRowSchema{C,V}) where {C,V} + attrs = node_attributes(node) + source, bid, row = _bucket_row(getfield(attrs, :ref)) + bucket = source.buckets[bid] + values = Dict{Symbol,V}() + sizehint!(values, 3) + for key in (:symbols, :scales, :description) + idx = get(bucket.col_index, key, 0) + values[key] = iszero(idx) ? nothing : + _get_column_value(_row_column(schema, _column(bucket, idx)), row, nothing) end + dest = _store_for_node_attrs(node_attributes(child)) + _check_row_writes(schema, dest, symbol(child), values) + return values +end + +function _inherit_root_attributes!(child, node, schema::_ColumnRowSchema, values) + dest, dbid, drow = _bucket_row(getfield(node_attributes(child), :ref)) + for (key, value) in values + _set_value_bound!(dest.buckets[dbid], drow, key, value, schema) + end + return child +end - # Clean the old deleted node (isolate it, no parent, no children): +function _detach_deleted_node!(parent_node, node, schema) + _detach_child!(parent_node, node) + _isolate_deleted_node!(node, schema) + return parent_node +end + +function _isolate_deleted_node!(node::Node{N,A}, schema) where {N,A} _discard_traversal_cache!(node) attrs = node_attributes(node) - attrs isa ColumnarAttrs && remove_columnar_node!(attrs) + attrs isa ColumnarAttrs && remove_columnar_node!(attrs, schema) reparent!(node, nothing) - rechildren!(node, Node{N,A}[]) - - return node_return + _replace_children!(node, ()) + return nothing end """ diff --git a/src/compute_MTG/node_funs.jl b/src/compute_MTG/node_funs.jl index 850bce8..cbfda74 100644 --- a/src/compute_MTG/node_funs.jl +++ b/src/compute_MTG/node_funs.jl @@ -107,15 +107,36 @@ function _subtree_has_node_id_conflict(node::Node, store::MTGAttributeStore) return false end -function _merge_columnar_subtree_into_store!(node::Node, target_store::MTGAttributeStore) +function _columnar_row_snapshot(attrs::ColumnarAttrs, schema) + V = _row_value_type(schema) + snapshot = Dict{Symbol,V}() + sizehint!(snapshot, _row_length(attrs, schema)) + ref = getfield(attrs, :ref) + if !_isbound(attrs) + for (key, value) in pairs(_staged_attributes(attrs)) + snapshot[key] = value::V + end + else + source, source_bid, source_row = _bucket_row(ref) + for raw in source.buckets[source_bid].columns + column = _row_column(schema, raw) + if _row_has_value(column, source_row) + snapshot[column.name] = column.data[source_row]::V + end + end + end + return snapshot +end + +function _merge_columnar_subtree_into_store!(node::Node, target_store::MTGAttributeStore, schema=nothing) attrs = node_attributes(node) attrs isa ColumnarAttrs || return false source_store = _store_for_node_attrs(attrs) source_node_id = attrs.ref.node_id - snapshot = Dict{Symbol,Any}(pairs(attrs)) - _add_node_with_attrs!(target_store, node_id(node), symbol(node), snapshot) + snapshot = _columnar_row_snapshot(attrs, schema) + _add_node_with_attrs!(target_store, node_id(node), symbol(node), snapshot, schema) if source_store !== nothing && source_store !== target_store - _remove_node!(source_store, source_node_id) + _remove_node!(source_store, source_node_id, schema) end attrs.ref.store = target_store attrs.ref.node_id = node_id(node) @@ -126,27 +147,29 @@ function _merge_columnar_subtree_into_store!(node::Node, target_store::MTGAttrib _register_traversal_cache!(target_store, node) end for ch in children(node) - _merge_columnar_subtree_into_store!(ch, target_store) || return false + _merge_columnar_subtree_into_store!(ch, target_store, schema) || return false end return true end -function _try_merge_subtree_store!(child::Node, parent_store::MTGAttributeStore, child_store::MTGAttributeStore) +function _try_merge_subtree_store!(child::Node, parent_store::MTGAttributeStore, child_store::MTGAttributeStore, schema=nothing) parent_store === child_store && return true _subtree_has_node_id_conflict(child, parent_store) && return false - return _merge_columnar_subtree_into_store!(child, parent_store) + return _merge_columnar_subtree_into_store!(child, parent_store, schema) end function _validate_columnar_attach!( p::Node, child::Node, reserved_ids::Union{Nothing,Set{Int}}=nothing, + schema=nothing, ) p_store = _columnar_store_or_nothing(p) c_store = _columnar_store_or_nothing(child) if p_store !== nothing && c_store !== nothing && p_store !== c_store reserved_ids === nothing && (reserved_ids = Set{Int}()) subtree_ids = Set{Int}() + pending = isnothing(schema) ? nothing : Dict{Tuple{Symbol,Symbol},Type}() stack = typeof(child)[child] while !isempty(stack) current = pop!(stack) @@ -158,6 +181,13 @@ function _validate_columnar_attach!( "cannot attach subtree rooted at node $(node_id(child)): node id $nid is duplicated or already present in the destination attribute store", )) end + if !isnothing(schema) + attrs = node_attributes(current) + source, bid, _ = _bucket_row(getfield(attrs, :ref)) + _check_row_columns(schema, source.buckets[bid]) + _check_row_writes(schema, p_store, symbol(current), + _columnar_row_snapshot(attrs, schema), pending) + end push!(subtree_ids, nid) current_children = children(current) @inbounds for child_index in reverse(eachindex(current_children)) @@ -169,11 +199,11 @@ function _validate_columnar_attach!( return reserved_ids end -@inline function _maybe_recolumnarize_after_attach!(p::Node, child::Node) +@inline function _maybe_recolumnarize_after_attach!(p::Node, child::Node, schema=nothing) p_store = _columnar_store_or_nothing(p) c_store = _columnar_store_or_nothing(child) if p_store !== nothing && c_store !== nothing && p_store !== c_store - _try_merge_subtree_store!(child, p_store, c_store) || error( + _try_merge_subtree_store!(child, p_store, c_store, schema) || error( "failed to merge the attached subtree into its destination attribute store", ) end diff --git a/src/compute_MTG/prepared_node_edits.jl b/src/compute_MTG/prepared_node_edits.jl new file mode 100644 index 0000000..05a9b99 --- /dev/null +++ b/src/compute_MTG/prepared_node_edits.jl @@ -0,0 +1,52 @@ +struct PreparedNodeEdits{S} + store::MTGAttributeStore + schema::S +end + +""" + prepare_node_edits(node) + +Prepare repeated edits on the columnar tree containing `node`. The returned +plan borrows the tree's attribute store and records its column types. +Use `addchild!(plan, parent, id, encoding[, attributes])` to insert a child, +`attribute(plan, node, key[, default])` to read a tree attribute, and +`delete_node!(plan, node)` to remove a node using the usual child-promotion rules. + +An empty attribute tuple is the default. New nodes and attribute names may +appear at any time. Each resulting column type must belong to the prepared +family. To introduce another type, declare its column with [`add_column!`](@ref) +and prepare a fresh plan. The plan is specific to this store. +""" +function prepare_node_edits(node::Node{M,ColumnarAttrs}) where {M} + store = _store_for_node_attrs(node_attributes(node)) + isnothing(store) && throw(ArgumentError("Prepare edits on an attached node.")) + return PreparedNodeEdits(store, _column_row_schema(store)) +end + +function _check_edit_store(plan::PreparedNodeEdits, node) + _store_for_node_attrs(node_attributes(node)) === plan.store || + throw(ArgumentError("The node does not belong to the prepared tree.")) + return nothing +end + +function addchild!(plan::PreparedNodeEdits, parent::Node{M,ColumnarAttrs}, + id::Int, encoding::M, attributes::NamedTuple=(;)) where {M<:AbstractNodeMTG} + _check_edit_store(plan, parent) + return _node_with_columnar_attrs(id, parent, encoding, ColumnarAttrs(), attributes, plan.schema) +end + +function delete_node!(plan::PreparedNodeEdits, node::Node{M,ColumnarAttrs}) where {M} + _check_edit_store(plan, node) + return _delete_node!(node, new_child_link, plan.schema) +end + +function attribute(plan::PreparedNodeEdits, node::Node{M,ColumnarAttrs}, key::Symbol, default=nothing) where {M} + _check_edit_store(plan, node) + store, bid, row = _bucket_row(getfield(node_attributes(node), :ref)) + bucket = store.buckets[bid] + slot = get(bucket.col_index, key, 0) + iszero(slot) && return default + column = _column(bucket, slot) + _check_row_column_type(plan.schema, typeof(column)) + return _get_column_value(_row_column(plan.schema, column), row, default) +end diff --git a/src/types/Attributes.jl b/src/types/Attributes.jl index f8823cf..7b6eda1 100644 --- a/src/types/Attributes.jl +++ b/src/types/Attributes.jl @@ -237,23 +237,27 @@ end ColumnarAttrs() = ColumnarAttrs(NodeAttrRef(nothing, 0), nothing) function ColumnarAttrs(d::AbstractDict) isempty(d) && return ColumnarAttrs() - staged = Dict{Symbol,Any}() + return ColumnarAttrs(NodeAttrRef(nothing, 0), _stage_attributes(d, Any)) +end + +function _stage_attributes(d::AbstractDict, ::Type{V}) where {V} + staged = Dict{Symbol,V}() for (k, v) in d - staged[Symbol(k)] = v + staged[Symbol(k)] = v::V end - ColumnarAttrs(NodeAttrRef(nothing, 0), staged) + return staged end # Unbound empty attributes need no mutable staging dictionary. @inline _staged_attributes(attrs::ColumnarAttrs) = isnothing(attrs.staged) ? NamedTuple() : attrs.staged -@inline _isbound(attrs::ColumnarAttrs) = attrs.ref.store !== nothing && attrs.ref.node_id > 0 +@inline _isbound(attrs::ColumnarAttrs) = getfield(attrs, :ref).store !== nothing && getfield(attrs, :ref).node_id > 0 function _assert_columnar_attrs_unbound(attrs::ColumnarAttrs) _isbound(attrs) || return nothing throw(ArgumentError( - "ColumnarAttrs is already bound to node id $(attrs.ref.node_id); " * + "ColumnarAttrs is already bound to node id $(string(getfield(attrs, :ref).node_id)); " * "pass `copy(attrs)` to a Node constructor to copy its current values.", )) end @@ -264,9 +268,9 @@ end end function _assert_node_id_available(store::MTGAttributeStore, node_id::Int) - node_id > 0 || throw(ArgumentError("node id must be positive; got $(node_id)")) + node_id > 0 || throw(ArgumentError("node id must be positive; got $(string(node_id))")) _node_id_is_active(store, node_id) && throw(ArgumentError( - "node id $(node_id) is already registered in the destination attribute store", + "node id $(string(node_id)) is already registered in the destination attribute store", )) return nothing end @@ -302,15 +306,14 @@ end bucket.columns[col_idx] end -function _widen_column!(bucket::SymbolBucket, col_idx::Int, ::Type{NewT}) where {NewT} - old_col = bucket.columns[col_idx] +function _widen_column!(bucket::SymbolBucket, col_idx::Int, old_col::Column, ::Type{NewT}) where {NewT} old_data = old_col.data new_data = Vector{NewT}(undef, length(old_data)) @inbounds for i in eachindex(old_data) new_data[i] = old_data[i] end new_default = convert(NewT, old_col.default) - bucket.columns[col_idx] = Column{NewT}( + column = Column{NewT}( old_col.name, new_data, copy(old_col.present), @@ -318,18 +321,16 @@ function _widen_column!(bucket::SymbolBucket, col_idx::Int, ::Type{NewT}) where new_default, old_col.default_present, ) + bucket.columns[col_idx] = column bucket.col_types[col_idx] = NewT - return bucket.columns[col_idx] + return column end -function _ensure_column_type!(bucket::SymbolBucket, col_idx::Int, value) - T = bucket.col_types[col_idx] - value_T = typeof(value) - if value_T <: T - return _column(bucket, col_idx) - end - NewT = Union{T,value_T} - return _widen_column!(bucket, col_idx, NewT) +function _ensure_column_type!(bucket::SymbolBucket, col_idx::Int, column::Column{T}, value::V, schema) where {T,V} + value isa T && return column + NewT = Union{T,V} + _check_row_column_type(schema, Column{NewT}) + return _widen_column!(bucket, col_idx, column, NewT) end function _add_column_internal!( @@ -383,19 +384,21 @@ end return nothing end -function _set_value!(bucket::SymbolBucket, row::Int, key::Symbol, value) +function _set_value!(bucket::SymbolBucket, row::Int, key::Symbol, value::V, schema=nothing) where {V} col_idx = get(bucket.col_index, key, 0) if col_idx == 0 - if value === nothing - _add_nullable_column_internal!(bucket, key, Nothing) - else - _add_nullable_column_internal!(bucket, key, typeof(value)) - end + _check_row_column_type(schema, Column{Union{Nothing,V}}) + _add_nullable_column_internal!(bucket, key, V) col_idx = bucket.col_index[key] end - col = _ensure_column_type!(bucket, col_idx, value) - col.data[row] = value + col = _ensure_column_type!(bucket, col_idx, _row_column(schema, _column(bucket, col_idx)), value, schema) + _write_present_value!(col, row, value) + return value +end + +@inline function _write_present_value!(col::Column{T}, row, value) where {T} + col.data[row] = value::T _mark_row_present!(col, row) return value end @@ -426,11 +429,11 @@ function _bucket_row(ref::NodeAttrRef) store = ref.store store === nothing && error("Columnar attributes are not bound to a store.") node_id = ref.node_id - node_id <= 0 && error("Invalid node id for columnar attributes: $(node_id)") - node_id > length(store.node_bucket) && error("Node id $(node_id) is outside of store bounds.") + node_id <= 0 && error("Invalid node id for columnar attributes: $(string(node_id))") + node_id > length(store.node_bucket) && error("Node id $(string(node_id)) is outside of store bounds.") bid = store.node_bucket[node_id] row = store.node_row[node_id] - bid == 0 && error("Node id $(node_id) is no longer attached to the attribute store.") + bid == 0 && error("Node id $(string(node_id)) is no longer attached to the attribute store.") return store, bid, row end @@ -442,19 +445,48 @@ end return store, bid, row end -function _add_node_row!(store::MTGAttributeStore, node_id::Int, symbol::Symbol) +# Prepared tree operations admit the concrete column types present during preparation. +# Row widths, attribute names and the number of nodes can still change. +struct _ColumnRowSchema{C,V} end + +function _column_row_schema(store::MTGAttributeStore) + types = unique(typeof(column) for bucket in store.buckets for column in bucket.columns) + values = [eltype(fieldtype(T, :data)) for T in types] + return _ColumnRowSchema{Union{Column{Nothing},types...},Union{Nothing,values...}}() +end + +_check_row_column_type(::Nothing, type) = nothing +function _check_row_column_type(::_ColumnRowSchema{C}, type) where {C} + type <: C || throw(ArgumentError("The attribute column type is outside the prepared tree schema.")) + return nothing +end + +_row_value_type(::Nothing) = Any +_row_value_type(::_ColumnRowSchema{C,V}) where {C,V} = V + +_check_row_columns(::Nothing, bucket) = nothing +function _check_row_columns(::_ColumnRowSchema{C}, bucket) where {C} + all(column -> column isa C, bucket.columns) && return nothing + throw(ArgumentError("The attribute column type is outside the prepared tree schema.")) +end + +_row_column(::Nothing, column) = column +_row_column(::_ColumnRowSchema{C}, column) where {C} = column::C + +function _add_node_row!(store::MTGAttributeStore, node_id::Int, symbol::Symbol, schema=nothing) _assert_node_id_available(store, node_id) - _mark_subtree_index_mutation!(store) - _ensure_node_capacity!(store, node_id) bid = _get_or_create_bucket!(store, symbol) bucket = store.buckets[bid] + _check_row_columns(schema, bucket) + _mark_subtree_index_mutation!(store) + _ensure_node_capacity!(store, node_id) row = length(bucket.row_to_node) + 1 push!(bucket.row_to_node, node_id) bucket.node_to_row[node_id] = row @inbounds for i in eachindex(bucket.columns) - _append_default_row!(bucket.columns[i]) + _append_default_row!(_row_column(schema, bucket.columns[i])) end store.node_bucket[node_id] = bid @@ -464,39 +496,65 @@ function _add_node_row!(store::MTGAttributeStore, node_id::Int, symbol::Symbol) return bucket, row end -function _add_node_with_attrs!(store::MTGAttributeStore, node_id::Int, symbol::Symbol, attrs::AbstractDict) - bucket, row = _add_node_row!(store, node_id, symbol) +function _add_node_with_attrs!(store::MTGAttributeStore, node_id::Int, symbol::Symbol, ::NamedTuple{()}, schema=nothing) + _add_node_row!(store, node_id, symbol, schema) + return nothing +end + +# The open store may widen columns freely. A bounded operation must admit all +# prospective types before it publishes its row or detaches a source subtree. +_check_row_writes(::Nothing, store, symbol, attrs, pending=nothing) = nothing +function _check_row_writes(schema::_ColumnRowSchema, store, symbol, attrs, pending=nothing) + bid = get(store.symbol_to_bucket, symbol, 0) + bucket = iszero(bid) ? nothing : store.buckets[bid] + isnothing(bucket) || _check_row_columns(schema, bucket) + for (name, value) in pairs(attrs) + key = _normalize_attr_key(name) + index = isnothing(bucket) ? 0 : get(bucket.col_index, key, 0) + previous = iszero(index) ? Nothing : bucket.col_types[index]::Type + if !isnothing(pending) + previous = get(pending, (symbol, key), previous) + end + next = Union{previous,typeof(value)} + _check_row_column_type(schema, Column{next}) + isnothing(pending) || (pending[(symbol, key)] = next) + end + return nothing +end + +function _add_node_with_attrs!(store::MTGAttributeStore, node_id::Int, symbol::Symbol, attrs::AbstractDict, schema=nothing) + _check_row_writes(schema, store, symbol, attrs) + bucket, row = _add_node_row!(store, node_id, symbol, schema) for (k, v) in attrs - _set_value_bound!(bucket, row, _normalize_attr_key(k), v) + _set_value_bound!(bucket, row, _normalize_attr_key(k), v, schema) end return nothing end -@inline _set_namedtuple_attrs!(bucket::SymbolBucket, row::Int, ::Tuple{}, ::Tuple{}) = nothing +@inline _set_namedtuple_attrs!(bucket::SymbolBucket, row::Int, ::Tuple{}, ::Tuple{}, schema=nothing) = nothing -@inline function _set_namedtuple_attrs!(bucket::SymbolBucket, row::Int, names::Tuple, values::Tuple) - _set_value_bound!(bucket, row, first(names), first(values)) - _set_namedtuple_attrs!(bucket, row, Base.tail(names), Base.tail(values)) +@inline function _set_namedtuple_attrs!(bucket::SymbolBucket, row::Int, names::Tuple, values::Tuple, schema=nothing) + _set_value_bound!(bucket, row, first(names), first(values), schema) + _set_namedtuple_attrs!(bucket, row, Base.tail(names), Base.tail(values), schema) return nothing end -function _add_node_with_attrs!(store::MTGAttributeStore, node_id::Int, symbol::Symbol, attrs::NamedTuple) - if isempty(attrs) - _add_node_row!(store, node_id, symbol) - return nothing - end +function _add_node_with_attrs!(store::MTGAttributeStore, node_id::Int, symbol::Symbol, attrs::NamedTuple, schema=nothing) bid = get(store.symbol_to_bucket, symbol, 0) if bid == 0 || !all(key -> haskey(store.buckets[bid].col_index, key), keys(attrs)) # Keep the existing schema insertion order when a new key appears. Once # the schema exists, repeated organ creation needs neither filled Dict. - staged = ColumnarAttrs(Dict{Symbol,Any}(pairs(attrs))).staged - return _add_node_with_attrs!(store, node_id, symbol, staged) + V = _row_value_type(schema) + _check_row_writes(schema, store, symbol, attrs) + staged = _stage_attributes(Dict{Symbol,V}(pairs(attrs)), V) + return _add_node_with_attrs!(store, node_id, symbol, staged, schema) end - bucket, row = _add_node_row!(store, node_id, symbol) - _set_namedtuple_attrs!(bucket, row, keys(attrs), values(attrs)) + _check_row_writes(schema, store, symbol, attrs) + bucket, row = _add_node_row!(store, node_id, symbol, schema) + _set_namedtuple_attrs!(bucket, row, keys(attrs), values(attrs), schema) return nothing end @@ -514,13 +572,14 @@ end return nothing end -function _remove_node!(store::MTGAttributeStore, node_id::Int) +function _remove_node!(store::MTGAttributeStore, node_id::Int, schema=nothing) node_id > length(store.node_bucket) && return nothing bid = store.node_bucket[node_id] bid == 0 && return nothing + bucket = store.buckets[bid] + _check_row_columns(schema, bucket) _mark_subtree_index_mutation!(store) - bucket = store.buckets[bid] row = bucket.node_to_row[node_id] last_row = length(bucket.row_to_node) moved_node = 0 @@ -536,7 +595,7 @@ function _remove_node!(store::MTGAttributeStore, node_id::Int) @inbounds for i in eachindex(bucket.columns) # Columns have different element types. Dispatch once for the complete # row operation instead of accessing each field through `Any`. - _remove_column_row!(bucket.columns[i], row, last_row) + _remove_column_row!(_row_column(schema, bucket.columns[i]), row, last_row) end if moved_node != 0 @@ -687,22 +746,23 @@ function bind_columnar_child!( node_id::Int, symbol::Symbol, values=_staged_attributes(child_attrs), + schema=nothing, ) _assert_columnar_attrs_unbound(child_attrs) store = _store_for_node_attrs(parent_attrs) store === nothing && error("Parent node is not attached to a columnar attribute store.") _assert_node_id_available(store, node_id) - _add_node_with_attrs!(store, node_id, symbol, values) + _add_node_with_attrs!(store, node_id, symbol, values, schema) child_attrs.ref.store = store child_attrs.ref.node_id = node_id child_attrs.staged = nothing return child_attrs end -function remove_columnar_node!(attrs::ColumnarAttrs) +function remove_columnar_node!(attrs::ColumnarAttrs, schema=nothing) store = _store_for_node_attrs(attrs) store === nothing && return nothing - _remove_node!(store, attrs.ref.node_id) + _remove_node!(store, getfield(attrs, :ref).node_id, schema) attrs.ref.node_id = 0 return nothing end @@ -727,7 +787,8 @@ function rename_column!(store::MTGAttributeStore, symbol::Symbol, from::Symbol, return store end -function Base.length(attrs::ColumnarAttrs) +Base.length(attrs::ColumnarAttrs) = _row_length(attrs, nothing) +function _row_length(attrs::ColumnarAttrs, schema) if !_isbound(attrs) return length(_staged_attributes(attrs)) end @@ -735,7 +796,7 @@ function Base.length(attrs::ColumnarAttrs) bucket = store.buckets[bid] count = 0 @inbounds for column in bucket.columns - count += column.present[row] + count += _row_has_value(_row_column(schema, column), row) end return count end @@ -839,10 +900,10 @@ function Base.get(attrs::ColumnarAttrs, key::Symbol, default::T) where {T} end Base.get(attrs::ColumnarAttrs, key, default) = get(attrs, _normalize_attr_key(key), default) -@inline function _set_value_bound!(bucket::SymbolBucket, row::Int, key::Symbol, value::T) where {T} +@inline function _set_value_bound!(bucket::SymbolBucket, row::Int, key::Symbol, value::T, schema=nothing) where {T} col_idx = get(bucket.col_index, key, 0) if col_idx == 0 - _set_value!(bucket, row, key, value) + _set_value!(bucket, row, key, value, schema) return value end @@ -855,7 +916,7 @@ Base.get(attrs::ColumnarAttrs, key, default) = get(attrs, _normalize_attr_key(ke @inbounds col.data[row] = value _mark_row_present!(col, row) else - _set_value!(bucket, row, key, value) + _set_value!(bucket, row, key, value, schema) end return value diff --git a/src/types/Node.jl b/src/types/Node.jl index f61e170..71b7587 100644 --- a/src/types/Node.jl +++ b/src/types/Node.jl @@ -152,6 +152,7 @@ function _node_with_columnar_attrs( MTG::M, attributes::ColumnarAttrs, values, + schema=nothing, ) where {M<:AbstractNodeMTG} parent_attrs = node_attributes(parent) parent_store = _store_for_node_attrs(parent_attrs) @@ -162,9 +163,9 @@ function _node_with_columnar_attrs( node = Node{M,ColumnarAttrs}( id, parent, Vector{Node{M,ColumnarAttrs}}(), MTG, attributes, nothing ) + bind_columnar_child!(parent_attrs, attributes, id, getfield(MTG, :symbol), values, schema) push!(children(parent), node) _invalidate_traversal_caches!(parent) - bind_columnar_child!(parent_attrs, attributes, id, getfield(MTG, :symbol), values) return node end @@ -293,15 +294,19 @@ end Set the parent of the node, removing it from the old parent's children and adding it to the new parent's children. """ -function reparent!(node::N, p::N2) where {N<:Node{T,A},N2<:Union{Nothing,Node{T,A}}} where {T,A} +reparent!(node::N, p::N2) where {N<:Node{T,A},N2<:Union{Nothing,Node{T,A}}} where {T,A} = + _reparent!(node, p, nothing) + +function _reparent!(node::Node{T,A}, p::Union{Nothing,Node{T,A}}, schema, new_link=nothing) where {T,A} p === node && error("A node cannot be its own parent.") old_parent = parent(node) changed = old_parent !== p if changed && p !== nothing _validate_reparent_target(node, p) - _validate_columnar_attach!(p, node) + _validate_columnar_attach!(p, node, nothing, schema) end + isnothing(new_link) || link!(node, something(new_link)) changed && _maybe_traversal_cache(node) !== nothing && _discard_traversal_cache!(node) if old_parent !== nothing && changed _detach_child!(old_parent, node) @@ -309,7 +314,7 @@ function reparent!(node::N, p::N2) where {N<:Node{T,A},N2<:Union{Nothing,Node{T, setfield!(node, :parent, p) attached = p === nothing ? false : _attach_child!(p, node) - p === nothing || _maybe_recolumnarize_after_attach!(p, node) + p === nothing || _maybe_recolumnarize_after_attach!(p, node, schema) if (changed || attached) && (!attached || _maybe_traversal_cache(node) !== nothing) _mark_structure_mutation!(node) end @@ -322,7 +327,11 @@ end Set the children of the node, detaching removed children and setting this node as the parent of the new children. """ -function rechildren!(node::Node{T,A}, chnodes::Vector{Node{T,A}}) where {T,A} +rechildren!(node::Node{T,A}, chnodes::Vector{Node{T,A}}) where {T,A} = + _replace_children!(node, chnodes) + +# Empty tuples let a deletion express that it supplies no new children. +function _replace_children!(node::Node{T,A}, chnodes) where {T,A} if length(chnodes) <= 8 for child_index in eachindex(chnodes) child = chnodes[child_index] @@ -350,7 +359,7 @@ function rechildren!(node::Node{T,A}, chnodes::Vector{Node{T,A}}) where {T,A} end old_children = children(node) - setfield!(node, :children, chnodes) + setfield!(node, :children, chnodes isa Tuple{} ? Node{T,A}[] : chnodes) for old_child in old_children if parent(old_child) === node && _child_index_by_identity(chnodes, old_child) === nothing @@ -363,7 +372,7 @@ function rechildren!(node::Node{T,A}, chnodes::Vector{Node{T,A}}) where {T,A} end _mark_structure_mutation!(node) - return chnodes + return children(node) end # AbstractTrees.childstatetype(::Type{Node{T,A}}) where {T,A} = Node{T,A} diff --git a/test/runtests.jl b/test/runtests.jl index b14a89d..26c64c7 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -25,6 +25,7 @@ end include("test-columnar-iteration-mutation.jl") include("test-columnar-reads.jl") include("test-columnar-updates.jl") + include("test-prepared-node-edits.jl") end @testset "descendants()" begin diff --git a/test/test-prepared-node-edits.jl b/test/test-prepared-node-edits.jl new file mode 100644 index 0000000..d998578 --- /dev/null +++ b/test/test-prepared-node-edits.jl @@ -0,0 +1,28 @@ +@testset "Prepared edits on the original columnar tree" begin + root = Node(1, NodeMTG(:/, :Plant, 1, 1), (rank=0,)) + other = Node(1, NodeMTG(:/, :Plant, 1, 1), (rank=0,)) + plan = prepare_node_edits(root) + label = NodeMTG(:+, :Leaf, 1, 2) + @test_throws ArgumentError addchild!(plan, other, 2, label) + @test_throws ArgumentError addchild!(plan, root, 2, label, (rank=1, weight=1.0,)) + @test isempty(children(root)) + @test get_node(root, 2) === nothing + leaf = addchild!(plan, root, 2, label) + @test isempty(node_attributes(leaf)) + @test attribute(plan, leaf, :rank, -1) === -1 + child = addchild!(plan, leaf, 3, NodeMTG(:<, :Leaf, 2, 2), (rank=7, tag=nothing)) + @test attribute(plan, child, :rank) === 7 + @test attribute(plan, child, :tag, -1) === nothing + @test_throws ArgumentError addchild!(plan, root, 3, label) + @test_throws ArgumentError delete_node!(plan, other) + @test delete_node!(plan, leaf) === root + @test only(children(root)) === child + @test parent(child) === root + @test link(child) === :+ + @test attribute(child, :rank) === 7 + @test get_node(root, 2) === nothing + @test_throws ArgumentError attribute(plan, leaf, :rank) + @test_throws ArgumentError addchild!(plan, root, 4, label, (rank="four",)) + @test get_node(root, 4) === nothing + @test only(children(root)) === child +end From bcc58a86356d0cbdcafbac721a367e7dcb978fdb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 11:34:28 +0100 Subject: [PATCH 2/3] Preserve numeric attribute reads and cover schema renewal --- src/compute_MTG/prepared_node_edits.jl | 8 ++++++-- src/types/Attributes.jl | 12 ++++++++---- test/test-prepared-node-edits.jl | 20 ++++++++++++++++++++ 3 files changed, 34 insertions(+), 6 deletions(-) diff --git a/src/compute_MTG/prepared_node_edits.jl b/src/compute_MTG/prepared_node_edits.jl index 05a9b99..b749e0e 100644 --- a/src/compute_MTG/prepared_node_edits.jl +++ b/src/compute_MTG/prepared_node_edits.jl @@ -40,7 +40,7 @@ function delete_node!(plan::PreparedNodeEdits, node::Node{M,ColumnarAttrs}) wher return _delete_node!(node, new_child_link, plan.schema) end -function attribute(plan::PreparedNodeEdits, node::Node{M,ColumnarAttrs}, key::Symbol, default=nothing) where {M} +function attribute(plan::PreparedNodeEdits, node::Node{M,ColumnarAttrs}, key::Symbol, default) where {M} _check_edit_store(plan, node) store, bid, row = _bucket_row(getfield(node_attributes(node), :ref)) bucket = store.buckets[bid] @@ -48,5 +48,9 @@ function attribute(plan::PreparedNodeEdits, node::Node{M,ColumnarAttrs}, key::Sy iszero(slot) && return default column = _column(bucket, slot) _check_row_column_type(plan.schema, typeof(column)) - return _get_column_value(_row_column(plan.schema, column), row, default) + value = _get_column_value(_row_column(plan.schema, column), row, default) + return _attribute_read_value(value, default) end + +attribute(plan::PreparedNodeEdits, node::Node, key::Symbol; default=nothing) = + attribute(plan, node, key, default) diff --git a/src/types/Attributes.jl b/src/types/Attributes.jl index 7b6eda1..17261e5 100644 --- a/src/types/Attributes.jl +++ b/src/types/Attributes.jl @@ -852,11 +852,16 @@ end bucket.col_types[col_idx] === Union{Nothing,T} end +@inline _attribute_read_value(value, default) = value +@inline function _attribute_read_value(value, default::T) where {T<:Number} + value === nothing && return nothing + return value isa T ? value : (convert(T, value)::T) +end + @inline function _get_typed_numeric(attrs::ColumnarAttrs, key::Symbol, default::T) where {T<:Number} if !_isbound(attrs) v = get(_staged_attributes(attrs), key, default) - v === nothing && return nothing - return v isa T ? v : (convert(T, v)::T) + return _attribute_read_value(v, default) end store, bid, row = _bound_store_bid_row(attrs.ref) @@ -874,8 +879,7 @@ end end v = _get_column_value(column, row, default) - v === nothing && return nothing - return v isa T ? v : (convert(T, v)::T) + return _attribute_read_value(v, default) end function Base.get(attrs::ColumnarAttrs, key::Symbol, default::T) where {T} diff --git a/test/test-prepared-node-edits.jl b/test/test-prepared-node-edits.jl index d998578..1207db9 100644 --- a/test/test-prepared-node-edits.jl +++ b/test/test-prepared-node-edits.jl @@ -26,3 +26,23 @@ @test get_node(root, 4) === nothing @test only(children(root)) === child end + +@testset "Refresh a prepared tree after declaring a column" begin + root = Node(1, NodeMTG(:/, :Plant, 1, 1), (;)) + plan = prepare_node_edits(root) + label = NodeMTG(:+, :Leaf, 1, 2) + first_leaf = addchild!(plan, root, 2, label) + add_column!(root, :Leaf, :area, Float32; default=0f0) + @test_throws ArgumentError addchild!(plan, root, 3, label) + @test_throws ArgumentError delete_node!(plan, first_leaf) + @test_throws ArgumentError attribute(plan, first_leaf, :area) + @test only(children(root)) === first_leaf + refreshed = prepare_node_edits(first_leaf) + second_leaf = addchild!(refreshed, root, 3, label, (area=0.5f0,)) + @test attribute(refreshed, first_leaf, :area) === 0f0 + @test attribute(refreshed, second_leaf, :area) === 0.5f0 + @test attribute(refreshed, second_leaf, :area; default=0.0) === attribute(second_leaf, :area, 0.0) === 0.5 + @test_throws InexactError attribute(refreshed, second_leaf, :area, 0) + @test delete_node!(refreshed, first_leaf) === root + @test only(children(root)) === second_leaf +end From b3b39f5d33543fe2775756782ec1c4de33ba5775 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 15:43:34 +0100 Subject: [PATCH 3/3] Expose declared attribute types for prepared tree edits --- docs/src/api.md | 7 ++++++- src/MultiScaleTreeGraph.jl | 2 +- src/compute_MTG/node_funs.jl | 5 +++-- src/compute_MTG/prepared_node_edits.jl | 2 +- src/types/Node.jl | 20 ++++++++++++++++++++ test/test-prepared-node-edits.jl | 15 +++++++++++++++ 6 files changed, 46 insertions(+), 5 deletions(-) diff --git a/docs/src/api.md b/docs/src/api.md index 74b6610..da82b3c 100644 --- a/docs/src/api.md +++ b/docs/src/api.md @@ -4,7 +4,7 @@ Here is a list of all exported functions from MultiScaleTreeGraph.jl. For more d Notable attribute APIs: -- `attribute`, `attribute!`, `attributes`, `attribute_names` +- `attribute`, `attribute!`, `attributes`, `attribute_names`, `attribute_type` - `add_column!`, `drop_column!`, `rename_column!` - `descendants_strategy`, `descendants_strategy!` (choose automatic/direct/indexed descendants retrieval) - `to_table` (`Tables.jl` source/sink entry-point) @@ -32,3 +32,8 @@ The optional final named tuple of `addchild!` supplies **tree attributes**. In a coupled simulation, variables held by the simulation can stay in its own status. Removing a node promotes its children according to the ordinary `delete_node!` rules. It only changes the tree. + +To inspect the types that future organs can inherit, call +`attribute_type(plant, :kind)`. For example, if a leaf declares an `Int` +and a flower declares a `Symbol` for `kind`, the result is +`Union{Int,Symbol}` even before the first leaf or flower has grown. diff --git a/src/MultiScaleTreeGraph.jl b/src/MultiScaleTreeGraph.jl index 2113338..6848af3 100644 --- a/src/MultiScaleTreeGraph.jl +++ b/src/MultiScaleTreeGraph.jl @@ -88,7 +88,7 @@ export symbol, scale, index, link export symbol!, scale!, index!, link! export ColumnarStore export Column, SymbolBucket, MTGAttributeStore, NodeAttrRef -export attribute, attribute!, attributes, attribute_names +export attribute, attribute!, attributes, attribute_names, attribute_type export add_column!, drop_column!, rename_column! export descendants_strategy, descendants_strategy! export columnarize! diff --git a/src/compute_MTG/node_funs.jl b/src/compute_MTG/node_funs.jl index cbfda74..bdca020 100644 --- a/src/compute_MTG/node_funs.jl +++ b/src/compute_MTG/node_funs.jl @@ -120,8 +120,9 @@ function _columnar_row_snapshot(attrs::ColumnarAttrs, schema) source, source_bid, source_row = _bucket_row(ref) for raw in source.buckets[source_bid].columns column = _row_column(schema, raw) - if _row_has_value(column, source_row) - snapshot[column.name] = column.data[source_row]::V + value = _get_column_value(column, source_row, nothing)::V + if !isnothing(value) || _row_has_value(column, source_row) + snapshot[column.name] = value end end end diff --git a/src/compute_MTG/prepared_node_edits.jl b/src/compute_MTG/prepared_node_edits.jl index b749e0e..946bde1 100644 --- a/src/compute_MTG/prepared_node_edits.jl +++ b/src/compute_MTG/prepared_node_edits.jl @@ -14,7 +14,7 @@ Use `addchild!(plan, parent, id, encoding[, attributes])` to insert a child, An empty attribute tuple is the default. New nodes and attribute names may appear at any time. Each resulting column type must belong to the prepared -family. To introduce another type, declare its column with [`add_column!`](@ref) +family. To introduce another type, declare its column with `add_column!` and prepare a fresh plan. The plan is specific to this store. """ function prepare_node_edits(node::Node{M,ColumnarAttrs}) where {M} diff --git a/src/types/Node.jl b/src/types/Node.jl index 71b7587..5ec9daa 100644 --- a/src/types/Node.jl +++ b/src/types/Node.jl @@ -810,6 +810,26 @@ end return nothing end +""" + attribute_type(node, key::Symbol) + +Return the union of the value types declared for `key` across the columnar +tree that contains `node`. Columns on organ symbols with no nodes are included. +An undeclared attribute gives `Union{}`. This queries the current schema, +so call it before preparing an application that fixes its attribute types. +""" +function attribute_type(node::Node, key::Symbol) + store = _node_store(node) + T = Union{} + for bucket in store.buckets + slot = get(bucket.col_index, key, 0) + if !iszero(slot) + T = Union{T,bucket.col_types[slot]} + end + end + return T +end + function add_column!(node::Node, symbol::Symbol, key::Symbol, ::Type{T}; default::T) where {T} add_column!(_node_store(node), symbol, key, T, default=default) end diff --git a/test/test-prepared-node-edits.jl b/test/test-prepared-node-edits.jl index 1207db9..e90699b 100644 --- a/test/test-prepared-node-edits.jl +++ b/test/test-prepared-node-edits.jl @@ -46,3 +46,18 @@ end @test delete_node!(refreshed, first_leaf) === root @test only(children(root)) === second_leaf end + +@testset "Declared attribute types include organ symbols without nodes" begin + root = Node(1, NodeMTG(:/, :Plant, 1, 1), (;)) + @test attribute_type(root, :kind) === Union{} + add_column!(root, :Leaf, :kind, Int; default=3) + add_column!(root, :Flower, :kind, Symbol; default=:open) + add_column!(root, :Plant, :note, String; default="plot") + @test isempty(children(root)) + @test attribute_type(root, :kind) === Union{Int,Symbol} + leaf = addchild!(prepare_node_edits(root), root, 2, NodeMTG(:+, :Leaf, 1, 2)) + @test attribute_type(leaf, :note) === String + @test attribute_type(leaf, :kind) === Union{Int,Symbol} + drop_column!(root, :Leaf, :kind) + @test attribute_type(leaf, :kind) === Symbol +end