Skip to content

Instantly share code, notes, and snippets.

@ppazos
Last active August 16, 2023 21:52
Show Gist options
  • Save ppazos/24877ae9a62a4ce3c396ce9ea2832713 to your computer and use it in GitHub Desktop.
Save ppazos/24877ae9a62a4ce3c396ce9ea2832713 to your computer and use it in GitHub Desktop.
openEHR data paths to trees
import groovy.json.*
// NOTE: the prefix / was removed to help the recursion, this step could be done before starting of it can be part of the first recursion
def data = [
"name",
"category",
"context/setting",
"context/start_time",
"content(3)/data/origin",
"content(3)/data/events(1)/time",
"content(3)/data/events(1)/data/items(0)/items(0)/value",
"content(3)/data/events(1)/data/items(0)/items(1)/value",
"content(3)/data/events(1)/data/items(0)/items(2)/items(0)/value",
"content(3)/data/events(1)/data/items(0)/items(2)/items(1)/value",
"content(3)/data/events(1)/data/items(0)/items(3)/items(0)/value",
"content(3)/data/events(1)/data/items(0)/items(3)/items(1)/value",
"content(3)/data/events(1)/data/items(1)/items(0)/value",
"content(3)/data/events(1)/data/items(1)/items(1)/value",
"content(3)/data/events(1)/data/items(1)/items(2)/items(0)/value",
"content(3)/data/events(1)/data/items(1)/items(2)/items(1)/value",
"content(3)/data/events(1)/data/items(1)/items(3)/items(0)/value",
"content(3)/data/events(1)/data/items(1)/items(3)/items(1)/value"
]
class Tree {
String name
List subtrees = []
// NOTE: the data value index will be inside the tree and appear only on leaf trees
}
def generate_multi_trees(List list_of_paths)
{
def trees = []
def parts, next_list_of_paths, t
Map group = list_of_paths.groupBy{ it.split('/', 2)[0] }
group.each { parent, paths ->
//println parent +': '
t = new Tree(name: parent)
trees << t
next_list_of_paths = []
paths.each { path ->
// the tree for the leaf node is created if the last recursion, being the leaf the parent in that recursion, so the tree is always created for the parent.
if (parent == path) return // reached the end of the path
//println path - (parent +'/')
next_list_of_paths << path - (parent +'/') // remove the prefix from the path to continue the recursion
}
// no paths to continue, stop the recursion
if (next_list_of_paths)
t.subtrees = generate_multi_trees(next_list_of_paths)
}
return trees
}
def ts = generate_multi_trees(data)
println JsonOutput.toJson(ts)
//println JsonOutput.prettyPrint(JsonOutput.toJson(ts)) // pretty print
/*
def traverse(List path_tokens)
{
if (!path_tokens) return
def tree = new Tree(name: path_tokens[0])
def subtree = traverse(path_tokens.tail())
if (subtree)
tree.subtrees << subtree
return tree
}
println JsonOutput.toJson( traverse("/content(3)/data/events(1)/data/items(1)/items(3)/items(1)/value".tokenize('/')) )
*/
/*
def data2 = data.groupBy{ it.substring(0, it.indexOf('/')) }
data2.each { k, v ->
println k +": "+ v
}
*/
return
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment