source: sasmodels/doc/genmodel.py @ c094758

core_shell_microgelscostrafo411magnetic_modelrelease_v0.94release_v0.95ticket-1257-vesicle-productticket_1156ticket_1265_superballticket_822_more_unit_tests
Last change on this file since c094758 was c094758, checked in by Paul Kienzle <pkienzle@…>, 8 years ago

fix autogen 2d plots (mask passes 0 not 1)

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