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

Better sorting algorithm for classes_sorted_by_inheritance #47

Open
FChikh opened this issue Nov 22, 2023 · 0 comments
Open

Better sorting algorithm for classes_sorted_by_inheritance #47

FChikh opened this issue Nov 22, 2023 · 0 comments
Labels
enhancement New feature or request

Comments

@FChikh
Copy link
Collaborator

FChikh commented Nov 22, 2023

As I've noticed, now the average time complexity for DomainModel.classes_sorted_by_inheritance() is O(|classes|^2), as there are two nested loops which iterates over classes' set. It can be improved with implementation of Topological Sorting algorithm with asymptotic of O(|classes| + |generalizations|), so it can be assumed as linear time, if the number of generalizations is proportional to the number of classes. I haven't tried yet to debug it, but here is how it approximately should look like:

def classes_sorted_by_inheritance(classes):
    # Set up a dependency graph
    child_map = {cl: set() for cl in classes}

    # Populating the child_map based on generalizations (edges in top-sort graph)
    for cl in classes:
        for generalization in cl.generalizations:
            child_map[generalization.general].add(cl)

    # Helper function for DFS
    def dfs(cl, visited, sorted_list):
        visited.add(cl)
        for child in child_map[cl]:
            if child not in visited:
                dfs(child, visited, sorted_list)
        sorted_list.append(cl)

    # Perform DFS from each node that hasn't been visited yet
    visited = set()
    sorted_list = []
    for cl in classes:
        if cl not in visited:
            dfs(cl, visited, sorted_list)

    # The classes are sorted from most derived to least derived, so reverse the list
    sorted_list.reverse()
    return sorted_list

As I told Ivan, I can contribute on this matter as well.

@FChikh FChikh added the enhancement New feature or request label Nov 22, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants