Coverage for portality/models/lcc.py: 97%

65 statements  

« prev     ^ index     » next       coverage.py v6.4.2, created at 2022-07-19 18:38 +0100

1from portality.dao import DomainObject 

2 

3 

4class LCC(DomainObject): 

5 __type__ = "lcc" 

6 

7 def term_path(self, term): 

8 def dive(node, path): 

9 if node.get("name") == term: 

10 path.append(term) 

11 return True 

12 

13 if "children" not in node: 

14 return False 

15 

16 path.append(node.get("name")) 

17 

18 for n in node.get("children", []): 

19 found = dive(n, path) 

20 if found: 

21 return True 

22 

23 path.pop() 

24 return False 

25 

26 roots = self.data.get("children", []) 

27 for r in roots: 

28 path = [] 

29 found = dive(r, path) 

30 if found: 

31 return path 

32 

33 return None 

34 

35 def pathify(self, term, path_separator=": "): 

36 """ 

37 Convert the given term into a string containing the path from the root via the parents to the term 

38 :param term: 

39 :param path_separator: 

40 :return: 

41 """ 

42 path = self.term_path(term) 

43 if path is not None: 

44 return path_separator.join(path) 

45 return None 

46 

47 def expand_codes(self, code): 

48 def dive(node, path): 

49 if node.get("code") == code: 

50 path.append(code) 

51 return True 

52 

53 if "children" not in node: 

54 return False 

55 

56 path.append(node.get("code")) 

57 

58 for n in node.get("children", []): 

59 found = dive(n, path) 

60 if found: 

61 return True 

62 

63 path.pop() 

64 return False 

65 

66 roots = self.data.get("children", []) 

67 for r in roots: 

68 path = [] 

69 found = dive(r, path) 

70 if found: 

71 return path 

72 

73 return [] 

74 

75 def longest(self, paths): 

76 """ 

77 Returns only the longest paths from the provided classification paths (created with pathify) 

78 :param paths: 

79 :return: 

80 """ 

81 keep = [] 

82 for candidate in paths: 

83 trip = False 

84 for other in paths: 

85 # if the candidate is a substring of another, longer, string, hit the tripwire 

86 if candidate in other and len(candidate) != len(other): 

87 trip = True 

88 break 

89 

90 if not trip: 

91 if candidate not in keep: 

92 keep.append(candidate) 

93 

94 return keep 

95 

96 def save(self, **kwargs): 

97 self.set_id("lcc") 

98 return super(LCC, self).save(**kwargs)