Debian Codegraph @

brian2/sphinxext/examplefinder.py

raw
1 """
2 Automatically find examples of a Brian object or function.
3 """
4
5 import os
6 from collections import defaultdict
7
8 from brian2.utils.stringtools import get_identifiers
9
10 from .generate_examples import GlobDirectoryWalker
11
12 __all__ = ["auto_find_examples"]
13
14 the_examples_map = defaultdict(list)
15 the_tutorials_map = defaultdict(list)
16
17
18 def get_map(environ_var, relrootdir, pattern, the_map, path_exclusions=None):
19 if path_exclusions is None:
20 path_exclusions = []
21 if the_map:
22 return the_map
23 if environ_var in os.environ:
24 rootdir = os.environ[environ_var]
25 else:
26 rootdir, _ = os.path.split(__file__)
27 rootdir = os.path.normpath(os.path.join(rootdir, relrootdir))
28 fnames = [fname for fname in GlobDirectoryWalker(rootdir, f"*{pattern}")]
29 for exclude in path_exclusions:
30 fnames = [fname for fname in fnames if exclude not in fname]
31 shortfnames = [os.path.relpath(fname, rootdir) for fname in fnames]
32 exnames = [
33 fname.replace("/", ".").replace("\\", ".").replace(pattern, "")
34 for fname in shortfnames
35 ]
36 for fname, shortfname, exname in zip(fnames, shortfnames, exnames, strict=True):
37 with open(fname) as f:
38 ex = f.read()
39 ids = get_identifiers(ex)
40 for id in ids:
41 the_map[id].append((shortfname.replace("\\", "/"), exname))
42 return the_map
43
44
45 def get_examples_map():
46 return get_map("BRIAN2_DOCS_EXAMPLE_DIR", "../../examples", ".py", the_examples_map)
47
48
49 def get_tutorials_map():
50 return get_map(
51 "BRIAN2_DOCS_TUTORIALS_DIR",
52 "../../tutorials",
53 ".ipynb",
54 the_tutorials_map,
55 path_exclusions=[".ipynb_checkpoints"],
56 )
57
58
59 def auto_find_examples(obj, headersymbol="="):
60 """
61 Returns a restructured text section listing all the examples and
62 tutorials making use of the specified object (as determined by
63 the name being in the list of identifiers, which may occasionally
64 make mistakes but is usually going to be correct).
65 """
66 name = obj.__name__
67 # These will only go through the examples/tutorials once. The dictionaries are cached in the
68 # module variables `the_examples_map` and `the_tutorials_map`.
69 examples_map = get_examples_map()
70 examples = sorted(examples_map[name])
71 tutorials_map = get_tutorials_map()
72 tutorials = sorted(tutorials_map[name])
73 if len(examples + tutorials) == 0:
74 return ""
75 txt = "Tutorials and examples using this"
76 txt = f"{txt}\n{headersymbol * len(txt)}\n\n"
77 for tutname, tutloc in tutorials:
78 tutname = tutname.replace(".ipynb", "")
79 txt += f"* Tutorial :doc:`{tutname} </resources/tutorials/{tutloc}>`\n"
80 for exname, exloc in examples:
81 exname = exname.replace(".py", "")
82 txt += f"* Example :doc:`{exname} </examples/{exloc}>`\n"
83 return f"{txt}\n"
84
85
86 if __name__ == "__main__":
87 from brian2 import NeuronGroup
88
89 print(auto_find_examples(NeuronGroup))