Changeset a5b8477 in sasmodels for doc


Ignore:
Timestamp:
Apr 13, 2016 8:17:10 PM (9 years ago)
Author:
Paul Kienzle <pkienzle@…>
Branches:
master, core_shell_microgels, costrafo411, magnetic_model, release_v0.94, release_v0.95, ticket-1257-vesicle-product, ticket_1156, ticket_1265_superball, ticket_822_more_unit_tests
Children:
0ce5710
Parents:
60f03de
Message:

update docs to work with the new ModelInfo/ParameterTable? classes

Location:
doc
Files:
3 edited

Legend:

Unmodified
Added
Removed
  • doc/genapi.py

    r3d5c6f8 ra5b8477  
    5959    #('alignment', 'GPU data alignment [unused]'), 
    6060    ('bumps_model', 'Bumps interface'), 
     61    ('compare', 'Compare models on different compute engines'), 
    6162    ('convert', 'Sasview to sasmodel converter'), 
    6263    ('core', 'Model access'), 
     64    ('data', 'Data layout and plotting routines'), 
     65    ('details', 'Parameter packing for kernel calls'), 
    6366    ('direct_model', 'Simple interface'), 
    6467    ('exception', 'Annotate exceptions'), 
     68    #('frozendict', 'Freeze a dictionary to make it immutable'), 
    6569    ('generate', 'Model parser'), 
     70    ('kernel', 'Evaluator type definitions'), 
    6671    ('kernelcl', 'OpenCL model evaluator'), 
    6772    ('kerneldll', 'Ctypes model evaluator'), 
    6873    ('kernelpy', 'Python model evaluator'), 
     74    ('list_pars', 'Identify all parameters in all models'), 
     75    ('mixture', 'Mixture model evaluator'), 
    6976    ('model_test', 'Unit test support'), 
     77    ('modelinfo', 'Parameter and model definitions'), 
     78    ('product', 'Product model evaluator'), 
    7079    ('resolution', '1-D resolution functions'), 
    7180    ('resolution2d', '2-D resolution functions'), 
    7281    ('sasview_model', 'Sasview interface'), 
    73     ('sesans', 'SESANS model evaluator'), 
     82    ('sesans', 'SESANS calculation routines'), 
     83    #('transition', 'Model stepper for automatic model selection'), 
    7484    ('weights', 'Distribution functions'), 
    75     #('transition', 'Model stepper for automatic model selection'), 
    7685] 
    7786package='sasmodels' 
  • doc/genmodel.py

    r89f4163 ra5b8477  
     1from __future__ import print_function 
     2 
    13import sys, os, math, re 
    24import numpy as np 
    35import matplotlib.pyplot as plt 
    4 import pylab 
    56sys.path.insert(0, os.path.abspath('..')) 
    67from sasmodels import generate, core 
     
    89from sasmodels.data import empty_data1D, empty_data2D 
    910 
    10  
    11 # Convert ../sasmodels/models/name.py to name 
    12 model_name = os.path.basename(sys.argv[1])[:-3] 
    13 model_info = core.load_model_info(model_name) 
    14 model = core.build_model(model_info) 
    15  
    16 # Load the doc string from the module definition file and store it in rst 
    17 docstr = generate.make_doc(model_info) 
    18  
    19  
    20 # Calculate 1D curve for default parameters 
    21 pars = dict((p.name, p.default) for p in model_info['parameters']) 
    22  
    23 # Plotting ranges and options 
    24 opts = { 
    25     'xscale'    : 'log', 
    26     'yscale'    : 'log' if not model_info['structure_factor'] else 'linear', 
    27     'zscale'    : 'log' if not model_info['structure_factor'] else 'linear', 
    28     'q_min'     : 0.001, 
    29     'q_max'     : 1.0, 
    30     'nq'        : 1000, 
    31     'nq2d'      : 1000, 
    32     'vmin'      : 1e-3,  # floor for the 2D data results 
    33     'qx_max'    : 0.5, 
    34     #'colormap'  : 'gist_ncar', 
    35     'colormap'  : 'nipy_spectral', 
    36     #'colormap'  : 'jet', 
    37 } 
    38  
     11try: 
     12    from typing import Dict, Any 
     13except ImportError: 
     14    pass 
     15else: 
     16    from matplotlib.axes import Axes 
     17    from sasmodels.kernel import KernelModel 
     18    from sasmodels.modelinfo import ModelInfo 
    3919 
    4020def plot_1d(model, opts, ax): 
     21    # type: (KernelModel, Dict[str, Any], Axes) -> None 
     22    """ 
     23    Create a 1-D image. 
     24    """ 
    4125    q_min, q_max, nq = opts['q_min'], opts['q_max'], opts['nq'] 
    4226    q_min = math.log10(q_min) 
     
    4731    Iq1D = calculator() 
    4832 
    49     ax.plot(q, Iq1D, color='blue', lw=2, label=model_info['name']) 
     33    ax.plot(q, Iq1D, color='blue', lw=2, label=model.info.name) 
    5034    ax.set_xlabel(r'$Q \/(\AA^{-1})$') 
    5135    ax.set_ylabel(r'$I(Q) \/(\mathrm{cm}^{-1})$') 
     
    5539 
    5640def plot_2d(model, opts, ax): 
     41    # type: (KernelModel, Dict[str, Any], Axes) -> None 
     42    """ 
     43    Create a 2-D image. 
     44    """ 
    5745    qx_max, nq2d = opts['qx_max'], opts['nq2d'] 
    58     q = np.linspace(-qx_max, qx_max, nq2d) 
     46    q = np.linspace(-qx_max, qx_max, nq2d) # type: np.ndarray 
    5947    data2d = empty_data2D(q, resolution=0.0) 
    6048    calculator = DirectModel(data2d, model) 
     
    6452        Iq2D = np.log(np.clip(Iq2D, opts['vmin'], np.inf)) 
    6553    ax.imshow(Iq2D, interpolation='nearest', aspect=1, origin='lower', 
    66         extent=[-qx_max, qx_max, -qx_max, qx_max], cmap=opts['colormap']) 
     54              extent=[-qx_max, qx_max, -qx_max, qx_max], cmap=opts['colormap']) 
    6755    ax.set_xlabel(r'$Q_x \/(\AA^{-1})$') 
    6856    ax.set_ylabel(r'$Q_y \/(\AA^{-1})$') 
    6957 
    70 # Generate image  
    71 fig_height = 3.0 # in 
    72 fig_left = 0.6 # in 
    73 fig_right = 0.5 # in 
    74 fig_top = 0.6*0.25 # in 
    75 fig_bottom = 0.6*0.75 
    76 if model_info['has_2d']: 
    77     plot_height = fig_height - (fig_top+fig_bottom) 
    78     plot_width = plot_height 
    79     fig_width = 2*(plot_width + fig_left + fig_right) 
    80     aspect = (fig_width, fig_height) 
    81     ratio = aspect[0]/aspect[1] 
    82     ax_left = fig_left/fig_width 
    83     ax_bottom = fig_bottom/fig_height 
    84     ax_height = plot_height/fig_height 
    85     ax_width = ax_height/ratio # square axes 
    86     fig = plt.figure(figsize=aspect) 
    87     ax2d = fig.add_axes([0.5+ax_left, ax_bottom, ax_width, ax_height]) 
    88     plot_2d(model, opts, ax2d) 
    89     ax1d = fig.add_axes([ax_left, ax_bottom, ax_width, ax_height]) 
    90     plot_1d(model, opts, ax1d) 
    91     #ax.set_aspect('square') 
    92 else: 
    93     plot_height = fig_height - (fig_top+fig_bottom) 
    94     plot_width = (1+np.sqrt(5))/2*fig_height 
    95     fig_width = plot_width + fig_left + fig_right 
    96     ax_left = fig_left/fig_width 
    97     ax_bottom = fig_bottom/fig_height 
    98     ax_width = plot_width/fig_width 
    99     ax_height = plot_height/fig_height 
    100     aspect = (fig_width, fig_height) 
    101     fig = plt.figure(figsize=aspect) 
    102     ax1d = fig.add_axes([ax_left, ax_bottom, ax_width, ax_height]) 
    103     plot_1d(model, opts, ax1d) 
     58def figfile(model_info): 
     59    # type: (ModelInfo) -> str 
     60    return model_info.id + '_autogenfig.png' 
    10461 
    105 # Save image in model/img 
    106 figname = model_name + '_autogenfig.png' 
    107 filename = os.path.join('model', 'img', figname) 
    108 plt.savefig(filename, bbox_inches='tight') 
    109 #print "figure saved in",filename 
     62def make_figure(model_info, opts): 
     63    # type: (ModelInfo, Dict[str, Any]) -> None 
     64    """ 
     65    Generate the figure file to include in the docs. 
     66    """ 
     67    model = core.build_model(model_info) 
    11068 
    111 # Auto caption for figure 
    112 captionstr = '\n' 
    113 captionstr += '.. figure:: img/' + model_info['id'] + '_autogenfig.png\n' 
    114 captionstr += '\n' 
    115 if model_info['has_2d']: 
    116     captionstr += '    1D and 2D plots corresponding to the default parameters of the model.\n' 
    117 else: 
    118     captionstr += '    1D plot corresponding to the default parameters of the model.\n' 
    119 captionstr += '\n' 
     69    fig_height = 3.0 # in 
     70    fig_left = 0.6 # in 
     71    fig_right = 0.5 # in 
     72    fig_top = 0.6*0.25 # in 
     73    fig_bottom = 0.6*0.75 
     74    if model_info.parameters.has_2d: 
     75        plot_height = fig_height - (fig_top+fig_bottom) 
     76        plot_width = plot_height 
     77        fig_width = 2*(plot_width + fig_left + fig_right) 
     78        aspect = (fig_width, fig_height) 
     79        ratio = aspect[0]/aspect[1] 
     80        ax_left = fig_left/fig_width 
     81        ax_bottom = fig_bottom/fig_height 
     82        ax_height = plot_height/fig_height 
     83        ax_width = ax_height/ratio # square axes 
     84        fig = plt.figure(figsize=aspect) 
     85        ax2d = fig.add_axes([0.5+ax_left, ax_bottom, ax_width, ax_height]) 
     86        plot_2d(model, opts, ax2d) 
     87        ax1d = fig.add_axes([ax_left, ax_bottom, ax_width, ax_height]) 
     88        plot_1d(model, opts, ax1d) 
     89        #ax.set_aspect('square') 
     90    else: 
     91        plot_height = fig_height - (fig_top+fig_bottom) 
     92        plot_width = (1+np.sqrt(5))/2*fig_height 
     93        fig_width = plot_width + fig_left + fig_right 
     94        ax_left = fig_left/fig_width 
     95        ax_bottom = fig_bottom/fig_height 
     96        ax_width = plot_width/fig_width 
     97        ax_height = plot_height/fig_height 
     98        aspect = (fig_width, fig_height) 
     99        fig = plt.figure(figsize=aspect) 
     100        ax1d = fig.add_axes([ax_left, ax_bottom, ax_width, ax_height]) 
     101        plot_1d(model, opts, ax1d) 
    120102 
    121 # Add figure reference and caption to documentation (at end, before References) 
    122 pattern = '\*\*REFERENCE' 
    123 m = re.search(pattern, docstr.upper()) 
     103    # Save image in model/img 
     104    path = os.path.join('model', 'img', figfile(model_info)) 
     105    plt.savefig(path, bbox_inches='tight') 
     106    #print("figure saved in",path) 
    124107 
    125 if m: 
    126     docstr1 = docstr[:m.start()] 
    127     docstr2 = docstr[m.start():] 
    128     docstr = docstr1 + captionstr + docstr2 
    129 else: 
    130     print '------------------------------------------------------------------' 
    131     print 'References NOT FOUND for model: ', model_info['id'] 
    132     print '------------------------------------------------------------------' 
    133     docstr = docstr + captionstr 
     108def gen_docs(model_info): 
     109    # type: (ModelInfo) -> None 
     110    """ 
     111    Generate the doc string with the figure inserted before the references. 
     112    """ 
    134113 
    135 open(sys.argv[2],'w').write(docstr) 
     114    # Load the doc string from the module definition file and store it in rst 
     115    docstr = generate.make_doc(model_info) 
     116 
     117    # Auto caption for figure 
     118    captionstr = '\n' 
     119    captionstr += '.. figure:: img/' + figfile(model_info) + '\n' 
     120    captionstr += '\n' 
     121    if model_info.parameters.has_2d: 
     122        captionstr += '    1D and 2D plots corresponding to the default parameters of the model.\n' 
     123    else: 
     124        captionstr += '    1D plot corresponding to the default parameters of the model.\n' 
     125    captionstr += '\n' 
     126 
     127    # Add figure reference and caption to documentation (at end, before References) 
     128    pattern = '\*\*REFERENCE' 
     129    match = re.search(pattern, docstr.upper()) 
     130 
     131    if match: 
     132        docstr1 = docstr[:match.start()] 
     133        docstr2 = docstr[match.start():] 
     134        docstr = docstr1 + captionstr + docstr2 
     135    else: 
     136        print('------------------------------------------------------------------') 
     137        print('References NOT FOUND for model: ', model_info.id) 
     138        print('------------------------------------------------------------------') 
     139        docstr += captionstr 
     140 
     141    open(sys.argv[2],'w').write(docstr) 
     142 
     143def process_model(path): 
     144    # type: (str) -> None 
     145    """ 
     146    Generate doc file and image file for the given model definition file. 
     147    """ 
     148 
     149    # Load the model file 
     150    model_name = os.path.basename(path)[:-3] 
     151    model_info = core.load_model_info(model_name) 
     152 
     153    # Plotting ranges and options 
     154    opts = { 
     155        'xscale'    : 'log', 
     156        'yscale'    : 'log' if not model_info.structure_factor else 'linear', 
     157        'zscale'    : 'log' if not model_info.structure_factor else 'linear', 
     158        'q_min'     : 0.001, 
     159        'q_max'     : 1.0, 
     160        'nq'        : 1000, 
     161        'nq2d'      : 1000, 
     162        'vmin'      : 1e-3,  # floor for the 2D data results 
     163        'qx_max'    : 0.5, 
     164        #'colormap'  : 'gist_ncar', 
     165        'colormap'  : 'nipy_spectral', 
     166        #'colormap'  : 'jet', 
     167    } 
     168 
     169    # Generate the RST file and the figure.  Order doesn't matter. 
     170    gen_docs(model_info) 
     171    make_figure(model_info, opts) 
     172 
     173if __name__ == "__main__": 
     174    process_model(sys.argv[1]) 
  • doc/gentoc.py

    r5041682 ra5b8477  
    99from sasmodels.core import load_model_info 
    1010 
     11try: 
     12    from typing import Optional, BinaryIO, List, Dict 
     13except ImportError: 
     14    pass 
     15else: 
     16    from sasmodels.modelinfo import ModelInfo 
    1117 
    1218TEMPLATE="""\ 
     
    2733 
    2834def _make_category(category_name, label, title, parent=None): 
     35    # type: (str, str, str, Optional[BinaryIO]) -> BinaryIO 
    2936    file = open(joinpath(MODEL_TOC_PATH, category_name+".rst"), "w") 
    3037    file.write(TEMPLATE%{'label':label, 'title':title, 'bar':'*'*len(title)}) 
     
    3441 
    3542def _add_subcategory(category_name, parent): 
     43    # type: (str, BinaryIO) -> None 
    3644    parent.write("    %s.rst\n"%category_name) 
    3745 
    3846def _add_model(file, model_name): 
     47    # type: (IO[str], str) -> None 
    3948    file.write("    ../../model/%s.rst\n"%model_name) 
    4049 
    4150def _maybe_make_category(category, models, cat_files, model_toc): 
     51    # type: (str, List[str], Dict[str, BinaryIO], BinaryIO) -> None 
    4252    if category not in cat_files: 
    4353        print("Unexpected category %s containing"%category, models, file=sys.stderr) 
     
    4656 
    4757def generate_toc(model_files): 
     58    # type: (List[str]) -> None 
    4859    if not model_files: 
    4960        print("gentoc needs a list of model files", file=sys.stderr) 
    5061 
    5162    # find all categories 
    52     category = {} 
     63    category = {} # type: Dict[str, List[str]] 
    5364    for item in model_files: 
    5465        # assume model is in sasmodels/models/name.py, and ignore the full path 
     
    5667        if model_name.startswith('_'): continue 
    5768        model_info = load_model_info(model_name) 
    58         if model_info['category'] is None: 
     69        if model_info.category is None: 
    5970            print("Missing category for", item, file=sys.stderr) 
    6071        else: 
    61             category.setdefault(model_info['category'],[]).append(model_name) 
     72            category.setdefault(model_info.category,[]).append(model_name) 
    6273 
    6374    # Check category names 
Note: See TracChangeset for help on using the changeset viewer.