diff --git a/.gitignore b/.gitignore index f3d74a9a..68ac5829 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ *.pyc *~ +*build/* diff --git a/dmipy/core/modeling_framework.py b/dmipy/core/modeling_framework.py index 9f901c4d..e4be0f49 100644 --- a/dmipy/core/modeling_framework.py +++ b/dmipy/core/modeling_framework.py @@ -3,34 +3,26 @@ Document Module ''' from __future__ import division -import pkg_resources -from collections import OrderedDict +import collections +from dipy.utils import optpkg import numpy as np -from time import time - -from ..utils.spherical_mean import ( - estimate_spherical_mean_multi_shell) -from ..utils.utils import ( - T1_tortuosity, - parameter_equality, - fractional_parameter) -from .fitted_modeling_framework import ( - FittedMultiCompartmentModel, - FittedMultiCompartmentSphericalMeanModel, - FittedMultiCompartmentSphericalHarmonicsModel) -from ..optimizers.brute2fine import ( - GlobalBruteOptimizer, Brute2FineOptimizer) -from ..optimizers_fod.csd_tournier import CsdTournierOptimizer -from ..optimizers_fod.csd_cvxpy import CsdCvxpyOptimizer -from ..optimizers.mix import MixOptimizer -from ..optimizers.multi_tissue_convex_optimizer import ( - MultiTissueConvexOptimizer) -from dipy.utils.optpkg import optional_package -from uuid import uuid4 -pathos, have_pathos, _ = optional_package("pathos") -numba, have_numba, _ = optional_package("numba") -graphviz, have_graphviz, _ = optional_package("graphviz") +import pkg_resources +import time +import uuid + +from dmipy.utils import spherical_mean +from dmipy.utils import utils +from dmipy.core import fitted_modeling_framework +from dmipy.optimizers import brute2fine +from dmipy.optimizers_fod import csd_tournier +from dmipy.optimizers_fod import csd_cvxpy +from dmipy.optimizers import mix +from dmipy.optimizers import multi_tissue_convex_optimizer + +pathos, have_pathos, _ = optpkg.optional_package("pathos") +numba, have_numba, _ = optpkg.optional_package("numba") +graphviz, have_graphviz, _ = optpkg.optional_package("graphviz") if have_graphviz: from graphviz import Digraph @@ -67,7 +59,7 @@ def parameter_ranges(self): These ranges are given in O(1) scale so optimization algorithms don't suffer from large scale differences in optimization parameters. """ - return OrderedDict(self._parameter_ranges.copy()) + return collections.OrderedDict(self._parameter_ranges.copy()) @property def parameter_scales(self): @@ -75,7 +67,7 @@ def parameter_scales(self): The scales scale the parameter_ranges to their actual size inside optimization algorithms. """ - return OrderedDict(self._parameter_scales.copy()) + return collections.OrderedDict(self._parameter_scales.copy()) @property def parameter_types(self): @@ -83,7 +75,7 @@ def parameter_types(self): The scales scale the parameter_ranges to their actual size inside optimization algorithms. """ - return OrderedDict(self._parameter_types.copy()) + return collections.OrderedDict(self._parameter_types.copy()) @property def parameter_names(self): @@ -93,7 +85,7 @@ def parameter_names(self): @property def parameter_cardinality(self): "Returns the cardinality of model parameters" - return OrderedDict([ + return collections.OrderedDict([ (k, len(np.atleast_2d(self.parameter_ranges[k]))) for k in self.parameter_ranges ]) @@ -254,19 +246,19 @@ def _prepare_parameters(self): ) ) - self.parameter_ranges = OrderedDict({ + self.parameter_ranges = collections.OrderedDict({ model_name + k: v for model, model_name in zip(self.models, self.model_names) for k, v in model.parameter_ranges.items() }) - self.parameter_scales = OrderedDict({ + self.parameter_scales = collections.OrderedDict({ model_name + k: v for model, model_name in zip(self.models, self.model_names) for k, v in model.parameter_scales.items() }) - self.parameter_types = OrderedDict({ + self.parameter_types = collections.OrderedDict({ model_name + k: v for model, model_name in zip(self.models, self.model_names) for k, v in model.parameter_types.items() @@ -282,7 +274,7 @@ def _prepare_parameters(self): v: k for k, v in self._parameter_map.items() } - self.parameter_cardinality = OrderedDict([ + self.parameter_cardinality = collections.OrderedDict([ (k, len(np.atleast_2d(self.parameter_ranges[k]))) for k in self.parameter_ranges ]) @@ -397,7 +389,7 @@ def _check_if_volume_fractions_are_fixed(self): def _prepare_parameters_to_optimize(self): "Sets up which parmameters to optimize." - self.parameter_optimization_flags = OrderedDict({ + self.parameter_optimization_flags = collections.OrderedDict({ k: True for k, v in self.parameter_cardinality.items() }) @@ -436,7 +428,7 @@ def scales_for_optimization(self): def _check_for_tortuosity_constraint(self): for link in self.parameter_links: - if link[2] is T1_tortuosity: + if link[2] is utils.T1_tortuosity: msg = "Cannot use MIX optimization when the Tortuosity " msg += "constraint is set in the MultiCompartmentModel. To " msg += "use MIX while imposing Tortuosity, set the constraint " @@ -595,7 +587,7 @@ def set_tortuous_parameter(self, lambda_perp_parameter_name, raise ValueError(msg) model, name = self._parameter_map[lambda_perp_parameter_name] - self.parameter_links.append([model, name, T1_tortuosity, [ + self.parameter_links.append([model, name, utils.T1_tortuosity, [ self._parameter_map[lambda_par_parameter_name], self._parameter_map[volume_fraction_intra_parameter_name], self._parameter_map[volume_fraction_extra_parameter_name]] @@ -632,7 +624,7 @@ def set_equal_parameter(self, parameter_name_in, parameter_name_out): param) raise ValueError(msg) model, name = self._parameter_map[parameter_name_out] - self.parameter_links.append([model, name, parameter_equality, [ + self.parameter_links.append([model, name, utils.parameter_equality, [ self._parameter_map[parameter_name_in]]]) del self.parameter_ranges[parameter_name_out] del self.parameter_cardinality[parameter_name_out] @@ -670,7 +662,7 @@ def set_fractional_parameter(self, self._add_optimization_parameter( new_parameter_name, [0., 1.], 1., 1, 'normal', True) model, name = self._parameter_map[parameter1_smaller_equal_than] - self.parameter_links.append([model, name, fractional_parameter, [ + self.parameter_links.append([model, name, utils.fractional_parameter, [ self._parameter_map[new_parameter_name], self._parameter_map[parameter2]]]) @@ -699,12 +691,15 @@ def _add_optimization_parameter( old_parameter_types = self.parameter_types old_optimization_flags = self.parameter_optimization_flags - self.parameter_ranges = OrderedDict({parameter_name: parameter_range}) - self.parameter_scales = OrderedDict({parameter_name: parameter_scale}) - self.parameter_cardinality = OrderedDict( + self.parameter_ranges = collections.OrderedDict( + {parameter_name: parameter_range}) + self.parameter_scales = collections.OrderedDict( + {parameter_name: parameter_scale}) + self.parameter_cardinality = collections.OrderedDict( {parameter_name: parameter_card}) - self.parameter_types = OrderedDict({parameter_name: parameter_type}) - self.parameter_optimization_flags = OrderedDict( + self.parameter_types = collections.OrderedDict( + {parameter_name: parameter_type}) + self.parameter_optimization_flags = collections.OrderedDict( {parameter_name: parameter_flag}) for name, _ in old_parameter_ranges.items(): @@ -760,7 +755,7 @@ def visualize_model_setup( raise ImportError('graphviz package not installed.') dot = Digraph('Model Setup', format=im_format) base_model = self.__class__.__name__ - base_uuid = str(uuid4()) + base_uuid = str(uuid.uuid4()) dot.node(base_uuid, base_model) self._add_recursive_graph_node(dot, base_uuid, self, with_parameters) dot.render('Model Setup', view=view, cleanup=cleanup) @@ -785,7 +780,7 @@ def _add_recursive_graph_node( """ for sub_model in entry_model.models: model_name = sub_model.__class__.__name__ - model_uuid = str(uuid4()) + model_uuid = str(uuid.uuid4()) graph_model.node(model_uuid, model_name) graph_model.edge(model_uuid, entry_uuid) if (sub_model._model_type == 'SphericalDistributedModel' or @@ -797,7 +792,7 @@ def _add_recursive_graph_node( self._add_parameter_nodes(graph_model, model_uuid, sub_model) if hasattr(entry_model, 'distribution'): dist_name = entry_model.distribution.__class__.__name__ - dist_uuid = str(uuid4()) + dist_uuid = str(uuid.uuid4()) graph_model.node(dist_uuid, dist_name) graph_model.edge(dist_uuid, entry_uuid) if with_parameters: @@ -819,7 +814,7 @@ def _add_parameter_nodes(self, graph_model, entry_uuid, entry_model): Entry dmipy model from which to keep growing the graph. """ for parameter_name in entry_model.parameter_names: - parameter_uuid = str(uuid4()) + parameter_uuid = str(uuid.uuid4()) graph_model.node(parameter_uuid, parameter_name) graph_model.edge(parameter_uuid, entry_uuid) @@ -1168,24 +1163,24 @@ def fit(self, acquisition_scheme, data, fitted_parameters_lin = np.empty( np.r_[N_voxels, N_parameters], dtype=float) - start = time() + start = time.time() if solver == 'brute2fine': - global_brute = GlobalBruteOptimizer( + global_brute = brute2fine.GlobalBruteOptimizer( self, self.scheme, x0_, Ns, N_sphere_samples) - fit_func = Brute2FineOptimizer(self, self.scheme, Ns) + fit_func = brute2fine.Brute2FineOptimizer(self, self.scheme, Ns) print('Setup brute2fine optimizer in {} seconds'.format( - time() - start)) + time.time() - start)) elif solver == 'mix': self._check_for_tortuosity_constraint() - fit_func = MixOptimizer(self, self.scheme, maxiter) + fit_func = mix.MixOptimizer(self, self.scheme, maxiter) print('Setup MIX optimizer in {} seconds'.format( - time() - start)) + time.time() - start)) else: msg = "Unknown solver name {}".format(solver) raise ValueError(msg) self.optimizer = fit_func - start = time() + start = time.time() for idx, pos in enumerate(zip(*mask_pos)): voxel_E = data_[pos] / S0[pos] voxel_x0_vector = x0_[pos] @@ -1205,7 +1200,7 @@ def fit(self, acquisition_scheme, data, pool.join() pool.clear() - fitting_time = time() - start + fitting_time = time.time() - start print('Fitting of {} voxels complete in {} seconds.'.format( len(fitted_parameters_lin), fitting_time)) print('Average of {} seconds per voxel.'.format( @@ -1215,16 +1210,17 @@ def fit(self, acquisition_scheme, data, if self.S0_tissue_responses: # secondary fitting including S0 responses print('Starting secondary multi-tissue optimization.') - start = time() + start = time.time() mt_fractions = np.empty( np.r_[N_voxels, self.N_models], dtype=float) - fit_func = MultiTissueConvexOptimizer( - acquisition_scheme, self, self.S0_tissue_responses) + fit_func = multi_tissue_convex_optimizer.\ + MultiTissueConvexOptimizer( + acquisition_scheme, self, self.S0_tissue_responses) for idx, pos in enumerate(zip(*mask_pos)): voxel_S = data_[pos] parameters = fitted_parameters_lin[idx] mt_fractions[idx] = fit_func(voxel_S, parameters) - fitting_time = time() - start + fitting_time = time.time() - start msg = 'Multi-tissue fitting of {} voxels complete in {} seconds.' print(msg.format(len(mt_fractions), fitting_time)) fitted_mt_fractions = np.zeros(np.r_[mask.shape, self.N_models]) @@ -1234,7 +1230,7 @@ def fit(self, acquisition_scheme, data, fitted_parameters[mask_pos] = ( fitted_parameters_lin * self.scales_for_optimization) - return FittedMultiCompartmentModel( + return fitted_modeling_framework.FittedMultiCompartmentModel( self, S0, mask, fitted_parameters, fitted_mt_fractions) def simulate_signal(self, acquisition_scheme, parameters_array_or_dict): @@ -1566,28 +1562,29 @@ def fit(self, acquisition_scheme, data, # estimate the spherical mean of the data. data_to_fit = np.zeros(np.r_[data_.shape[:-1], self.scheme.N_shells]) for pos in zip(*mask_pos): - data_to_fit[pos] = estimate_spherical_mean_multi_shell( - data_[pos], self.scheme) + data_to_fit[pos] = \ + spherical_mean.estimate_spherical_mean_multi_shell( + data_[pos], self.scheme) - start = time() + start = time.time() if solver == 'brute2fine': - global_brute = GlobalBruteOptimizer( + global_brute = brute2fine.GlobalBruteOptimizer( self, self.scheme, x0_, Ns, N_sphere_samples) - fit_func = Brute2FineOptimizer(self, self.scheme, Ns) + fit_func = brute2fine.Brute2FineOptimizer(self, self.scheme, Ns) print('Setup brute2fine optimizer in {} seconds'.format( - time() - start)) + time.time() - start)) elif solver == 'mix': self._check_for_tortuosity_constraint() - fit_func = MixOptimizer(self, self.scheme, maxiter) + fit_func = mix.MixOptimizer(self, self.scheme, maxiter) print('Setup MIX optimizer in {} seconds'.format( - time() - start)) + time.time() - start)) else: msg = "Unknown solver name {}".format(solver) raise ValueError(msg) self.optimizer = fit_func - start = time() + start = time.time() for idx, pos in enumerate(zip(*mask_pos)): voxel_E = data_to_fit[pos] / S0[pos] voxel_x0_vector = x0_[pos] @@ -1607,7 +1604,7 @@ def fit(self, acquisition_scheme, data, pool.join() pool.clear() - fitting_time = time() - start + fitting_time = time.time() - start print('Fitting of {} voxels complete in {} seconds.'.format( len(fitted_parameters_lin), fitting_time)) print('Average of {} seconds per voxel.'.format( @@ -1617,16 +1614,17 @@ def fit(self, acquisition_scheme, data, if self.S0_tissue_responses: # secondary fitting including S0 responses print('Starting secondary multi-tissue optimization.') - start = time() + start = time.time() mt_fractions = np.empty( np.r_[N_voxels, self.N_models], dtype=float) - fit_func = MultiTissueConvexOptimizer( - acquisition_scheme, self, self.S0_tissue_responses) + fit_func = multi_tissue_convex_optimizer.\ + MultiTissueConvexOptimizer( + acquisition_scheme, self, self.S0_tissue_responses) for idx, pos in enumerate(zip(*mask_pos)): voxel_S = data_to_fit[pos] parameters = fitted_parameters_lin[idx] mt_fractions[idx] = fit_func(voxel_S, parameters) - fitting_time = time() - start + fitting_time = time.time() - start msg = 'Multi-tissue fitting of {} voxels complete in {} seconds.' print(msg.format(len(mt_fractions), fitting_time)) fitted_mt_fractions = np.zeros(np.r_[mask.shape, self.N_models]) @@ -1636,8 +1634,9 @@ def fit(self, acquisition_scheme, data, fitted_parameters[mask_pos] = ( fitted_parameters_lin * self.scales_for_optimization) - return FittedMultiCompartmentSphericalMeanModel( - self, S0, mask, fitted_parameters, fitted_mt_fractions) + return fitted_modeling_framework.\ + FittedMultiCompartmentSphericalMeanModel( + self, S0, mask, fitted_parameters, fitted_mt_fractions) def simulate_signal(self, acquisition_scheme, parameters_array_or_dict): """ @@ -2006,10 +2005,10 @@ def fit(self, acquisition_scheme, data, mask=None, solver='csd', x0_ = homogenize_x0_to_data( data_, x0_) - start = time() + start = time.time() if solver == 'csd': if self.volume_fractions_fixed: - fit_func = CsdTournierOptimizer( + fit_func = csd_tournier.CsdTournierOptimizer( acquisition_scheme, self, x0_, self.sh_order, unity_constraint=self.unity_constraint, lambda_lb=lambda_lb) @@ -2023,17 +2022,17 @@ def fit(self, acquisition_scheme, data, mask=None, solver='csd', if verbose: print( 'Setup Tournier07 FOD optimizer in {} seconds'.format( - time() - start)) + time.time() - start)) else: - fit_func = CsdCvxpyOptimizer( + fit_func = csd_cvxpy.CsdCvxpyOptimizer( acquisition_scheme, self, x0_, self.sh_order, unity_constraint=self.unity_constraint, lambda_lb=lambda_lb) if verbose: print('Setup CVXPY FOD optimizer in {} seconds'.format( - time() - start)) + time.time() - start)) elif solver == 'csd_tournier07': - fit_func = CsdTournierOptimizer( + fit_func = csd_tournier.CsdTournierOptimizer( acquisition_scheme, self, x0_, self.sh_order, unity_constraint=self.unity_constraint, lambda_lb=lambda_lb) if use_parallel_processing: @@ -2044,14 +2043,14 @@ def fit(self, acquisition_scheme, data, mask=None, solver='csd', use_parallel_processing = False if verbose: print('Setup Tournier07 FOD optimizer in {} seconds'.format( - time() - start)) + time.time() - start)) elif solver == 'csd_cvxpy': - fit_func = CsdCvxpyOptimizer( + fit_func = csd_cvxpy.CsdCvxpyOptimizer( acquisition_scheme, self, x0_, self.sh_order, unity_constraint=self.unity_constraint, lambda_lb=lambda_lb) if verbose: print('Setup CVXPY FOD optimizer in {} seconds'.format( - time() - start)) + time.time() - start)) else: msg = "Unknown solver name {}".format(solver) raise ValueError(msg) @@ -2073,7 +2072,7 @@ def fit(self, acquisition_scheme, data, mask=None, solver='csd', fitted_parameters_lin = np.empty( np.r_[N_voxels, N_parameters], dtype=float) - start = time() + start = time.time() for idx, pos in enumerate(zip(*mask_pos)): if fit_S0_response: data_to_fit = data_[pos] / self.max_S0_response @@ -2093,7 +2092,7 @@ def fit(self, acquisition_scheme, data, mask=None, solver='csd', pool.join() pool.clear() - fitting_time = time() - start + fitting_time = time.time() - start if verbose: print('Fitting of {} voxels complete in {} seconds.'.format( len(fitted_parameters_lin), fitting_time)) @@ -2102,8 +2101,9 @@ def fit(self, acquisition_scheme, data, mask=None, solver='csd', fitted_parameters = np.zeros_like(x0_, dtype=float) fitted_parameters[mask_pos] = fitted_parameters_lin - return FittedMultiCompartmentSphericalHarmonicsModel( - self, S0, mask, fitted_parameters) + return fitted_modeling_framework.\ + FittedMultiCompartmentSphericalHarmonicsModel( + self, S0, mask, fitted_parameters) def simulate_signal(self, acquisition_scheme, parameters_array_or_dict): """ diff --git a/doc/Makefile b/doc/Makefile deleted file mode 100644 index 02359892..00000000 --- a/doc/Makefile +++ /dev/null @@ -1,179 +0,0 @@ -# Makefile for Sphinx documentation -# - -# You can set these variables from the command line. -SPHINXOPTS = -SPHINXBUILD = sphinx-build -PAPER = -BUILDDIR = _build - -# User-friendly check for sphinx-build -ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) -$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) -endif - -# Internal variables. -PAPEROPT_a4 = -D latex_paper_size=a4 -PAPEROPT_letter = -D latex_paper_size=letter -ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . -# the i18n builder cannot share the environment and doctrees with the others -I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . - -.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext - -help: - @echo "Please use \`make ' where is one of" - @echo " html to make standalone HTML files" - @echo " dirhtml to make HTML files named index.html in directories" - @echo " singlehtml to make a single large HTML file" - @echo " pickle to make pickle files" - @echo " json to make JSON files" - @echo " htmlhelp to make HTML files and a HTML help project" - @echo " qthelp to make HTML files and a qthelp project" - @echo " devhelp to make HTML files and a Devhelp project" - @echo " epub to make an epub" - @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" - @echo " latexpdf to make LaTeX files and run them through pdflatex" - @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" - @echo " text to make text files" - @echo " man to make manual pages" - @echo " texinfo to make Texinfo files" - @echo " info to make Texinfo files and run them through makeinfo" - @echo " gettext to make PO message catalogs" - @echo " changes to make an overview of all changed/added/deprecated items" - @echo " xml to make Docutils-native XML files" - @echo " pseudoxml to make pseudoxml-XML files for display purposes" - @echo " linkcheck to check all external links for integrity" - @echo " doctest to run all doctests embedded in the documentation (if enabled)" - - -clean: - rm -rf $(BUILDDIR)/* - rm -rf reference/* - -html: - $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html - @echo - @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." - -dirhtml: - $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml - @echo - @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." - -singlehtml: - $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml - @echo - @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." - -pickle: - $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle - @echo - @echo "Build finished; now you can process the pickle files." - -json: - $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json - @echo - @echo "Build finished; now you can process the JSON files." - -htmlhelp: - $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp - @echo - @echo "Build finished; now you can run HTML Help Workshop with the" \ - ".hhp project file in $(BUILDDIR)/htmlhelp." - -qthelp: - $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp - @echo - @echo "Build finished; now you can run "qcollectiongenerator" with the" \ - ".qhcp project file in $(BUILDDIR)/qthelp, like this:" - @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/microstruktur.qhcp" - @echo "To view the help file:" - @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/microstruktur.qhc" - -devhelp: - $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp - @echo - @echo "Build finished." - @echo "To view the help file:" - @echo "# mkdir -p $$HOME/.local/share/devhelp/microstruktur" - @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/microstruktur" - @echo "# devhelp" - -epub: - $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub - @echo - @echo "Build finished. The epub file is in $(BUILDDIR)/epub." - -latex: - $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex - @echo - @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." - @echo "Run \`make' in that directory to run these through (pdf)latex" \ - "(use \`make latexpdf' here to do that automatically)." - -latexpdf: - $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex - @echo "Running LaTeX files through pdflatex..." - $(MAKE) -C $(BUILDDIR)/latex all-pdf - @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." - -latexpdfja: - $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex - @echo "Running LaTeX files through platex and dvipdfmx..." - $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja - @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." - -text: - $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text - @echo - @echo "Build finished. The text files are in $(BUILDDIR)/text." - -man: - $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man - @echo - @echo "Build finished. The manual pages are in $(BUILDDIR)/man." - -texinfo: - $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo - @echo - @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." - @echo "Run \`make' in that directory to run these through makeinfo" \ - "(use \`make info' here to do that automatically)." - -info: - $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo - @echo "Running Texinfo files through makeinfo..." - make -C $(BUILDDIR)/texinfo info - @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." - -gettext: - $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale - @echo - @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." - -changes: - $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes - @echo - @echo "The overview file is in $(BUILDDIR)/changes." - -linkcheck: - $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck - @echo - @echo "Link check complete; look for any errors in the above output " \ - "or in $(BUILDDIR)/linkcheck/output.txt." - -doctest: - $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest - @echo "Testing of doctests in the sources finished, look at the " \ - "results in $(BUILDDIR)/doctest/output.txt." - -xml: - $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml - @echo - @echo "Build finished. The XML files are in $(BUILDDIR)/xml." - -pseudoxml: - $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml - @echo - @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." diff --git a/doc/_static/.!84647!git.png b/doc/_static/.!84647!git.png deleted file mode 100644 index e69de29b..00000000 diff --git a/doc/_static/.!84648!RTD-advanced-conf.png b/doc/_static/.!84648!RTD-advanced-conf.png deleted file mode 100644 index e69de29b..00000000 diff --git a/doc/_static/.!85069!git.png b/doc/_static/.!85069!git.png deleted file mode 100644 index e69de29b..00000000 diff --git a/doc/_static/.!85070!RTD-advanced-conf.png b/doc/_static/.!85070!RTD-advanced-conf.png deleted file mode 100644 index e69de29b..00000000 diff --git a/doc/_static/RTD-advanced-conf.png b/doc/_static/RTD-advanced-conf.png deleted file mode 100644 index ae066a74..00000000 Binary files a/doc/_static/RTD-advanced-conf.png and /dev/null differ diff --git a/doc/_static/git.png b/doc/_static/git.png deleted file mode 100644 index dcd84202..00000000 Binary files a/doc/_static/git.png and /dev/null differ diff --git a/doc/conf.py b/doc/conf.py deleted file mode 100755 index 60d61ec0..00000000 --- a/doc/conf.py +++ /dev/null @@ -1,307 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- -# -# dmipy documentation build configuration file, created by -# sphinx-quickstart on Tue Apr 14 10:29:06 2015. -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os - -# General information about the project. -project = 'dmipy' -copyright = '2017, Rutger Fick and Demian Wassermann' - -currentdir = os.path.abspath(os.path.dirname(__file__)) -ver_file = os.path.join(currentdir, '..', project, 'version.py') -with open(ver_file) as f: - exec(f.read()) -source_version = __version__ - -currentdir = os.path.abspath(os.path.dirname(__file__)) -sys.path.append(os.path.join(currentdir, 'tools')) -import buildmodref - -# autogenerate api documentation -# (see https://github.com/rtfd/readthedocs.org/issues/1139) -def generateapidoc(_): - output_path = os.path.join(currentdir, 'reference') - buildmodref.writeapi(project, output_path, source_version, True) - -def setup(app): - app.connect('builder-inited', generateapidoc) - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath('../')) - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = '1.0' # numpydoc requires sphinc >= 1.0 - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -sys.path.append(os.path.abspath('sphinxext')) - -extensions = [ - 'sphinx.ext.autodoc', - #'sphinx.ext.doctest', - #'sphinx.ext.intersphinx', - #'sphinx.ext.todo', - #'sphinx.ext.coverage', - #'sphinx.ext.ifconfig', - #'sphinx.ext.autosummary', - 'sphinx.ext.mathjax', - 'math_dollar', # has to go before numpydoc - 'numpydoc', - #'github', - # 'sphinx_gallery.gen_gallery' - ] - -# Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] - -# The suffix of source filenames. -source_suffix = '.rst' - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The master toctree document. -master_doc = 'index' - -# --- Sphinx Gallery --- -sphinx_gallery_conf = { - # path to your examples scripts - 'examples_dirs': '../examples', - # path where to save gallery generated examples - 'gallery_dirs': 'auto_examples'} - - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The short X.Y version. -version = '0.1' -# The full version, including alpha/beta/rc tags. -release = '0.1' - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -#language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -#today = '' -# Else, today_fmt is used as the format for a strftime call. -#today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ['_build'] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -#default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -#add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -#add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -#show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'sphinx' - -# A list of ignored prefixes for module index sorting. -#modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -#keep_warnings = False - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = 'sphinxdoc' - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -#html_theme_options = {} - -# Add any paths that contain custom themes here, relative to this directory. -#html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -#html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -#html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -#html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -#html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ['_static'] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -#html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -#html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -#html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -#html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -#html_additional_pages = {} - -# If false, no module index is generated. -#html_domain_indices = True -html_domain_indices = False - -# If false, no index is generated. -#html_use_index = True - -# If true, the index is split into individual pages for each letter. -#html_split_index = False - -# If true, links to the reST sources are added to the pages. -#html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -#html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -#html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -#html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -#html_file_suffix = None - -# Output file base name for HTML help builder. -htmlhelp_basename = 'dmipydoc' - - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { -# The paper size ('letterpaper' or 'a4paper'). -#'papersize': 'letterpaper', - -# The font size ('10pt', '11pt' or '12pt'). -#'pointsize': '10pt', - -# Additional stuff for the LaTeX preamble. -#'preamble': '', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ('index', 'dmipy.tex', 'dmipy Documentation', - 'Rutger Fick, Demian Wassermann', 'manual'), -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -#latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -#latex_use_parts = False - -# If true, show page references after internal links. -#latex_show_pagerefs = False - -# If true, show URL addresses after external links. -#latex_show_urls = False - -# Documents to append as an appendix to all manuals. -#latex_appendices = [] - -# If false, no module index is generated. -#latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ('index', 'dmipy', 'dmipy Documentation', - ['Rutger Fick, Demian Wassermann'], 1) -] - -# If true, show URL addresses after external links. -#man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ('index', 'dmipy', 'dmipy Documentation', - 'Rutger Fick, Demian Wassermann', 'dmipy', 'One line description of project.', - 'Miscellaneous'), -] - -# Documents to append as an appendix to all manuals. -#texinfo_appendices = [] - -# If false, no module index is generated. -texinfo_domain_indices = False - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -#texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -#texinfo_no_detailmenu = False - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = {'http://docs.python.org/': None} - -autodoc_default_flags = ['members', 'undoc-members'] diff --git a/doc/index.rst b/doc/index.rst deleted file mode 100644 index 7cf5b262..00000000 --- a/doc/index.rst +++ /dev/null @@ -1,26 +0,0 @@ -.. microstruktur documentation master file, created by sphinx-quickstart on Tue Apr 14 10:29:06 2015. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. - -Welcome to dmipy's documentation! -==================================== - -The dmipy software package facilitates state-of-the-art diffusion MRI Microstructure Imaging using a "Building Block" philosophy. In this philosophy, any combination of biophysical models, typically representing intra- and/or extra-axonal tissue compartments, can be easy combined into a multi-compartment Microstructure Model in just a few lines of code. - -To see how to use it, please refer to the `README file -`_ in the Github repository. - - -Contents: - -.. toctree:: - :maxdepth: 2 - - auto_examples/index - reference/index - -Indices and tables -================== - -* :ref:`genindex` -* :ref:`modindex` -* :ref:`search` - diff --git a/doc/push.sh b/doc/push.sh deleted file mode 100755 index cd990b00..00000000 --- a/doc/push.sh +++ /dev/null @@ -1,33 +0,0 @@ -#!/usr/bin/env bash -# Push HTML files to gh-pages automatically. - -# Fill this out with the correct org/repo -ORG=AthenaEPI -REPO=dmipy -# This probably should match an email for one of your users. -EMAIL=demian.wassermann@inria.fr - -set -e - -# Clone the gh-pages branch outside of the repo and cd into it. -cd .. -git clone -b gh-pages "https://$GH_TOKEN@github.com/$ORG/$REPO.git" gh-pages -cd gh-pages - -# Update git configuration so I can push. -if [ "$1" != "dry" ]; then - # Update git config. - git config user.name "Travis Builder" - git config user.email "$EMAIL" -fi - -# Copy in the HTML. You may want to change this with your documentation path. -cp -R ../$REPO/_build/html/* ./ - -# Add and commit changes. -git add -A . -git commit -m "[ci skip] Autodoc commit for $COMMIT." -if [ "$1" != "dry" ]; then - # -q is very important, otherwise you leak your GH_TOKEN - git push -q origin gh-pages -fi diff --git a/doc/reference/.gitignore b/doc/reference/.gitignore deleted file mode 100644 index 30d85567..00000000 --- a/doc/reference/.gitignore +++ /dev/null @@ -1 +0,0 @@ -*.rst diff --git a/doc/sphinxext/docscrape.py b/doc/sphinxext/docscrape.py deleted file mode 100644 index 470badd3..00000000 --- a/doc/sphinxext/docscrape.py +++ /dev/null @@ -1,570 +0,0 @@ -"""Extract reference documentation from the NumPy source tree. - -""" -from __future__ import division, absolute_import, print_function - -import inspect -import textwrap -import re -import pydoc -from warnings import warn -import collections -import sys - - -class Reader(object): - """A line-based string reader. - - """ - def __init__(self, data): - """ - Parameters - ---------- - data : str - String with lines separated by '\n'. - - """ - if isinstance(data, list): - self._str = data - else: - self._str = data.split('\n') # store string as list of lines - - self.reset() - - def __getitem__(self, n): - return self._str[n] - - def reset(self): - self._l = 0 # current line nr - - def read(self): - if not self.eof(): - out = self[self._l] - self._l += 1 - return out - else: - return '' - - def seek_next_non_empty_line(self): - for l in self[self._l:]: - if l.strip(): - break - else: - self._l += 1 - - def eof(self): - return self._l >= len(self._str) - - def read_to_condition(self, condition_func): - start = self._l - for line in self[start:]: - if condition_func(line): - return self[start:self._l] - self._l += 1 - if self.eof(): - return self[start:self._l+1] - return [] - - def read_to_next_empty_line(self): - self.seek_next_non_empty_line() - - def is_empty(line): - return not line.strip() - - return self.read_to_condition(is_empty) - - def read_to_next_unindented_line(self): - def is_unindented(line): - return (line.strip() and (len(line.lstrip()) == len(line))) - return self.read_to_condition(is_unindented) - - def peek(self, n=0): - if self._l + n < len(self._str): - return self[self._l + n] - else: - return '' - - def is_empty(self): - return not ''.join(self._str).strip() - - -class NumpyDocString(collections.Mapping): - def __init__(self, docstring, config={}): - docstring = textwrap.dedent(docstring).split('\n') - - self._doc = Reader(docstring) - self._parsed_data = { - 'Signature': '', - 'Summary': [''], - 'Extended Summary': [], - 'Parameters': [], - 'Returns': [], - 'Yields': [], - 'Raises': [], - 'Warns': [], - 'Other Parameters': [], - 'Attributes': [], - 'Methods': [], - 'See Also': [], - 'Notes': [], - 'Warnings': [], - 'References': '', - 'Examples': '', - 'index': {} - } - - self._parse() - - def __getitem__(self, key): - return self._parsed_data[key] - - def __setitem__(self, key, val): - if key not in self._parsed_data: - warn("Unknown section %s" % key) - else: - self._parsed_data[key] = val - - def __iter__(self): - return iter(self._parsed_data) - - def __len__(self): - return len(self._parsed_data) - - def _is_at_section(self): - self._doc.seek_next_non_empty_line() - - if self._doc.eof(): - return False - - l1 = self._doc.peek().strip() # e.g. Parameters - - if l1.startswith('.. index::'): - return True - - l2 = self._doc.peek(1).strip() # ---------- or ========== - return l2.startswith('-'*len(l1)) or l2.startswith('='*len(l1)) - - def _strip(self, doc): - i = 0 - j = 0 - for i, line in enumerate(doc): - if line.strip(): - break - - for j, line in enumerate(doc[::-1]): - if line.strip(): - break - - return doc[i:len(doc)-j] - - def _read_to_next_section(self): - section = self._doc.read_to_next_empty_line() - - while not self._is_at_section() and not self._doc.eof(): - if not self._doc.peek(-1).strip(): # previous line was empty - section += [''] - - section += self._doc.read_to_next_empty_line() - - return section - - def _read_sections(self): - while not self._doc.eof(): - data = self._read_to_next_section() - name = data[0].strip() - - if name.startswith('..'): # index section - yield name, data[1:] - elif len(data) < 2: - yield StopIteration - else: - yield name, self._strip(data[2:]) - - def _parse_param_list(self, content): - r = Reader(content) - params = [] - while not r.eof(): - header = r.read().strip() - if ' : ' in header: - arg_name, arg_type = header.split(' : ')[:2] - else: - arg_name, arg_type = header, '' - - desc = r.read_to_next_unindented_line() - desc = dedent_lines(desc) - - params.append((arg_name, arg_type, desc)) - - return params - - _name_rgx = re.compile(r"^\s*(:(?P\w+):`(?P[a-zA-Z0-9_.-]+)`|" - r" (?P[a-zA-Z0-9_.-]+))\s*", re.X) - - def _parse_see_also(self, content): - """ - func_name : Descriptive text - continued text - another_func_name : Descriptive text - func_name1, func_name2, :meth:`func_name`, func_name3 - - """ - items = [] - - def parse_item_name(text): - """Match ':role:`name`' or 'name'""" - m = self._name_rgx.match(text) - if m: - g = m.groups() - if g[1] is None: - return g[3], None - else: - return g[2], g[1] - raise ValueError("%s is not a item name" % text) - - def push_item(name, rest): - if not name: - return - name, role = parse_item_name(name) - items.append((name, list(rest), role)) - del rest[:] - - current_func = None - rest = [] - - for line in content: - if not line.strip(): - continue - - m = self._name_rgx.match(line) - if m and line[m.end():].strip().startswith(':'): - push_item(current_func, rest) - current_func, line = line[:m.end()], line[m.end():] - rest = [line.split(':', 1)[1].strip()] - if not rest[0]: - rest = [] - elif not line.startswith(' '): - push_item(current_func, rest) - current_func = None - if ',' in line: - for func in line.split(','): - if func.strip(): - push_item(func, []) - elif line.strip(): - current_func = line - elif current_func is not None: - rest.append(line.strip()) - push_item(current_func, rest) - return items - - def _parse_index(self, section, content): - """ - .. index: default - :refguide: something, else, and more - - """ - def strip_each_in(lst): - return [s.strip() for s in lst] - - out = {} - section = section.split('::') - if len(section) > 1: - out['default'] = strip_each_in(section[1].split(','))[0] - for line in content: - line = line.split(':') - if len(line) > 2: - out[line[1]] = strip_each_in(line[2].split(',')) - return out - - def _parse_summary(self): - """Grab signature (if given) and summary""" - if self._is_at_section(): - return - - # If several signatures present, take the last one - while True: - summary = self._doc.read_to_next_empty_line() - summary_str = " ".join([s.strip() for s in summary]).strip() - if re.compile('^([\w., ]+=)?\s*[\w\.]+\(.*\)$').match(summary_str): - self['Signature'] = summary_str - if not self._is_at_section(): - continue - break - - if summary is not None: - self['Summary'] = summary - - if not self._is_at_section(): - self['Extended Summary'] = self._read_to_next_section() - - def _parse(self): - self._doc.reset() - self._parse_summary() - - sections = list(self._read_sections()) - section_names = set([section for section, content in sections]) - - has_returns = 'Returns' in section_names - has_yields = 'Yields' in section_names - # We could do more tests, but we are not. Arbitrarily. - if has_returns and has_yields: - msg = 'Docstring contains both a Returns and Yields section.' - raise ValueError(msg) - - for (section, content) in sections: - if not section.startswith('..'): - section = (s.capitalize() for s in section.split(' ')) - section = ' '.join(section) - if section in ('Parameters', 'Returns', 'Yields', 'Raises', - 'Warns', 'Other Parameters', 'Attributes', - 'Methods'): - self[section] = self._parse_param_list(content) - elif section.startswith('.. index::'): - self['index'] = self._parse_index(section, content) - elif section == 'See Also': - self['See Also'] = self._parse_see_also(content) - else: - self[section] = content - - # string conversion routines - - def _str_header(self, name, symbol='-'): - return [name, len(name)*symbol] - - def _str_indent(self, doc, indent=4): - out = [] - for line in doc: - out += [' '*indent + line] - return out - - def _str_signature(self): - if self['Signature']: - return [self['Signature'].replace('*', '\*')] + [''] - else: - return [''] - - def _str_summary(self): - if self['Summary']: - return self['Summary'] + [''] - else: - return [] - - def _str_extended_summary(self): - if self['Extended Summary']: - return self['Extended Summary'] + [''] - else: - return [] - - def _str_param_list(self, name): - out = [] - if self[name]: - out += self._str_header(name) - for param, param_type, desc in self[name]: - if param_type: - out += ['%s : %s' % (param, param_type)] - else: - out += [param] - out += self._str_indent(desc) - out += [''] - return out - - def _str_section(self, name): - out = [] - if self[name]: - out += self._str_header(name) - out += self[name] - out += [''] - return out - - def _str_see_also(self, func_role): - if not self['See Also']: - return [] - out = [] - out += self._str_header("See Also") - last_had_desc = True - for func, desc, role in self['See Also']: - if role: - link = ':%s:`%s`' % (role, func) - elif func_role: - link = ':%s:`%s`' % (func_role, func) - else: - link = "`%s`_" % func - if desc or last_had_desc: - out += [''] - out += [link] - else: - out[-1] += ", %s" % link - if desc: - out += self._str_indent([' '.join(desc)]) - last_had_desc = True - else: - last_had_desc = False - out += [''] - return out - - def _str_index(self): - idx = self['index'] - out = [] - out += ['.. index:: %s' % idx.get('default', '')] - for section, references in idx.items(): - if section == 'default': - continue - out += [' :%s: %s' % (section, ', '.join(references))] - return out - - def __str__(self, func_role=''): - out = [] - out += self._str_signature() - out += self._str_summary() - out += self._str_extended_summary() - for param_list in ('Parameters', 'Returns', 'Yields', - 'Other Parameters', 'Raises', 'Warns'): - out += self._str_param_list(param_list) - out += self._str_section('Warnings') - out += self._str_see_also(func_role) - for s in ('Notes', 'References', 'Examples'): - out += self._str_section(s) - for param_list in ('Attributes', 'Methods'): - out += self._str_param_list(param_list) - out += self._str_index() - return '\n'.join(out) - - -def indent(str, indent=4): - indent_str = ' '*indent - if str is None: - return indent_str - lines = str.split('\n') - return '\n'.join(indent_str + l for l in lines) - - -def dedent_lines(lines): - """Deindent a list of lines maximally""" - return textwrap.dedent("\n".join(lines)).split("\n") - - -def header(text, style='-'): - return text + '\n' + style*len(text) + '\n' - - -class FunctionDoc(NumpyDocString): - def __init__(self, func, role='func', doc=None, config={}): - self._f = func - self._role = role # e.g. "func" or "meth" - - if doc is None: - if func is None: - raise ValueError("No function or docstring given") - doc = inspect.getdoc(func) or '' - NumpyDocString.__init__(self, doc) - - if not self['Signature'] and func is not None: - func, func_name = self.get_func() - try: - # try to read signature - if sys.version_info[0] >= 3: - argspec = inspect.getfullargspec(func) - else: - argspec = inspect.getargspec(func) - argspec = inspect.formatargspec(*argspec) - argspec = argspec.replace('*', '\*') - signature = '%s%s' % (func_name, argspec) - except TypeError as e: - signature = '%s()' % func_name - self['Signature'] = signature - - def get_func(self): - func_name = getattr(self._f, '__name__', self.__class__.__name__) - if inspect.isclass(self._f): - func = getattr(self._f, '__call__', self._f.__init__) - else: - func = self._f - return func, func_name - - def __str__(self): - out = '' - - func, func_name = self.get_func() - signature = self['Signature'].replace('*', '\*') - - roles = {'func': 'function', - 'meth': 'method'} - - if self._role: - if self._role not in roles: - print("Warning: invalid role %s" % self._role) - out += '.. %s:: %s\n \n\n' % (roles.get(self._role, ''), - func_name) - - out += super(FunctionDoc, self).__str__(func_role=self._role) - return out - - -class ClassDoc(NumpyDocString): - - extra_public_methods = ['__call__'] - - def __init__(self, cls, doc=None, modulename='', func_doc=FunctionDoc, - config={}): - if not inspect.isclass(cls) and cls is not None: - raise ValueError("Expected a class or None, but got %r" % cls) - self._cls = cls - - self.show_inherited_members = config.get( - 'show_inherited_class_members', True) - - if modulename and not modulename.endswith('.'): - modulename += '.' - self._mod = modulename - - if doc is None: - if cls is None: - raise ValueError("No class or documentation string given") - doc = pydoc.getdoc(cls) - - NumpyDocString.__init__(self, doc) - - if config.get('show_class_members', True): - def splitlines_x(s): - if not s: - return [] - else: - return s.splitlines() - - for field, items in [('Methods', self.methods), - ('Attributes', self.properties)]: - if not self[field]: - doc_list = [] - for name in sorted(items): - try: - doc_item = pydoc.getdoc(getattr(self._cls, name)) - doc_list.append((name, '', splitlines_x(doc_item))) - except AttributeError: - pass # method doesn't exist - self[field] = doc_list - - @property - def methods(self): - if self._cls is None: - return [] - return [name for name, func in inspect.getmembers(self._cls) - if ((not name.startswith('_') - or name in self.extra_public_methods) - and isinstance(func, collections.Callable) - and self._is_show_member(name))] - - @property - def properties(self): - if self._cls is None: - return [] - return [name for name, func in inspect.getmembers(self._cls) - if (not name.startswith('_') and - (func is None or isinstance(func, property) or - inspect.isgetsetdescriptor(func)) - and self._is_show_member(name))] - - def _is_show_member(self, name): - if self.show_inherited_members: - return True # show all class members - if name not in self._cls.__dict__: - return False # class member is inherited, we do not show it - return True diff --git a/doc/sphinxext/docscrape_sphinx.py b/doc/sphinxext/docscrape_sphinx.py deleted file mode 100644 index e44e770e..00000000 --- a/doc/sphinxext/docscrape_sphinx.py +++ /dev/null @@ -1,227 +0,0 @@ -import re, inspect, textwrap, pydoc -import sphinx -from docscrape import NumpyDocString, FunctionDoc, ClassDoc - -class SphinxDocString(NumpyDocString): - def __init__(self, docstring, config={}): - self.use_plots = config.get('use_plots', False) - NumpyDocString.__init__(self, docstring, config=config) - - # string conversion routines - def _str_header(self, name, symbol='`'): - return ['.. rubric:: ' + name, ''] - - def _str_field_list(self, name): - return [':' + name + ':'] - - def _str_indent(self, doc, indent=4): - out = [] - for line in doc: - out += [' '*indent + line] - return out - - def _str_signature(self): - return [''] - if self['Signature']: - return ['``%s``' % self['Signature']] + [''] - else: - return [''] - - def _str_summary(self): - return self['Summary'] + [''] - - def _str_extended_summary(self): - return self['Extended Summary'] + [''] - - def _str_param_list(self, name): - out = [] - if self[name]: - out += self._str_field_list(name) - out += [''] - for param,param_type,desc in self[name]: - out += self._str_indent(['**%s** : %s' % (param.strip(), - param_type)]) - out += [''] - out += self._str_indent(desc,8) - out += [''] - return out - - @property - def _obj(self): - if hasattr(self, '_cls'): - return self._cls - elif hasattr(self, '_f'): - return self._f - return None - - def _str_member_list(self, name): - """ - Generate a member listing, autosummary:: table where possible, - and a table where not. - - """ - out = [] - if self[name]: - out += ['.. rubric:: %s' % name, ''] - prefix = getattr(self, '_name', '') - - if prefix: - prefix = '~%s.' % prefix - - autosum = [] - others = [] - for param, param_type, desc in self[name]: - param = param.strip() - if not self._obj or hasattr(self._obj, param): - autosum += [" %s%s" % (prefix, param)] - else: - others.append((param, param_type, desc)) - - if autosum: - out += ['.. autosummary::', ' :toctree:', ''] - out += autosum - - if others: - maxlen_0 = max([len(x[0]) for x in others]) - maxlen_1 = max([len(x[1]) for x in others]) - hdr = "="*maxlen_0 + " " + "="*maxlen_1 + " " + "="*10 - fmt = '%%%ds %%%ds ' % (maxlen_0, maxlen_1) - n_indent = maxlen_0 + maxlen_1 + 4 - out += [hdr] - for param, param_type, desc in others: - out += [fmt % (param.strip(), param_type)] - out += self._str_indent(desc, n_indent) - out += [hdr] - out += [''] - return out - - def _str_section(self, name): - out = [] - if self[name]: - out += self._str_header(name) - out += [''] - content = textwrap.dedent("\n".join(self[name])).split("\n") - out += content - out += [''] - return out - - def _str_see_also(self, func_role): - out = [] - if self['See Also']: - see_also = super(SphinxDocString, self)._str_see_also(func_role) - out = ['.. seealso::', ''] - out += self._str_indent(see_also[2:]) - return out - - def _str_warnings(self): - out = [] - if self['Warnings']: - out = ['.. warning::', ''] - out += self._str_indent(self['Warnings']) - return out - - def _str_index(self): - idx = self['index'] - out = [] - if len(idx) == 0: - return out - - out += ['.. index:: %s' % idx.get('default','')] - for section, references in idx.iteritems(): - if section == 'default': - continue - elif section == 'refguide': - out += [' single: %s' % (', '.join(references))] - else: - out += [' %s: %s' % (section, ','.join(references))] - return out - - def _str_references(self): - out = [] - if self['References']: - out += self._str_header('References') - if isinstance(self['References'], str): - self['References'] = [self['References']] - out.extend(self['References']) - out += [''] - # Latex collects all references to a separate bibliography, - # so we need to insert links to it - if sphinx.__version__ >= "0.6": - out += ['.. only:: latex',''] - else: - out += ['.. latexonly::',''] - items = [] - for line in self['References']: - m = re.match(r'.. \[([a-z0-9._-]+)\]', line, re.I) - if m: - items.append(m.group(1)) - out += [' ' + ", ".join(["[%s]_" % item for item in items]), ''] - return out - - def _str_examples(self): - examples_str = "\n".join(self['Examples']) - - if (self.use_plots and 'import matplotlib' in examples_str - and 'plot::' not in examples_str): - out = [] - out += self._str_header('Examples') - out += ['.. plot::', ''] - out += self._str_indent(self['Examples']) - out += [''] - return out - else: - return self._str_section('Examples') - - def __str__(self, indent=0, func_role="obj"): - out = [] - out += self._str_signature() - out += self._str_index() + [''] - out += self._str_summary() - out += self._str_extended_summary() - for param_list in ('Parameters', 'Returns', 'Other Parameters', - 'Raises', 'Warns'): - out += self._str_param_list(param_list) - out += self._str_warnings() - out += self._str_see_also(func_role) - out += self._str_section('Notes') - out += self._str_references() - out += self._str_examples() - for param_list in ('Attributes', 'Methods'): - out += self._str_member_list(param_list) - out = self._str_indent(out,indent) - return '\n'.join(out) - -class SphinxFunctionDoc(SphinxDocString, FunctionDoc): - def __init__(self, obj, doc=None, config={}): - self.use_plots = config.get('use_plots', False) - FunctionDoc.__init__(self, obj, doc=doc, config=config) - -class SphinxClassDoc(SphinxDocString, ClassDoc): - def __init__(self, obj, doc=None, func_doc=None, config={}): - self.use_plots = config.get('use_plots', False) - ClassDoc.__init__(self, obj, doc=doc, func_doc=None, config=config) - -class SphinxObjDoc(SphinxDocString): - def __init__(self, obj, doc=None, config={}): - self._f = obj - SphinxDocString.__init__(self, doc, config=config) - -def get_doc_object(obj, what=None, doc=None, config={}): - if what is None: - if inspect.isclass(obj): - what = 'class' - elif inspect.ismodule(obj): - what = 'module' - elif callable(obj): - what = 'function' - else: - what = 'object' - if what == 'class': - return SphinxClassDoc(obj, func_doc=SphinxFunctionDoc, doc=doc, - config=config) - elif what in ('function', 'method'): - return SphinxFunctionDoc(obj, doc=doc, config=config) - else: - if doc is None: - doc = pydoc.getdoc(obj) - return SphinxObjDoc(obj, doc, config=config) diff --git a/doc/sphinxext/github.py b/doc/sphinxext/github.py deleted file mode 100644 index 519e146d..00000000 --- a/doc/sphinxext/github.py +++ /dev/null @@ -1,155 +0,0 @@ -"""Define text roles for GitHub - -* ghissue - Issue -* ghpull - Pull Request -* ghuser - User - -Adapted from bitbucket example here: -https://bitbucket.org/birkenfeld/sphinx-contrib/src/tip/bitbucket/sphinxcontrib/bitbucket.py - -Authors -------- - -* Doug Hellmann -* Min RK -""" -# -# Original Copyright (c) 2010 Doug Hellmann. All rights reserved. -# - -from docutils import nodes, utils -from docutils.parsers.rst.roles import set_classes - -def make_link_node(rawtext, app, type, slug, options): - """Create a link to a github resource. - - :param rawtext: Text being replaced with link node. - :param app: Sphinx application context - :param type: Link type (issues, changeset, etc.) - :param slug: ID of the thing to link to - :param options: Options dictionary passed to role func. - """ - - try: - base = app.config.github_project_url - if not base: - raise AttributeError - if not base.endswith('/'): - base += '/' - except AttributeError as err: - raise ValueError('github_project_url configuration value is not set (%s)' % str(err)) - - ref = base + type + '/' + slug + '/' - set_classes(options) - prefix = "#" - if type == 'pull': - prefix = "PR " + prefix - node = nodes.reference(rawtext, prefix + utils.unescape(slug), refuri=ref, - **options) - return node - -def ghissue_role(name, rawtext, text, lineno, inliner, options={}, content=[]): - """Link to a GitHub issue. - - Returns 2 part tuple containing list of nodes to insert into the - document and a list of system messages. Both are allowed to be - empty. - - :param name: The role name used in the document. - :param rawtext: The entire markup snippet, with role. - :param text: The text marked with the role. - :param lineno: The line number where rawtext appears in the input. - :param inliner: The inliner instance that called us. - :param options: Directive options for customization. - :param content: The directive content for customization. - """ - - try: - issue_num = int(text) - if issue_num <= 0: - raise ValueError - except ValueError: - msg = inliner.reporter.error( - 'GitHub issue number must be a number greater than or equal to 1; ' - '"%s" is invalid.' % text, line=lineno) - prb = inliner.problematic(rawtext, rawtext, msg) - return [prb], [msg] - app = inliner.document.settings.env.app - #app.info('issue %r' % text) - if 'pull' in name.lower(): - category = 'pull' - elif 'issue' in name.lower(): - category = 'issues' - else: - msg = inliner.reporter.error( - 'GitHub roles include "ghpull" and "ghissue", ' - '"%s" is invalid.' % name, line=lineno) - prb = inliner.problematic(rawtext, rawtext, msg) - return [prb], [msg] - node = make_link_node(rawtext, app, category, str(issue_num), options) - return [node], [] - -def ghuser_role(name, rawtext, text, lineno, inliner, options={}, content=[]): - """Link to a GitHub user. - - Returns 2 part tuple containing list of nodes to insert into the - document and a list of system messages. Both are allowed to be - empty. - - :param name: The role name used in the document. - :param rawtext: The entire markup snippet, with role. - :param text: The text marked with the role. - :param lineno: The line number where rawtext appears in the input. - :param inliner: The inliner instance that called us. - :param options: Directive options for customization. - :param content: The directive content for customization. - """ - app = inliner.document.settings.env.app - #app.info('user link %r' % text) - ref = 'https://www.github.com/' + text - node = nodes.reference(rawtext, text, refuri=ref, **options) - return [node], [] - -def ghcommit_role(name, rawtext, text, lineno, inliner, options={}, content=[]): - """Link to a GitHub commit. - - Returns 2 part tuple containing list of nodes to insert into the - document and a list of system messages. Both are allowed to be - empty. - - :param name: The role name used in the document. - :param rawtext: The entire markup snippet, with role. - :param text: The text marked with the role. - :param lineno: The line number where rawtext appears in the input. - :param inliner: The inliner instance that called us. - :param options: Directive options for customization. - :param content: The directive content for customization. - """ - app = inliner.document.settings.env.app - #app.info('user link %r' % text) - try: - base = app.config.github_project_url - if not base: - raise AttributeError - if not base.endswith('/'): - base += '/' - except AttributeError as err: - raise ValueError('github_project_url configuration value is not set (%s)' % str(err)) - - ref = base + text - node = nodes.reference(rawtext, text[:6], refuri=ref, **options) - return [node], [] - - -def setup(app): - """Install the plugin. - - :param app: Sphinx application context. - """ - app.info('Initializing GitHub plugin') - app.add_role('ghissue', ghissue_role) - app.add_role('ghpull', ghissue_role) - app.add_role('ghuser', ghuser_role) - app.add_role('ghcommit', ghcommit_role) - app.add_config_value('github_project_url', None, 'env') - return diff --git a/doc/sphinxext/math_dollar.py b/doc/sphinxext/math_dollar.py deleted file mode 100644 index ad415deb..00000000 --- a/doc/sphinxext/math_dollar.py +++ /dev/null @@ -1,63 +0,0 @@ -import re - -def dollars_to_math(source): - r""" - Replace dollar signs with backticks. - - More precisely, do a regular expression search. Replace a plain - dollar sign ($) by a backtick (`). Replace an escaped dollar sign - (\$) by a dollar sign ($). Don't change a dollar sign preceded or - followed by a backtick (`$ or $`), because of strings like - "``$HOME``". Don't make any changes on lines starting with - spaces, because those are indented and hence part of a block of - code or examples. - - This also doesn't replaces dollar signs enclosed in curly braces, - to avoid nested math environments, such as :: - - $f(n) = 0 \text{ if $n$ is prime}$ - - Thus the above line would get changed to - - `f(n) = 0 \text{ if $n$ is prime}` - """ - s = "\n".join(source) - if s.find("$") == -1: - return - # This searches for "$blah$" inside a pair of curly braces -- - # don't change these, since they're probably coming from a nested - # math environment. So for each match, we replace it with a temporary - # string, and later on we substitute the original back. - global _data - _data = {} - def repl(matchobj): - global _data - s = matchobj.group(0) - t = "___XXX_REPL_%d___" % len(_data) - _data[t] = s - return t - s = re.sub(r"({[^{}$]*\$[^{}$]*\$[^{}]*})", repl, s) - # matches $...$ - dollars = re.compile(r"(?= 3: - sixu = lambda s: s -else: - sixu = lambda s: unicode(s, 'unicode_escape') - - -def mangle_docstrings(app, what, name, obj, options, lines, - reference_offset=[0]): - - cfg = {'use_plots': app.config.numpydoc_use_plots, - 'show_class_members': app.config.numpydoc_show_class_members, - 'show_inherited_class_members': - app.config.numpydoc_show_inherited_class_members, - 'class_members_toctree': app.config.numpydoc_class_members_toctree} - - u_NL = sixu('\n') - if what == 'module': - # Strip top title - pattern = '^\\s*[#*=]{4,}\\n[a-z0-9 -]+\\n[#*=]{4,}\\s*' - title_re = re.compile(sixu(pattern), re.I | re.S) - lines[:] = title_re.sub(sixu(''), u_NL.join(lines)).split(u_NL) - else: - doc = get_doc_object(obj, what, u_NL.join(lines), config=cfg) - if sys.version_info[0] >= 3: - doc = str(doc) - else: - doc = unicode(doc) - lines[:] = doc.split(u_NL) - - if (app.config.numpydoc_edit_link and hasattr(obj, '__name__') and - obj.__name__): - if hasattr(obj, '__module__'): - v = dict(full_name=sixu("%s.%s") % (obj.__module__, obj.__name__)) - else: - v = dict(full_name=obj.__name__) - lines += [sixu(''), sixu('.. htmlonly::'), sixu('')] - lines += [sixu(' %s') % x for x in - (app.config.numpydoc_edit_link % v).split("\n")] - - # replace reference numbers so that there are no duplicates - references = [] - for line in lines: - line = line.strip() - m = re.match(sixu('^.. \\[([a-z0-9_.-])\\]'), line, re.I) - if m: - references.append(m.group(1)) - - # start renaming from the longest string, to avoid overwriting parts - references.sort(key=lambda x: -len(x)) - if references: - for i, line in enumerate(lines): - for r in references: - if re.match(sixu('^\\d+$'), r): - new_r = sixu("R%d") % (reference_offset[0] + int(r)) - else: - new_r = sixu("%s%d") % (r, reference_offset[0]) - lines[i] = lines[i].replace(sixu('[%s]_') % r, - sixu('[%s]_') % new_r) - lines[i] = lines[i].replace(sixu('.. [%s]') % r, - sixu('.. [%s]') % new_r) - - reference_offset[0] += len(references) - - -def mangle_signature(app, what, name, obj, options, sig, retann): - # Do not try to inspect classes that don't define `__init__` - if (inspect.isclass(obj) and - (not hasattr(obj, '__init__') or - 'initializes x; see ' in pydoc.getdoc(obj.__init__))): - return '', '' - - if not (isinstance(obj, collections.Callable) or - hasattr(obj, '__argspec_is_invalid_')): - return - - if not hasattr(obj, '__doc__'): - return - - doc = SphinxDocString(pydoc.getdoc(obj)) - if doc['Signature']: - sig = re.sub(sixu("^[^(]*"), sixu(""), doc['Signature']) - return sig, sixu('') - - -def setup(app, get_doc_object_=get_doc_object): - if not hasattr(app, 'add_config_value'): - return # probably called by nose, better bail out - - global get_doc_object - get_doc_object = get_doc_object_ - - app.connect('autodoc-process-docstring', mangle_docstrings) - app.connect('autodoc-process-signature', mangle_signature) - app.add_config_value('numpydoc_edit_link', None, False) - app.add_config_value('numpydoc_use_plots', None, False) - app.add_config_value('numpydoc_show_class_members', True, True) - app.add_config_value('numpydoc_show_inherited_class_members', True, True) - app.add_config_value('numpydoc_class_members_toctree', True, True) - - # Extra mangling domains - app.add_domain(NumpyPythonDomain) - app.add_domain(NumpyCDomain) - -# ------------------------------------------------------------------------------ -# Docstring-mangling domains -# ------------------------------------------------------------------------------ - -from docutils.statemachine import ViewList -from sphinx.domains.c import CDomain -from sphinx.domains.python import PythonDomain - - -class ManglingDomainBase(object): - directive_mangling_map = {} - - def __init__(self, *a, **kw): - super(ManglingDomainBase, self).__init__(*a, **kw) - self.wrap_mangling_directives() - - def wrap_mangling_directives(self): - for name, objtype in list(self.directive_mangling_map.items()): - self.directives[name] = wrap_mangling_directive( - self.directives[name], objtype) - - -class NumpyPythonDomain(ManglingDomainBase, PythonDomain): - name = 'np' - directive_mangling_map = { - 'function': 'function', - 'class': 'class', - 'exception': 'class', - 'method': 'function', - 'classmethod': 'function', - 'staticmethod': 'function', - 'attribute': 'attribute', - } - indices = [] - - -class NumpyCDomain(ManglingDomainBase, CDomain): - name = 'np-c' - directive_mangling_map = { - 'function': 'function', - 'member': 'attribute', - 'macro': 'function', - 'type': 'class', - 'var': 'object', - } - - -def wrap_mangling_directive(base_directive, objtype): - class directive(base_directive): - def run(self): - env = self.state.document.settings.env - - name = None - if self.arguments: - m = re.match(r'^(.*\s+)?(.*?)(\(.*)?', self.arguments[0]) - name = m.group(2).strip() - - if not name: - name = self.arguments[0] - - lines = list(self.content) - mangle_docstrings(env.app, objtype, name, None, None, lines) - self.content = ViewList(lines, self.content.parent) - - return base_directive.run(self) - - return directive diff --git a/doc/theory.rst b/doc/theory.rst deleted file mode 100644 index a3fc9f87..00000000 --- a/doc/theory.rst +++ /dev/null @@ -1,17 +0,0 @@ - -This is a theory section -======================== - -I might want to describe some equations: - -.. math:: - - \int_0^\infty e^{-x^2} dx=\frac{\sqrt{\pi}}{2} - - -And refer to a paper [author2015]_. - - -.. [author2015] first a., second a., cheese b. (2015). The title of their - paper. Journal of papers, *15*: 1023-1049. - diff --git a/doc/tools/LICENSE.txt b/doc/tools/LICENSE.txt deleted file mode 100644 index 9e1d415a..00000000 --- a/doc/tools/LICENSE.txt +++ /dev/null @@ -1,7 +0,0 @@ -These files were obtained from - -https://www.mail-archive.com/sphinx-dev@googlegroups.com/msg02472.html - -and were released under a BSD/MIT license by Fernando Perez, Matthew Brett and -the PyMVPA folks. Further cleanups by the scikit-image crew. - diff --git a/doc/tools/apigen.py b/doc/tools/apigen.py deleted file mode 100644 index 758671fa..00000000 --- a/doc/tools/apigen.py +++ /dev/null @@ -1,509 +0,0 @@ -""" -Attempt to generate templates for module reference with Sphinx - -To include extension modules, first identify them as valid in the -``_uri2path`` method, then handle them in the ``_parse_module_with_import`` -script. - -Notes ------ -This parsing is based on import and introspection of modules. -Previously functions and classes were found by parsing the text of .py files. - -Extension modules should be discovered and included as well. - -This is a modified version of a script originally shipped with the PyMVPA -project, then adapted for use first in NIPY and then in skimage. PyMVPA -is an MIT-licensed project. -""" - -# Stdlib imports -import os -import re -from inspect import getmodule - -from types import BuiltinFunctionType, FunctionType - -# suppress print statements (warnings for empty files) -DEBUG = True - -class ApiDocWriter(object): - ''' Class for automatic detection and parsing of API docs - to Sphinx-parsable reST format''' - - # only separating first two levels - rst_section_levels = ['*', '=', '-', '~', '^'] - - def __init__(self, - package_name, - rst_extension='.txt', - package_skip_patterns=None, - module_skip_patterns=None, - other_defines = True - ): - ''' Initialize package for parsing - - Parameters - ---------- - package_name : string - Name of the top-level package. *package_name* must be the - name of an importable package - rst_extension : string, optional - Extension for reST files, default '.rst' - package_skip_patterns : None or sequence of {strings, regexps} - Sequence of strings giving URIs of packages to be excluded - Operates on the package path, starting at (including) the - first dot in the package path, after *package_name* - so, - if *package_name* is ``sphinx``, then ``sphinx.util`` will - result in ``.util`` being passed for searching by these - regexps. If is None, gives default. Default is: - ['\.tests$'] - module_skip_patterns : None or sequence - Sequence of strings giving URIs of modules to be excluded - Operates on the module name including preceding URI path, - back to the first dot after *package_name*. For example - ``sphinx.util.console`` results in the string to search of - ``.util.console`` - If is None, gives default. Default is: - ['\.setup$', '\._'] - other_defines : {True, False}, optional - Whether to include classes and functions that are imported in a - particular module but not defined there. - ''' - if package_skip_patterns is None: - package_skip_patterns = ['\\.tests$'] - if module_skip_patterns is None: - module_skip_patterns = ['\\.setup$', '\\._'] - self.package_name = package_name - self.rst_extension = rst_extension - self.package_skip_patterns = package_skip_patterns - self.module_skip_patterns = module_skip_patterns - self.other_defines = other_defines - - def get_package_name(self): - return self._package_name - - def set_package_name(self, package_name): - ''' Set package_name - - >>> docwriter = ApiDocWriter('sphinx') - >>> import sphinx - >>> docwriter.root_path == sphinx.__path__[0] - True - >>> docwriter.package_name = 'docutils' - >>> import docutils - >>> docwriter.root_path == docutils.__path__[0] - True - ''' - # It's also possible to imagine caching the module parsing here - self._package_name = package_name - root_module = self._import(package_name) - self.root_path = root_module.__path__[-1] - self.written_modules = None - - package_name = property(get_package_name, set_package_name, None, - 'get/set package_name') - - def _import(self, name): - ''' Import namespace package ''' - mod = __import__(name) - components = name.split('.') - for comp in components[1:]: - mod = getattr(mod, comp) - return mod - - def _get_object_name(self, line): - ''' Get second token in line - >>> docwriter = ApiDocWriter('sphinx') - >>> docwriter._get_object_name(" def func(): ") - 'func' - >>> docwriter._get_object_name(" class Klass(object): ") - 'Klass' - >>> docwriter._get_object_name(" class Klass: ") - 'Klass' - ''' - name = line.split()[1].split('(')[0].strip() - # in case we have classes which are not derived from object - # ie. old style classes - return name.rstrip(':') - - def _uri2path(self, uri): - ''' Convert uri to absolute filepath - - Parameters - ---------- - uri : string - URI of python module to return path for - - Returns - ------- - path : None or string - Returns None if there is no valid path for this URI - Otherwise returns absolute file system path for URI - - Examples - -------- - >>> docwriter = ApiDocWriter('sphinx') - >>> import sphinx - >>> modpath = sphinx.__path__[0] - >>> res = docwriter._uri2path('sphinx.builder') - >>> res == os.path.join(modpath, 'builder.py') - True - >>> res = docwriter._uri2path('sphinx') - >>> res == os.path.join(modpath, '__init__.py') - True - >>> docwriter._uri2path('sphinx.does_not_exist') - - ''' - if uri == self.package_name: - return os.path.join(self.root_path, '__init__.py') - path = uri.replace(self.package_name + '.', '') - path = path.replace('.', os.path.sep) - path = os.path.join(self.root_path, path) - # XXX maybe check for extensions as well? - if os.path.exists(path + '.py'): # file - path += '.py' - elif os.path.exists(os.path.join(path, '__init__.py')): - path = os.path.join(path, '__init__.py') - else: - return None - return path - - def _path2uri(self, dirpath): - ''' Convert directory path to uri ''' - package_dir = self.package_name.replace('.', os.path.sep) - relpath = dirpath.replace(self.root_path, package_dir) - if relpath.startswith(os.path.sep): - relpath = relpath[1:] - return relpath.replace(os.path.sep, '.') - - def _parse_module(self, uri): - ''' Parse module defined in *uri* ''' - filename = self._uri2path(uri) - if filename is None: - print(filename, 'erk') - # nothing that we could handle here. - return ([],[]) - - f = open(filename, 'rt') - functions, classes = self._parse_lines(f) - f.close() - return functions, classes - - def _parse_module_with_import(self, uri): - """Look for functions and classes in an importable module. - - Parameters - ---------- - uri : str - The name of the module to be parsed. This module needs to be - importable. - - Returns - ------- - functions : list of str - A list of (public) function names in the module. - classes : list of str - A list of (public) class names in the module. - """ - mod = __import__(uri, fromlist=[uri]) - # find all public objects in the module. - obj_strs = [obj for obj in dir(mod) if not obj.startswith('_')] - functions = [] - classes = [] - for obj_str in obj_strs: - # find the actual object from its string representation - if obj_str not in mod.__dict__: - continue - obj = mod.__dict__[obj_str] - # Check if function / class defined in module - if not self.other_defines and not getmodule(obj) == mod: - continue - # figure out if obj is a function or class - if hasattr(obj, 'func_name') or \ - isinstance(obj, BuiltinFunctionType) or \ - isinstance(obj, FunctionType): - functions.append(obj_str) - else: - try: - issubclass(obj, object) - classes.append(obj_str) - except TypeError: - # not a function or class - pass - return functions, classes - - def _parse_lines(self, linesource): - ''' Parse lines of text for functions and classes ''' - functions = [] - classes = [] - for line in linesource: - if line.startswith('def ') and line.count('('): - # exclude private stuff - name = self._get_object_name(line) - if not name.startswith('_'): - functions.append(name) - elif line.startswith('class '): - # exclude private stuff - name = self._get_object_name(line) - if not name.startswith('_'): - classes.append(name) - else: - pass - functions.sort() - classes.sort() - return functions, classes - - def generate_api_doc(self, uri): - '''Make autodoc documentation template string for a module - - Parameters - ---------- - uri : string - python location of module - e.g 'sphinx.builder' - - Returns - ------- - head : string - Module name, table of contents. - body : string - Function and class docstrings. - ''' - # get the names of all classes and functions - functions, classes = self._parse_module_with_import(uri) - if not len(functions) and not len(classes) and DEBUG: - print('WARNING: Empty -', uri) # dbg - - # Make a shorter version of the uri that omits the package name for - # titles - uri_short = re.sub(r'^%s\.' % self.package_name,'',uri) - - head = '.. AUTO-GENERATED FILE -- DO NOT EDIT!\n\n' - body = '' - - # Set the chapter title to read 'module' for all modules except for the - # main packages - if '.' in uri_short: - title = 'Module: :mod:`' + uri_short + '`' - head += title + '\n' + self.rst_section_levels[2] * len(title) - else: - title = ':mod:`' + uri_short + '`' - head += title + '\n' + self.rst_section_levels[1] * len(title) - - head += '\n.. automodule:: ' + uri + '\n' - head += '\n.. currentmodule:: ' + uri + '\n' - body += '\n.. currentmodule:: ' + uri + '\n\n' - for c in classes: - body += '\n:class:`' + c + '`\n' \ - + self.rst_section_levels[3] * \ - (len(c)+9) + '\n\n' - body += '\n.. autoclass:: ' + c + '\n' - # must NOT exclude from index to keep cross-refs working - body += ' :members:\n' \ - ' :undoc-members:\n' \ - ' :show-inheritance:\n' \ - '\n' \ - ' .. automethod:: __init__\n\n' - head += '.. autosummary::\n\n' - for f in classes + functions: - head += ' ' + f + '\n' - head += '\n' - - for f in functions: - # must NOT exclude from index to keep cross-refs working - body += f + '\n' - body += self.rst_section_levels[3] * len(f) + '\n' - body += '\n.. autofunction:: ' + f + '\n\n' - - return head, body - - def _survives_exclude(self, matchstr, match_type): - ''' Returns True if *matchstr* does not match patterns - - ``self.package_name`` removed from front of string if present - - Examples - -------- - >>> dw = ApiDocWriter('sphinx') - >>> dw._survives_exclude('sphinx.okpkg', 'package') - True - >>> dw.package_skip_patterns.append('^\\.badpkg$') - >>> dw._survives_exclude('sphinx.badpkg', 'package') - False - >>> dw._survives_exclude('sphinx.badpkg', 'module') - True - >>> dw._survives_exclude('sphinx.badmod', 'module') - True - >>> dw.module_skip_patterns.append('^\\.badmod$') - >>> dw._survives_exclude('sphinx.badmod', 'module') - False - ''' - if match_type == 'module': - patterns = self.module_skip_patterns - elif match_type == 'package': - patterns = self.package_skip_patterns - else: - raise ValueError('Cannot interpret match type "%s"' - % match_type) - # Match to URI without package name - L = len(self.package_name) - if matchstr[:L] == self.package_name: - matchstr = matchstr[L:] - for pat in patterns: - try: - pat.search - except AttributeError: - pat = re.compile(pat) - if pat.search(matchstr): - return False - - return True - - def discover_modules(self): - ''' Return module sequence discovered from ``self.package_name`` - - - Parameters - ---------- - None - - Returns - ------- - mods : sequence - Sequence of module names within ``self.package_name`` - - Examples - -------- - >>> dw = ApiDocWriter('sphinx') - >>> mods = dw.discover_modules() - >>> 'sphinx.util' in mods - True - >>> dw.package_skip_patterns.append('\.util$') - >>> 'sphinx.util' in dw.discover_modules() - False - >>> - ''' - modules = [self.package_name] - # raw directory parsing - for dirpath, dirnames, filenames in os.walk(self.root_path): - # Check directory names for packages - root_uri = self._path2uri(os.path.join(self.root_path, - dirpath)) - - # Normally, we'd only iterate over dirnames, but since - # dipy does not import a whole bunch of modules we'll - # include those here as well (the *.py filenames). - filenames = [f[:-3] for f in filenames if - f.endswith('.py') and not f.startswith('__init__')] - for filename in filenames: - package_uri = '/'.join((dirpath, filename)) - - for subpkg_name in dirnames + filenames: - package_uri = '.'.join((root_uri, subpkg_name)) - package_path = self._uri2path(package_uri) - if (package_path and - self._survives_exclude(package_uri, 'package')): - modules.append(package_uri) - - return sorted(modules) - - def write_modules_api(self, modules, outdir): - # upper-level modules - main_module = modules[0].split('.')[0] - ulms = ['.'.join(m.split('.')[:2]) if m.count('.') >= 1 - else m.split('.')[0] for m in modules] - - from collections import OrderedDict - module_by_ulm = OrderedDict() - - for v, k in zip(modules, ulms): - if k in module_by_ulm: - module_by_ulm[k].append(v) - else: - module_by_ulm[k] = [v] - - written_modules = [] - - for ulm, mods in module_by_ulm.items(): - print("Generating docs for %s:" % ulm) - document_head = [] - document_body = [] - - for m in mods: - print(" -> " + m) - head, body = self.generate_api_doc(m) - - document_head.append(head) - document_body.append(body) - - out_module = ulm + self.rst_extension - outfile = os.path.join(outdir, out_module) - fileobj = open(outfile, 'wt') - - fileobj.writelines(document_head + document_body) - fileobj.close() - written_modules.append(out_module) - - self.written_modules = written_modules - - def write_api_docs(self, outdir): - """Generate API reST files. - - Parameters - ---------- - outdir : string - Directory name in which to store files - We create automatic filenames for each module - - Returns - ------- - None - - Notes - ----- - Sets self.written_modules to list of written modules - """ - if not os.path.exists(outdir): - os.mkdir(outdir) - # compose list of modules - modules = self.discover_modules() - self.write_modules_api(modules,outdir) - - def write_index(self, outdir, froot='gen', relative_to=None): - """Make a reST API index file from written files - - Parameters - ---------- - path : string - Filename to write index to - outdir : string - Directory to which to write generated index file - froot : string, optional - root (filename without extension) of filename to write to - Defaults to 'gen'. We add ``self.rst_extension``. - relative_to : string - path to which written filenames are relative. This - component of the written file path will be removed from - outdir, in the generated index. Default is None, meaning, - leave path as it is. - """ - if self.written_modules is None: - raise ValueError('No modules written') - # Get full filename path - path = os.path.join(outdir, froot+self.rst_extension) - # Path written into index is relative to rootpath - if relative_to is not None: - relpath = (outdir + os.path.sep).replace(relative_to + os.path.sep, '') - else: - relpath = outdir - idx = open(path,'wt') - w = idx.write - w('.. AUTO-GENERATED FILE -- DO NOT EDIT!\n\n') - - title = "API Reference" - w(title + "\n") - w("=" * len(title) + "\n\n") - w('.. toctree::\n\n') - for f in self.written_modules: - w(' %s\n' % os.path.join(relpath,f)) - idx.close() diff --git a/doc/tools/buildmodref.py b/doc/tools/buildmodref.py deleted file mode 100755 index e2a7b9f6..00000000 --- a/doc/tools/buildmodref.py +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/env python -"""Script to auto-generate API docs. -""" -from __future__ import print_function, division - -# stdlib imports -import sys -import re - -# local imports -from apigen import ApiDocWriter - -# version comparison -from distutils.version import LooseVersion as V - -#***************************************************************************** - -def abort(error): - print('*WARNING* API documentation not generated: %s' % error) - exit() - - -def writeapi(package, outdir, source_version, other_defines=True): - # Check that the package is available. If not, the API documentation is not - # (re)generated and existing API documentation sources will be used. - - try: - __import__(package) - except ImportError: - abort("Can not import " + package) - - module = sys.modules[package] - - # Check that the source version is equal to the installed - # version. If the versions mismatch the API documentation sources - # are not (re)generated. This avoids automatic generation of documentation - # for older or newer versions if such versions are installed on the system. - - installed_version = V(module.__version__) - if source_version != installed_version: - abort("Installed version does not match source version") - - docwriter = ApiDocWriter(package, rst_extension='.rst', - other_defines=other_defines) - - docwriter.package_skip_patterns += [r'\.%s$' % package, - r'.*test.*$', - r'\.version.*$'] - docwriter.write_api_docs(outdir) - docwriter.write_index(outdir, 'index', relative_to=outdir) - print('%d files written' % len(docwriter.written_modules)) - - -if __name__ == '__main__': - package = sys.argv[1] - outdir = sys.argv[2] - try: - other_defines = sys.argv[3] - except IndexError: - other_defines = True - else: - other_defines = other_defines in ('True', 'true', '1') - - writeapi(package, outdir, other_defines=other_defines) diff --git a/docs/Makefile b/docs/Makefile new file mode 100644 index 00000000..69fe55ec --- /dev/null +++ b/docs/Makefile @@ -0,0 +1,19 @@ +# Minimal makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +SOURCEDIR = source +BUILDDIR = build + +# Put it first so that "make" without argument is like "make help". +help: + @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) + +.PHONY: help Makefile + +# Catch-all target: route all unknown targets to Sphinx using the new +# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). +%: Makefile + @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) \ No newline at end of file diff --git a/docs/make.bat b/docs/make.bat new file mode 100644 index 00000000..543c6b13 --- /dev/null +++ b/docs/make.bat @@ -0,0 +1,35 @@ +@ECHO OFF + +pushd %~dp0 + +REM Command file for Sphinx documentation + +if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=sphinx-build +) +set SOURCEDIR=source +set BUILDDIR=build + +if "%1" == "" goto help + +%SPHINXBUILD% >NUL 2>NUL +if errorlevel 9009 ( + echo. + echo.The 'sphinx-build' command was not found. Make sure you have Sphinx + echo.installed, then set the SPHINXBUILD environment variable to point + echo.to the full path of the 'sphinx-build' executable. Alternatively you + echo.may add the Sphinx directory to PATH. + echo. + echo.If you don't have Sphinx installed, grab it from + echo.http://sphinx-doc.org/ + exit /b 1 +) + +%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% +goto end + +:help +%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% + +:end +popd diff --git a/docs/source/.index.rst.swp b/docs/source/.index.rst.swp new file mode 100644 index 00000000..357cab7c Binary files /dev/null and b/docs/source/.index.rst.swp differ diff --git a/docs/source/conf.py b/docs/source/conf.py new file mode 100644 index 00000000..767f7017 --- /dev/null +++ b/docs/source/conf.py @@ -0,0 +1,180 @@ +# -*- coding: utf-8 -*- +# +# Configuration file for the Sphinx documentation builder. +# +# This file does only contain a selection of the most common options. For a +# full list see the documentation: +# http://www.sphinx-doc.org/en/master/config + +# -- Path setup -------------------------------------------------------------- + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +# +# import os +# import sys +# sys.path.insert(0, os.path.abspath('.')) + + +# -- Project information ----------------------------------------------------- + +project = u'dmipy' +copyright = u'2020, Rutger Fick' +author = u'Rutger Fick' + +# The short X.Y version +version = u'' +# The full version, including alpha/beta/rc tags +release = u'1.0.3' + + +# -- General configuration --------------------------------------------------- + +# If your documentation needs a minimal Sphinx version, state it here. +# +# needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + 'sphinx.ext.autodoc', + 'sphinx.ext.mathjax', + 'sphinx.ext.viewcode', + 'sphinx.ext.napoleon', +] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# +# source_suffix = ['.rst', '.md'] +source_suffix = '.rst' + +# The master toctree document. +master_doc = 'index' + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This pattern also affects html_static_path and html_extra_path. +exclude_patterns = [] + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = None + + +# -- Options for HTML output ------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +html_theme = 'alabaster' + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +# +# html_theme_options = {} + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + +# Custom sidebar templates, must be a dictionary that maps document names +# to template names. +# +# The default sidebars (for documents that don't match any pattern) are +# defined by theme itself. Builtin themes are using these templates by +# default: ``['localtoc.html', 'relations.html', 'sourcelink.html', +# 'searchbox.html']``. +# +# html_sidebars = {} + + +# -- Options for HTMLHelp output --------------------------------------------- + +# Output file base name for HTML help builder. +htmlhelp_basename = 'dmipydoc' + + +# -- Options for LaTeX output ------------------------------------------------ + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # + # 'papersize': 'letterpaper', + + # The font size ('10pt', '11pt' or '12pt'). + # + # 'pointsize': '10pt', + + # Additional stuff for the LaTeX preamble. + # + # 'preamble': '', + + # Latex figure (float) alignment + # + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + (master_doc, 'dmipy.tex', u'dmipy Documentation', + u'Rutger Fick', 'manual'), +] + + +# -- Options for manual page output ------------------------------------------ + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + (master_doc, 'dmipy', u'dmipy Documentation', + [author], 1) +] + + +# -- Options for Texinfo output ---------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + (master_doc, 'dmipy', u'dmipy Documentation', + author, 'dmipy', 'One line description of project.', + 'Miscellaneous'), +] + + +# -- Options for Epub output ------------------------------------------------- + +# Bibliographic Dublin Core info. +epub_title = project + +# The unique identifier of the text. This can be a ISBN number +# or the project homepage. +# +# epub_identifier = '' + +# A unique identification for the text. +# +# epub_uid = '' + +# A list of files that should not be packed into the epub file. +epub_exclude_files = ['search.html'] + + +# -- Extension configuration ------------------------------------------------- diff --git a/docs/source/dmipy.core.rst b/docs/source/dmipy.core.rst new file mode 100644 index 00000000..b535789b --- /dev/null +++ b/docs/source/dmipy.core.rst @@ -0,0 +1,62 @@ +dmipy.core package +================== + +Submodules +---------- + +dmipy.core.acquisition\_scheme module +------------------------------------- + +.. automodule:: dmipy.core.acquisition_scheme + :members: + :undoc-members: + :show-inheritance: + +dmipy.core.constants module +--------------------------- + +.. automodule:: dmipy.core.constants + :members: + :undoc-members: + :show-inheritance: + +dmipy.core.fitted\_modeling\_framework module +--------------------------------------------- + +.. automodule:: dmipy.core.fitted_modeling_framework + :members: + :undoc-members: + :show-inheritance: + +dmipy.core.gradient\_conversions module +--------------------------------------- + +.. automodule:: dmipy.core.gradient_conversions + :members: + :undoc-members: + :show-inheritance: + +dmipy.core.modeling\_framework module +------------------------------------- + +.. automodule:: dmipy.core.modeling_framework + :members: + :undoc-members: + :show-inheritance: + +dmipy.core.signal\_model\_properties module +------------------------------------------- + +.. automodule:: dmipy.core.signal_model_properties + :members: + :undoc-members: + :show-inheritance: + + +Module contents +--------------- + +.. automodule:: dmipy.core + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/source/dmipy.custom_optimizers.rst b/docs/source/dmipy.custom_optimizers.rst new file mode 100644 index 00000000..909aaf9b --- /dev/null +++ b/docs/source/dmipy.custom_optimizers.rst @@ -0,0 +1,30 @@ +dmipy.custom\_optimizers package +================================ + +Submodules +---------- + +dmipy.custom\_optimizers.intra\_voxel\_incoherent\_motion module +---------------------------------------------------------------- + +.. automodule:: dmipy.custom_optimizers.intra_voxel_incoherent_motion + :members: + :undoc-members: + :show-inheritance: + +dmipy.custom\_optimizers.single\_shell\_three\_tissue\_csd module +----------------------------------------------------------------- + +.. automodule:: dmipy.custom_optimizers.single_shell_three_tissue_csd + :members: + :undoc-members: + :show-inheritance: + + +Module contents +--------------- + +.. automodule:: dmipy.custom_optimizers + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/source/dmipy.data.rst b/docs/source/dmipy.data.rst new file mode 100644 index 00000000..5bba1e83 --- /dev/null +++ b/docs/source/dmipy.data.rst @@ -0,0 +1,30 @@ +dmipy.data package +================== + +Submodules +---------- + +dmipy.data.saved\_acquisition\_schemes module +--------------------------------------------- + +.. automodule:: dmipy.data.saved_acquisition_schemes + :members: + :undoc-members: + :show-inheritance: + +dmipy.data.saved\_data module +----------------------------- + +.. automodule:: dmipy.data.saved_data + :members: + :undoc-members: + :show-inheritance: + + +Module contents +--------------- + +.. automodule:: dmipy.data + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/source/dmipy.distributions.rst b/docs/source/dmipy.distributions.rst new file mode 100644 index 00000000..b953d079 --- /dev/null +++ b/docs/source/dmipy.distributions.rst @@ -0,0 +1,30 @@ +dmipy.distributions package +=========================== + +Submodules +---------- + +dmipy.distributions.distribute\_models module +--------------------------------------------- + +.. automodule:: dmipy.distributions.distribute_models + :members: + :undoc-members: + :show-inheritance: + +dmipy.distributions.distributions module +---------------------------------------- + +.. automodule:: dmipy.distributions.distributions + :members: + :undoc-members: + :show-inheritance: + + +Module contents +--------------- + +.. automodule:: dmipy.distributions + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/source/dmipy.hcp_interface.rst b/docs/source/dmipy.hcp_interface.rst new file mode 100644 index 00000000..7d86f1b8 --- /dev/null +++ b/docs/source/dmipy.hcp_interface.rst @@ -0,0 +1,22 @@ +dmipy.hcp\_interface package +============================ + +Submodules +---------- + +dmipy.hcp\_interface.downloader\_aws module +------------------------------------------- + +.. automodule:: dmipy.hcp_interface.downloader_aws + :members: + :undoc-members: + :show-inheritance: + + +Module contents +--------------- + +.. automodule:: dmipy.hcp_interface + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/source/dmipy.optimizers.rst b/docs/source/dmipy.optimizers.rst new file mode 100644 index 00000000..d2704a2f --- /dev/null +++ b/docs/source/dmipy.optimizers.rst @@ -0,0 +1,46 @@ +dmipy.optimizers package +======================== + +Submodules +---------- + +dmipy.optimizers.amico\_cvxpy module +------------------------------------ + +.. automodule:: dmipy.optimizers.amico_cvxpy + :members: + :undoc-members: + :show-inheritance: + +dmipy.optimizers.brute2fine module +---------------------------------- + +.. automodule:: dmipy.optimizers.brute2fine + :members: + :undoc-members: + :show-inheritance: + +dmipy.optimizers.mix module +--------------------------- + +.. automodule:: dmipy.optimizers.mix + :members: + :undoc-members: + :show-inheritance: + +dmipy.optimizers.multi\_tissue\_convex\_optimizer module +-------------------------------------------------------- + +.. automodule:: dmipy.optimizers.multi_tissue_convex_optimizer + :members: + :undoc-members: + :show-inheritance: + + +Module contents +--------------- + +.. automodule:: dmipy.optimizers + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/source/dmipy.optimizers_fod.rst b/docs/source/dmipy.optimizers_fod.rst new file mode 100644 index 00000000..6e72ad46 --- /dev/null +++ b/docs/source/dmipy.optimizers_fod.rst @@ -0,0 +1,30 @@ +dmipy.optimizers\_fod package +============================= + +Submodules +---------- + +dmipy.optimizers\_fod.csd\_cvxpy module +--------------------------------------- + +.. automodule:: dmipy.optimizers_fod.csd_cvxpy + :members: + :undoc-members: + :show-inheritance: + +dmipy.optimizers\_fod.csd\_tournier module +------------------------------------------ + +.. automodule:: dmipy.optimizers_fod.csd_tournier + :members: + :undoc-members: + :show-inheritance: + + +Module contents +--------------- + +.. automodule:: dmipy.optimizers_fod + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/source/dmipy.rst b/docs/source/dmipy.rst new file mode 100644 index 00000000..7386f354 --- /dev/null +++ b/docs/source/dmipy.rst @@ -0,0 +1,38 @@ +dmipy package +============= + +Subpackages +----------- + +.. toctree:: + + dmipy.core + dmipy.custom_optimizers + dmipy.data + dmipy.distributions + dmipy.hcp_interface + dmipy.optimizers + dmipy.optimizers_fod + dmipy.signal_models + dmipy.tissue_response + dmipy.utils + +Submodules +---------- + +dmipy.version module +-------------------- + +.. automodule:: dmipy.version + :members: + :undoc-members: + :show-inheritance: + + +Module contents +--------------- + +.. automodule:: dmipy + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/source/dmipy.signal_models.rst b/docs/source/dmipy.signal_models.rst new file mode 100644 index 00000000..18eaaa2f --- /dev/null +++ b/docs/source/dmipy.signal_models.rst @@ -0,0 +1,62 @@ +dmipy.signal\_models package +============================ + +Submodules +---------- + +dmipy.signal\_models.capped\_cylinder\_models module +---------------------------------------------------- + +.. automodule:: dmipy.signal_models.capped_cylinder_models + :members: + :undoc-members: + :show-inheritance: + +dmipy.signal\_models.cylinder\_models module +-------------------------------------------- + +.. automodule:: dmipy.signal_models.cylinder_models + :members: + :undoc-members: + :show-inheritance: + +dmipy.signal\_models.gaussian\_models module +-------------------------------------------- + +.. automodule:: dmipy.signal_models.gaussian_models + :members: + :undoc-members: + :show-inheritance: + +dmipy.signal\_models.plane\_models module +----------------------------------------- + +.. automodule:: dmipy.signal_models.plane_models + :members: + :undoc-members: + :show-inheritance: + +dmipy.signal\_models.sphere\_models module +------------------------------------------ + +.. automodule:: dmipy.signal_models.sphere_models + :members: + :undoc-members: + :show-inheritance: + +dmipy.signal\_models.tissue\_response\_models module +---------------------------------------------------- + +.. automodule:: dmipy.signal_models.tissue_response_models + :members: + :undoc-members: + :show-inheritance: + + +Module contents +--------------- + +.. automodule:: dmipy.signal_models + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/source/dmipy.tissue_response.rst b/docs/source/dmipy.tissue_response.rst new file mode 100644 index 00000000..1a651ddb --- /dev/null +++ b/docs/source/dmipy.tissue_response.rst @@ -0,0 +1,30 @@ +dmipy.tissue\_response package +============================== + +Submodules +---------- + +dmipy.tissue\_response.three\_tissue\_response module +----------------------------------------------------- + +.. automodule:: dmipy.tissue_response.three_tissue_response + :members: + :undoc-members: + :show-inheritance: + +dmipy.tissue\_response.white\_matter\_response module +----------------------------------------------------- + +.. automodule:: dmipy.tissue_response.white_matter_response + :members: + :undoc-members: + :show-inheritance: + + +Module contents +--------------- + +.. automodule:: dmipy.tissue_response + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/source/dmipy.utils.rst b/docs/source/dmipy.utils.rst new file mode 100644 index 00000000..6cf4034d --- /dev/null +++ b/docs/source/dmipy.utils.rst @@ -0,0 +1,54 @@ +dmipy.utils package +=================== + +Submodules +---------- + +dmipy.utils.construct\_observation\_matrix module +------------------------------------------------- + +.. automodule:: dmipy.utils.construct_observation_matrix + :members: + :undoc-members: + :show-inheritance: + +dmipy.utils.spherical\_convolution module +----------------------------------------- + +.. automodule:: dmipy.utils.spherical_convolution + :members: + :undoc-members: + :show-inheritance: + +dmipy.utils.spherical\_mean module +---------------------------------- + +.. automodule:: dmipy.utils.spherical_mean + :members: + :undoc-members: + :show-inheritance: + +dmipy.utils.utils module +------------------------ + +.. automodule:: dmipy.utils.utils + :members: + :undoc-members: + :show-inheritance: + +dmipy.utils.viz module +---------------------- + +.. automodule:: dmipy.utils.viz + :members: + :undoc-members: + :show-inheritance: + + +Module contents +--------------- + +.. automodule:: dmipy.utils + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/source/index.rst b/docs/source/index.rst new file mode 100644 index 00000000..683ea026 --- /dev/null +++ b/docs/source/index.rst @@ -0,0 +1,15 @@ +Dmipy: Diffusion MRI-based Microstructure Imaging in Python +=========================================================== + +.. toctree:: + :maxdepth: 2 + :caption: Contents: + + modules + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` diff --git a/docs/source/modules.rst b/docs/source/modules.rst new file mode 100644 index 00000000..7d706a81 --- /dev/null +++ b/docs/source/modules.rst @@ -0,0 +1,7 @@ +dmipy +===== + +.. toctree:: + :maxdepth: 4 + + dmipy