Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

get_ancestors, get_descendants on Hierarchy #732

Merged
merged 3 commits into from
Jun 1, 2022
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
40 changes: 36 additions & 4 deletions TM1py/Objects/Hierarchy.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import collections
import json
from typing import List, Dict, Iterable, Optional, Tuple, Union
from typing import List, Dict, Iterable, Optional, Tuple, Union, Set

from TM1py.Objects.Element import Element
from TM1py.Objects.ElementAttribute import ElementAttribute
Expand Down Expand Up @@ -48,7 +48,7 @@ def __init__(
self._name = name
self._dimension_name = None
self.dimension_name = dimension_name
self._elements = CaseAndSpaceInsensitiveDict()
self._elements: Dict[str, Element] = CaseAndSpaceInsensitiveDict()
if elements:
for elem in elements:
self._elements[elem.name] = elem
Expand Down Expand Up @@ -99,15 +99,15 @@ def dimension_name(self, dimension_name: str):
self._dimension_name = dimension_name

@property
def elements(self) -> CaseAndSpaceInsensitiveDict:
def elements(self) -> Dict[str, Element]:
return self._elements

@property
def element_attributes(self) -> List[ElementAttribute]:
return self._element_attributes

@property
def edges(self) -> 'CaseAndSpaceInsensitiveTuplesDict':
def edges(self) -> Dict[Tuple[str], Element]:
return self._edges

@property
Expand Down Expand Up @@ -139,6 +139,38 @@ def get_element(self, element_name: str) -> Element:
else:
raise ValueError("Element: {} not found in Hierarchy: {}".format(element_name, self.name))

def get_ancestors(self, element_name: str, recursive: bool = False) -> Set[Element]:
ancestors = set()

for (parent, component) in self._edges:
if not case_and_space_insensitive_equals(component, element_name):
continue

ancestor: Element = self.elements[parent]
ancestors.add(ancestor)

if recursive:
ancestors = ancestors.union(self.get_ancestors(ancestor.name, True))
return ancestors

def get_descendants(self, element_name: str, recursive: bool = False, leaves_only=False) -> Set[Element]:
descendants = set()

for (parent, component) in self._edges:
if not case_and_space_insensitive_equals(parent, element_name):
continue

descendant: Element = self.elements[component]
if not leaves_only:
descendants.add(descendant)
else:
if descendant.element_type == Element.Types.NUMERIC:
descendants.add(descendant)

if recursive and descendant.element_type == Element.Types.CONSOLIDATED:
descendants = descendants.union(self.get_descendants(descendant.name, True))
return descendants

def add_element(self, element_name: str, element_type: Union[str, Element.Types]):
if element_name in self._elements:
raise ValueError("Element name must be unique")
Expand Down
4 changes: 2 additions & 2 deletions TM1py/Services/HierarchyService.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def create(self, hierarchy: Hierarchy, **kwargs):
response = self._rest.POST(url, hierarchy.body, **kwargs)
return response

def get(self, dimension_name: str, hierarchy_name: str, **kwargs):
def get(self, dimension_name: str, hierarchy_name: str, **kwargs) -> Hierarchy:
""" get hierarchy

:param dimension_name: name of the dimension
Expand All @@ -51,7 +51,7 @@ def get(self, dimension_name: str, hierarchy_name: str, **kwargs):
response = self._rest.GET(url, **kwargs)
return Hierarchy.from_dict(response.json())

def get_all_names(self, dimension_name: str, **kwargs):
def get_all_names(self, dimension_name: str, **kwargs) -> List[str]:
""" get all names of existing Hierarchies in a dimension

:param dimension_name:
Expand Down
138 changes: 137 additions & 1 deletion Tests/Hierarchy_test.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import unittest

from TM1py import Hierarchy
from TM1py import Hierarchy, Element


class TestHierarchy(unittest.TestCase):
Expand Down Expand Up @@ -39,6 +39,142 @@ def test_add_component_parent_is_string(self):
hierarchy.add_component(parent_name="c1", component_name="e1", weight=1)
print(str(error))

def test_get_ancestors(self):
hierarchy = Hierarchy(
name="NotRelevant",
dimension_name="NotRelevant",
elements=[
Element("Total", "Consolidated"),
Element("Europe", "Consolidated"),
Element("DACH", "Consolidated"),
Element("Germany", "Numeric"),
Element("Switzerland", "Numeric"),
Element("Austria", "Numeric"),
Element("France", "Numeric"),
Element("Other", "Numeric")],
edges={
("Total", "Europe"): 1,
("Europe", "DACH"): 1,
("DACH", "Germany"): 1,
("DACH", "Switzerland"): 1,
("DACH", "Austria"): 1,
("Europe", "France"): 1,
})

elements = hierarchy.get_ancestors("Germany", recursive=False)
self.assertEqual(
{Element("DACH", "Consolidated")},
elements)

def test_get_ancestors_recursive(self):
hierarchy = Hierarchy(
name="NotRelevant",
dimension_name="NotRelevant",
elements=[
Element("Total", "Consolidated"),
Element("Europe", "Consolidated"),
Element("DACH", "Consolidated"),
Element("Germany", "Numeric"),
Element("Switzerland", "Numeric"),
Element("Austria", "Numeric"),
Element("France", "Numeric"),
Element("Other", "Numeric")],
edges={
("Total", "Europe"): 1,
("Europe", "DACH"): 1,
("DACH", "Germany"): 1,
("DACH", "Switzerland"): 1,
("DACH", "Austria"): 1,
("Europe", "France"): 1,
})

elements = hierarchy.get_ancestors("Germany", recursive=True)
self.assertEqual(
{Element("DACH", "Consolidated"), Element("Europe", "Consolidated"), Element("Total", "Consolidated")},
elements)

def test_get_descendants(self):
hierarchy = Hierarchy(
name="NotRelevant",
dimension_name="NotRelevant",
elements=[
Element("Total", "Consolidated"),
Element("Europe", "Consolidated"),
Element("DACH", "Consolidated"),
Element("Germany", "Numeric"),
Element("Switzerland", "Numeric"),
Element("Austria", "Numeric"),
Element("France", "Numeric"),
Element("Other", "Numeric")],
edges={
("Total", "Europe"): 1,
("Europe", "DACH"): 1,
("DACH", "Germany"): 1,
("DACH", "Switzerland"): 1,
("DACH", "Austria"): 1,
("Europe", "France"): 1,
})

elements = hierarchy.get_descendants("DACH")
self.assertEqual(
{Element("Germany", "Numeric"), Element("Austria", "Numeric"), Element("Switzerland", "Numeric")},
elements)

def test_get_descendants_recursive(self):
hierarchy = Hierarchy(
name="NotRelevant",
dimension_name="NotRelevant",
elements=[
Element("Total", "Consolidated"),
Element("Europe", "Consolidated"),
Element("DACH", "Consolidated"),
Element("Germany", "Numeric"),
Element("Switzerland", "Numeric"),
Element("Austria", "Numeric"),
Element("France", "Numeric"),
Element("Other", "Numeric")],
edges={
("Total", "Europe"): 1,
("Europe", "DACH"): 1,
("DACH", "Germany"): 1,
("DACH", "Switzerland"): 1,
("DACH", "Austria"): 1,
("Europe", "France"): 1,
})

elements = hierarchy.get_descendants("Europe", recursive=True)
self.assertEqual(
{Element("DACH", "Consolidated"), Element("Germany", "Numeric"), Element("Austria", "Numeric"),
Element("Switzerland", "Numeric"), Element("France", "Numeric")},
elements)

def test_get_descendants_recursive_leaves_only(self):
hierarchy = Hierarchy(
name="NotRelevant",
dimension_name="NotRelevant",
elements=[
Element("Total", "Consolidated"),
Element("Europe", "Consolidated"),
Element("DACH", "Consolidated"),
Element("Germany", "Numeric"),
Element("Switzerland", "Numeric"),
Element("Austria", "Numeric"),
Element("France", "Numeric"),
Element("Other", "Numeric")],
edges={
("Total", "Europe"): 1,
("Europe", "DACH"): 1,
("DACH", "Germany"): 1,
("DACH", "Switzerland"): 1,
("DACH", "Austria"): 1,
("Europe", "France"): 1,
})

elements = hierarchy.get_descendants("Europe", recursive=True, leaves_only=True)
self.assertEqual(
{Element("Germany", "Numeric"), Element("Austria", "Numeric"),
Element("Switzerland", "Numeric"), Element("France", "Numeric")},
elements)

if __name__ == '__main__':
unittest.main()
2 changes: 1 addition & 1 deletion Tests/NativeView_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def test_as_mdx_happy_case(self):
"SELECT\r\n"
"NON EMPTY {[d1].[e1]} ON 0,\r\n"
"{[d2].[e2]} ON 1\r\n"
"FROM [C1]\r\n"
"FROM [c1]\r\n"
"WHERE ([d3].[d3].[e3])",
native_view.mdx)

Expand Down