source: sasmodels/doc/genmodel.py @ 044a9c1

core_shell_microgelscostrafo411magnetic_modelrelease_v0.94release_v0.95ticket-1257-vesicle-productticket_1156ticket_1265_superballticket_822_more_unit_tests
Last change on this file since 044a9c1 was 044a9c1, checked in by gonzalezm, 8 years ago

Fixed details on images produced for doc

  • Property mode set to 100644
File size: 5.3 KB
Line 
1import sys, os, math, re
2import numpy as np
3import matplotlib.pyplot as plt
4import pylab
5sys.path.insert(0, os.path.abspath('..'))
6from sasmodels import generate, core
7from sasmodels.direct_model import DirectModel
8from sasmodels.data import empty_data1D, empty_data2D
9
10
11# Convert ../sasmodels/models/name.py to name
12model_name = os.path.basename(sys.argv[1])[:-3]
13model_info = core.load_model_info(model_name)
14model = core.build_model(model_info)
15
16# Load the doc string from the module definition file and store it in rst
17docstr = generate.make_doc(model_info)
18
19
20# Calculate 1D curve for default parameters
21pars = dict((p.name, p.default) for p in model_info['parameters'])
22
23# Plotting ranges and options
24opts = {
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'      : 100,
32    'vmin'      : 1e-3,  # floor for the 2D data results
33    'qx_max'    : 0.5,
34}
35
36
37def plot_1d(model, opts, ax):
38    q_min, q_max, nq = opts['q_min'], opts['q_max'], opts['nq']
39    q_min = math.log10(q_min)
40    q_max = math.log10(q_max)
41    q = np.logspace(q_min, q_max, nq)
42    data = empty_data1D(q)
43    calculator = DirectModel(data, model)
44    Iq1D = calculator()
45
46    ax.plot(q, Iq1D, color='blue', lw=2, label=model_info['name'])
47    ax.set_xlabel(r'$Q \/(\AA^{-1})$')
48    ax.set_ylabel(r'$I(Q) \/(\mathrm{cm}^{-1})$')
49    ax.set_xscale(opts['xscale'])
50    ax.set_yscale(opts['yscale'])
51    #ax.legend(loc='best')
52
53def plot_2d(model, opts, ax):
54    qx_max, nq2d = opts['qx_max'], opts['nq2d']
55    q = np.linspace(-qx_max, qx_max, nq2d)
56    data2d = empty_data2D(q, resolution=0.0)
57    calculator = DirectModel(data2d, model)
58    Iq2D = calculator() #background=0)
59    Iq2D = Iq2D.reshape(nq2d, nq2d)
60    if opts['zscale'] == 'log':
61        Iq2D = np.log(np.clip(Iq2D, opts['vmin'], np.inf))
62    ax.imshow(Iq2D, interpolation='nearest', aspect=1, origin='lower',
63        extent=[-qx_max, qx_max, -qx_max, qx_max], cmap=pylab.cm.jet)   
64    ax.set_xlabel(r'$Q_x \/(\AA^{-1})$')
65    ax.set_ylabel(r'$Q_y \/(\AA^{-1})$')
66
67#            im = self.subplot.imshow(output, interpolation='nearest',
68#                                     origin='lower',
69#                                     vmin=zmin_temp, vmax=self.zmax_2D,
70#                                     cmap=self.cmap,
71#                                     extent=(self.xmin_2D, self.xmax_2D,
72#                                             self.ymin_2D, self.ymax_2D))
73
74def ice_cm():
75    from matplotlib._cm import _Blues_data
76    from matplotlib import colors
77    from matplotlib import rcParams
78    def from_white(segments):
79        scale = 1.0/segments[0][1]
80        return [(k, v*scale, w*scale) for k, v, w in segments]
81    ice_data = dict((k,from_white(v)) for k,v in _Blues_data.items())
82    ice = colors.LinearSegmentedColormap("ice", ice_data, rcParams['image.lut'])
83    return ice
84
85
86# Generate image
87fig_height = 3.0 # in
88fig_left = 0.6 # in
89fig_right = 0.5 # in
90fig_top = 0.6*0.25 # in
91fig_bottom = 0.6*0.75
92if model_info['has_2d']:
93    plot_height = fig_height - (fig_top+fig_bottom)
94    plot_width = plot_height
95    fig_width = 2*(plot_width + fig_left + fig_right)
96    aspect = (fig_width, fig_height)
97    ratio = aspect[0]/aspect[1]
98    ax_left = fig_left/fig_width
99    ax_bottom = fig_bottom/fig_height
100    ax_height = plot_height/fig_height
101    ax_width = ax_height/ratio # square axes
102    fig = plt.figure(figsize=aspect)
103    ax2d = fig.add_axes([0.5+ax_left, ax_bottom, ax_width, ax_height])
104    plot_2d(model, opts, ax2d)
105    ax1d = fig.add_axes([ax_left, ax_bottom, ax_width, ax_height])
106    plot_1d(model, opts, ax1d)
107    #ax.set_aspect('square')
108else:
109    plot_height = fig_height - (fig_top+fig_bottom)
110    plot_width = (1+np.sqrt(5))/2*fig_height
111    fig_width = plot_width + fig_left + fig_right
112    ax_left = fig_left/fig_width
113    ax_bottom = fig_bottom/fig_height
114    ax_width = plot_width/fig_width
115    ax_height = plot_height/fig_height
116    aspect = (fig_width, fig_height)
117    fig = plt.figure(figsize=aspect)
118    ax1d = fig.add_axes([ax_left, ax_bottom, ax_width, ax_height])
119    plot_1d(model, opts, ax1d)
120
121# Save image in model/img
122figname = model_name + '_autogenfig.png'
123filename = os.path.join('model', 'img', figname)
124plt.savefig(filename, bbox_inches='tight')
125#print "figure saved in",filename
126
127# Auto caption for figure
128captionstr = '\n'
129captionstr += '.. figure:: img/' + model_info['id'] + '_autogenfig.png\n'
130captionstr += '\n'
131if model_info['has_2d']:
132    captionstr += '    1D and 2D plots corresponding to the default parameters of the model.\n'
133else:
134    captionstr += '    1D plot corresponding to the default parameters of the model.\n'
135captionstr += '\n'
136
137# Add figure reference and caption to documentation (at end, before References)
138pattern = '\*\*REFERENCE'
139m = re.search(pattern, docstr.upper())
140
141if m:
142    docstr1 = docstr[:m.start()]
143    docstr2 = docstr[m.start():]
144    docstr = docstr1 + captionstr + docstr2
145else:
146    print '------------------------------------------------------------------'
147    print 'References NOT FOUND for model: ', model_info['id']
148    print '------------------------------------------------------------------'
149    docstr = docstr + captionstr
150
151open(sys.argv[2],'w').write(docstr)
Note: See TracBrowser for help on using the repository browser.