Skip to content

Commit

Permalink
MAINT: Run black on codebase
Browse files Browse the repository at this point in the history
  • Loading branch information
larsoner committed May 2, 2023
1 parent 97bbc37 commit e81ec52
Show file tree
Hide file tree
Showing 707 changed files with 107,021 additions and 70,350 deletions.
1,958 changes: 1,158 additions & 800 deletions doc/conf.py

Large diffs are not rendered by default.

184 changes: 100 additions & 84 deletions doc/sphinxext/flow_diagram.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import os
from os import path as op

title = 'mne-python flow diagram'
title = "mne-python flow diagram"

font_face = 'Arial'
font_face = "Arial"
node_size = 12
node_small_size = 9
edge_size = 9
sensor_color = '#7bbeca'
source_color = '#ff6347'
sensor_color = "#7bbeca"
source_color = "#ff6347"

legend = """
<<FONT POINT-SIZE="%s">
Expand All @@ -17,62 +17,74 @@
Sensor (M/EEG) space</TD></TR>
<TR><TD BGCOLOR="%s"> </TD><TD ALIGN="left">
Source (brain) space</TD></TR>
</TABLE></FONT>>""" % (edge_size, sensor_color, source_color)
legend = ''.join(legend.split('\n'))
</TABLE></FONT>>""" % (
edge_size,
sensor_color,
source_color,
)
legend = "".join(legend.split("\n"))

nodes = dict(
T1='T1',
flashes='Flash5/30',
trans='Head-MRI trans',
recon='Freesurfer surfaces',
bem='BEM',
src='Source space\nmne.SourceSpaces',
cov='Noise covariance\nmne.Covariance',
fwd='Forward solution\nmne.forward.Forward',
inv='Inverse operator\nmne.minimum_norm.InverseOperator',
stc='Source estimate\nmne.SourceEstimate',
raw='Raw data\nmne.io.Raw',
epo='Epoched data\nmne.Epochs',
evo='Averaged data\nmne.Evoked',
pre='Preprocessed data\nmne.io.Raw',
T1="T1",
flashes="Flash5/30",
trans="Head-MRI trans",
recon="Freesurfer surfaces",
bem="BEM",
src="Source space\nmne.SourceSpaces",
cov="Noise covariance\nmne.Covariance",
fwd="Forward solution\nmne.forward.Forward",
inv="Inverse operator\nmne.minimum_norm.InverseOperator",
stc="Source estimate\nmne.SourceEstimate",
raw="Raw data\nmne.io.Raw",
epo="Epoched data\nmne.Epochs",
evo="Averaged data\nmne.Evoked",
pre="Preprocessed data\nmne.io.Raw",
legend=legend,
)

sensor_space = ('raw', 'pre', 'epo', 'evo', 'cov')
source_space = ('src', 'stc', 'bem', 'flashes', 'recon', 'T1')
sensor_space = ("raw", "pre", "epo", "evo", "cov")
source_space = ("src", "stc", "bem", "flashes", "recon", "T1")

edges = (
('T1', 'recon'),
('flashes', 'bem'),
('recon', 'bem'),
('recon', 'src', 'mne.setup_source_space'),
('src', 'fwd'),
('bem', 'fwd'),
('trans', 'fwd', 'mne.make_forward_solution'),
('fwd', 'inv'),
('cov', 'inv', 'mne.make_inverse_operator'),
('inv', 'stc'),
('evo', 'stc', 'mne.minimum_norm.apply_inverse'),
('raw', 'pre', 'raw.filter\n'
'mne.preprocessing.ICA\n'
'mne.preprocessing.compute_proj_eog\n'
'mne.preprocessing.compute_proj_ecg\n'
'...'),
('pre', 'epo', 'mne.Epochs'),
('epo', 'evo', 'epochs.average'),
('epo', 'cov', 'mne.compute_covariance'),
("T1", "recon"),
("flashes", "bem"),
("recon", "bem"),
("recon", "src", "mne.setup_source_space"),
("src", "fwd"),
("bem", "fwd"),
("trans", "fwd", "mne.make_forward_solution"),
("fwd", "inv"),
("cov", "inv", "mne.make_inverse_operator"),
("inv", "stc"),
("evo", "stc", "mne.minimum_norm.apply_inverse"),
(
"raw",
"pre",
"raw.filter\n"
"mne.preprocessing.ICA\n"
"mne.preprocessing.compute_proj_eog\n"
"mne.preprocessing.compute_proj_ecg\n"
"...",
),
("pre", "epo", "mne.Epochs"),
("epo", "evo", "epochs.average"),
("epo", "cov", "mne.compute_covariance"),
)

subgraphs = (
[('T1', 'flashes', 'recon', 'bem', 'src'),
('<Structural information<BR/><FONT POINT-SIZE="%s"><I>'
'Freesurfer / MNE-C</I></FONT>>' % node_small_size)],
[
("T1", "flashes", "recon", "bem", "src"),
(
'<Structural information<BR/><FONT POINT-SIZE="%s"><I>'
"Freesurfer / MNE-C</I></FONT>>" % node_small_size
),
],
)


def setup(app):
app.connect('builder-inited', generate_flow_diagram)
app.add_config_value('make_flow_diagram', True, 'html')
app.connect("builder-inited", generate_flow_diagram)
app.add_config_value("make_flow_diagram", True, "html")


def setup_module():
Expand All @@ -81,84 +93,88 @@ def setup_module():


def generate_flow_diagram(app):
out_dir = op.join(app.builder.outdir, '_static')
out_dir = op.join(app.builder.outdir, "_static")
if not op.isdir(out_dir):
os.makedirs(out_dir)
out_fname = op.join(out_dir, 'mne-python_flow.svg')
make_flow_diagram = app is None or \
bool(app.builder.config.make_flow_diagram)
out_fname = op.join(out_dir, "mne-python_flow.svg")
make_flow_diagram = app is None or bool(app.builder.config.make_flow_diagram)
if not make_flow_diagram:
print('Skipping flow diagram, webpage will have a missing image')
print("Skipping flow diagram, webpage will have a missing image")
return

import pygraphviz as pgv

g = pgv.AGraph(name=title, directed=True)

for key, label in nodes.items():
label = label.split('\n')
label = label.split("\n")
if len(label) > 1:
label[0] = ('<<FONT POINT-SIZE="%s">' % node_size
+ label[0] + '</FONT>')
label[0] = '<<FONT POINT-SIZE="%s">' % node_size + label[0] + "</FONT>"
for li in range(1, len(label)):
label[li] = ('<FONT POINT-SIZE="%s"><I>' % node_small_size
+ label[li] + '</I></FONT>')
label[-1] = label[-1] + '>'
label = '<BR/>'.join(label)
label[li] = (
'<FONT POINT-SIZE="%s"><I>' % node_small_size
+ label[li]
+ "</I></FONT>"
)
label[-1] = label[-1] + ">"
label = "<BR/>".join(label)
else:
label = label[0]
g.add_node(key, shape='plaintext', label=label)
g.add_node(key, shape="plaintext", label=label)

# Create and customize nodes and edges
for edge in edges:
g.add_edge(*edge[:2])
e = g.get_edge(*edge[:2])
if len(edge) > 2:
e.attr['label'] = ('<<I>' +
'<BR ALIGN="LEFT"/>'.join(edge[2].split('\n')) +
'<BR ALIGN="LEFT"/></I>>')
e.attr['fontsize'] = edge_size
e.attr["label"] = (
"<<I>"
+ '<BR ALIGN="LEFT"/>'.join(edge[2].split("\n"))
+ '<BR ALIGN="LEFT"/></I>>'
)
e.attr["fontsize"] = edge_size

# Change colors
for these_nodes, color in zip((sensor_space, source_space),
(sensor_color, source_color)):
for these_nodes, color in zip(
(sensor_space, source_space), (sensor_color, source_color)
):
for node in these_nodes:
g.get_node(node).attr['fillcolor'] = color
g.get_node(node).attr['style'] = 'filled'
g.get_node(node).attr["fillcolor"] = color
g.get_node(node).attr["style"] = "filled"

# Create subgraphs
for si, subgraph in enumerate(subgraphs):
g.add_subgraph(subgraph[0], 'cluster%s' % si,
label=subgraph[1], color='black')
g.add_subgraph(subgraph[0], "cluster%s" % si, label=subgraph[1], color="black")

# Format (sub)graphs
for gr in g.subgraphs() + [g]:
for x in [gr.node_attr, gr.edge_attr]:
x['fontname'] = font_face
g.node_attr['shape'] = 'box'
x["fontname"] = font_face
g.node_attr["shape"] = "box"

# A couple of special ones
for ni, node in enumerate(('fwd', 'inv', 'trans')):
for ni, node in enumerate(("fwd", "inv", "trans")):
node = g.get_node(node)
node.attr['gradientangle'] = 270
node.attr["gradientangle"] = 270
colors = (source_color, sensor_color)
colors = colors if ni == 0 else colors[::-1]
node.attr['fillcolor'] = ':'.join(colors)
node.attr['style'] = 'filled'
node.attr["fillcolor"] = ":".join(colors)
node.attr["style"] = "filled"
del node
g.get_node('legend').attr.update(shape='plaintext', margin=0, rank='sink')
g.get_node("legend").attr.update(shape="plaintext", margin=0, rank="sink")
# put legend in same rank/level as inverse
leg = g.add_subgraph(['legend', 'inv'], name='legendy')
leg.graph_attr['rank'] = 'same'
leg = g.add_subgraph(["legend", "inv"], name="legendy")
leg.graph_attr["rank"] = "same"

g.layout('dot')
g.draw(out_fname, format='svg')
g.layout("dot")
g.draw(out_fname, format="svg")
return g


# This is useful for testing/iterating to see what the result looks like
if __name__ == '__main__':
if __name__ == "__main__":
from mne.io.constants import Bunch
out_dir = op.abspath(op.join(op.dirname(__file__), '..', '_build', 'html'))
app = Bunch(builder=Bunch(outdir=out_dir,
config=Bunch(make_flow_diagram=True)))

out_dir = op.abspath(op.join(op.dirname(__file__), "..", "_build", "html"))
app = Bunch(builder=Bunch(outdir=out_dir, config=Bunch(make_flow_diagram=True)))
g = generate_flow_diagram(app)
52 changes: 27 additions & 25 deletions doc/sphinxext/gen_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@


def setup(app):
app.connect('builder-inited', generate_commands_rst)
app.connect("builder-inited", generate_commands_rst)


def setup_module():
Expand Down Expand Up @@ -52,23 +52,24 @@ def generate_commands_rst(app=None):
except Exception:
from sphinx.util import status_iterator
root = Path(__file__).parent.parent.parent.absolute()
out_dir = (root / 'doc' / 'generated').absolute()
out_dir = (root / "doc" / "generated").absolute()
out_dir.mkdir(exist_ok=True)
out_fname =out_dir / 'commands.rst.new'
out_fname = out_dir / "commands.rst.new"

command_path = root / 'mne' / 'commands'
command_path = root / "mne" / "commands"
fnames = sorted(
Path(fname).name
for fname in glob.glob(str(command_path / 'mne_*.py')))
Path(fname).name for fname in glob.glob(str(command_path / "mne_*.py"))
)
assert len(fnames)
iterator = status_iterator(
fnames, 'generating MNE command help ... ', length=len(fnames))
with open(out_fname, 'w', encoding='utf8') as f:
fnames, "generating MNE command help ... ", length=len(fnames)
)
with open(out_fname, "w", encoding="utf8") as f:
f.write(header)
for fname in iterator:
cmd_name = fname[:-3]
module = import_module('.' + cmd_name, 'mne.commands')
with ArgvSetter(('mne', cmd_name, '--help')) as out:
module = import_module("." + cmd_name, "mne.commands")
with ArgvSetter(("mne", cmd_name, "--help")) as out:
try:
module.run()
except SystemExit: # this is how these terminate
Expand All @@ -80,29 +81,30 @@ def generate_commands_rst(app=None):

# Add header marking
for idx in (1, 0):
output.insert(idx, '-' * len(output[0]))
output.insert(idx, "-" * len(output[0]))

# Add code styling for the "Usage: " line
for li, line in enumerate(output):
if line.startswith('Usage: mne '):
output[li] = 'Usage: ``%s``' % line[7:]
if line.startswith("Usage: mne "):
output[li] = "Usage: ``%s``" % line[7:]
break

# Turn "Options:" into field list
if 'Options:' in output:
ii = output.index('Options:')
output[ii] = 'Options'
output.insert(ii + 1, '-------')
output.insert(ii + 2, '')
output.insert(ii + 3, '.. rst-class:: field-list cmd-list')
output.insert(ii + 4, '')
output = '\n'.join(output)
cmd_name_space = cmd_name.replace('mne_', 'mne ')
f.write(command_rst.format(
cmd_name_space, '=' * len(cmd_name_space), output))
if "Options:" in output:
ii = output.index("Options:")
output[ii] = "Options"
output.insert(ii + 1, "-------")
output.insert(ii + 2, "")
output.insert(ii + 3, ".. rst-class:: field-list cmd-list")
output.insert(ii + 4, "")
output = "\n".join(output)
cmd_name_space = cmd_name.replace("mne_", "mne ")
f.write(
command_rst.format(cmd_name_space, "=" * len(cmd_name_space), output)
)
_replace_md5(str(out_fname))


# This is useful for testing/iterating to see what the result looks like
if __name__ == '__main__':
if __name__ == "__main__":
generate_commands_rst()
21 changes: 11 additions & 10 deletions doc/sphinxext/gen_names.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@


def setup(app):
app.connect('builder-inited', generate_name_links_rst)
app.connect("builder-inited", generate_name_links_rst)


def setup_module():
Expand All @@ -12,17 +12,18 @@ def setup_module():


def generate_name_links_rst(app=None):
if 'linkcheck' not in str(app.builder).lower():
if "linkcheck" not in str(app.builder).lower():
return
out_dir = op.abspath(op.join(op.dirname(__file__), '..', 'generated'))
out_dir = op.abspath(op.join(op.dirname(__file__), "..", "generated"))
if not op.isdir(out_dir):
os.mkdir(out_dir)
out_fname = op.join(out_dir, '_names.rst')
out_fname = op.join(out_dir, "_names.rst")
names_path = op.abspath(
op.join(os.path.dirname(__file__), '..', 'changes', 'names.inc'))
with open(out_fname, 'w', encoding='utf8') as fout:
fout.write(':orphan:\n\n')
with open(names_path, 'r') as fin:
op.join(os.path.dirname(__file__), "..", "changes", "names.inc")
)
with open(out_fname, "w", encoding="utf8") as fout:
fout.write(":orphan:\n\n")
with open(names_path, "r") as fin:
for line in fin:
if line.startswith('.. _'):
fout.write(f'- {line[4:]}')
if line.startswith(".. _"):
fout.write(f"- {line[4:]}")
Loading

0 comments on commit e81ec52

Please sign in to comment.