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
24 changes: 23 additions & 1 deletion docs/src/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -15,3 +15,25 @@ 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.

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.
5 changes: 3 additions & 2 deletions src/MultiScaleTreeGraph.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand All @@ -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
Expand Down Expand Up @@ -87,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!
Expand Down
81 changes: 59 additions & 22 deletions src/compute_MTG/delete_nodes.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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

"""
Expand Down
49 changes: 40 additions & 9 deletions src/compute_MTG/node_funs.jl
Original file line number Diff line number Diff line change
Expand Up @@ -107,15 +107,37 @@ 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)
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
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)
Expand All @@ -126,27 +148,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)
Expand All @@ -158,6 +182,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))
Expand All @@ -169,11 +200,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
Expand Down
56 changes: 56 additions & 0 deletions src/compute_MTG/prepared_node_edits.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
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!`
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) 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))
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)
Loading
Loading