source: sasmodels/sasmodels/product.py @ ce896fd

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

improved handling of vector parameters; remove compile errors from onion.c

  • Property mode set to 100644
File size: 6.7 KB
Line 
1"""
2Product model
3-------------
4
5The product model multiplies the structure factor by the form factor,
6modulated by the effective radius of the form.  The resulting model
7has a attributes of both the model description (with parameters, etc.)
8and the module evaluator (with call, release, etc.).
9
10To use it, first load form factor P and structure factor S, then create
11*ProductModel(P, S)*.
12"""
13import numpy as np
14
15from .core import call_ER_VR
16
17SCALE=0
18BACKGROUND=1
19RADIUS_EFFECTIVE=2
20VOLFRACTION=3
21
22def make_product_info(p_info, s_info):
23    """
24    Create info block for product model.
25    """
26    p_id, p_name, p_pars = p_info['id'], p_info['name'], p_info['parameters']
27    s_id, s_name, s_pars = s_info['id'], s_info['name'], s_info['parameters']
28    # We require models to start with scale and background
29    assert s_pars[SCALE].name == 'scale'
30    assert s_pars[BACKGROUND].name == 'background'
31    # We require structure factors to start with effect radius and volfraction
32    assert s_pars[RADIUS_EFFECTIVE].name == 'radius_effective'
33    assert s_pars[VOLFRACTION].name == 'volfraction'
34    # Combine the parameter sets.  We are skipping the first three
35    # parameters of S since scale, background are defined in P and
36    # effect_radius is set from P.ER().
37    pars = p_pars + s_pars[3:]
38    # check for duplicates; can't use assertion since they may never be checked
39    if len(set(p.name for p in pars)) != len(pars):
40        raise ValueError("Duplicate parameters in %s and %s"%(p_id))
41    # For comparison with sasview, determine the old parameters.
42    oldname = [p_info['oldname'], s_info['oldname']]
43    oldpars = {'scale':'scale_factor'}
44    oldpars.update(p_info['oldpars'])
45    oldpars.update(s_info['oldpars'])
46
47    model_info = {}
48    model_info['id'] = '*'.join((p_id, s_id))
49    model_info['name'] = ' X '.join((p_name, s_name))
50    model_info['filename'] = None
51    model_info['title'] = 'Product of %s and structure factor %s'%(p_name, s_name)
52    model_info['description'] = model_info['title']
53    model_info['docs'] = model_info['title']
54    model_info['category'] = "custom"
55    model_info['parameters'] = pars
56    #model_info['single'] = p_info['single'] and s_info['single']
57    model_info['structure_factor'] = False
58    model_info['variant_info'] = None
59    #model_info['tests'] = []
60    #model_info['source'] = []
61    # Iq, Iqxy, form_volume, ER, VR and sesans
62    model_info['oldname'] = oldname
63    model_info['oldpars'] = oldpars
64    model_info['composition'] = ('product', [p_info, s_info])
65    return model_info
66
67class ProductModel(object):
68    def __init__(self, model_info, P, S):
69        self.info = model_info
70        self.P = P
71        self.S = S
72
73    def __call__(self, q_vectors):
74        # Note: may be sending the q_vectors to the GPU twice even though they
75        # are only needed once.  It would mess up modularity quite a bit to
76        # handle this optimally, especially since there are many cases where
77        # separate q vectors are needed (e.g., form in python and structure
78        # in opencl; or both in opencl, but one in single precision and the
79        # other in double precision).
80        p_kernel = self.P(q_vectors)
81        s_kernel = self.S(q_vectors)
82        return ProductKernel(self.info, p_kernel, s_kernel)
83
84    def release(self):
85        """
86        Free resources associated with the model.
87        """
88        self.P.release()
89        self.S.release()
90
91
92class ProductKernel(object):
93    def __init__(self, model_info, p_kernel, s_kernel):
94        dim = '2d' if p_kernel.q_input.is_2d else '1d'
95
96        # Need to know if we want 2D and magnetic parameters when constructing
97        # a parameter map.
98        par_map = {}
99        p_info = p_kernel.info['par_type']
100        s_info = s_kernel.info['par_type']
101        vol_pars = set(p_info['volume'])
102        if dim == '2d':
103            num_p_fixed = len(p_info['fixed-2d'])
104            num_p_pd = len(p_info['pd-2d'])
105            num_s_fixed = len(s_info['fixed-2d'])
106            num_s_pd = len(s_info['pd-2d']) - 1 # exclude effect_radius
107            # volume parameters are amongst the pd pars for P, not S
108            vol_par_idx = [k for k,v in enumerate(p_info['pd-2d'])
109                           if v in vol_pars]
110        else:
111            num_p_fixed = len(p_info['fixed-1d'])
112            num_p_pd = len(p_info['pd-1d'])
113            num_s_fixed = len(s_info['fixed-1d'])
114            num_s_pd = len(s_info['pd-1d']) - 1  # exclude effect_radius
115            # volume parameters are amongst the pd pars for P, not S
116            vol_par_idx = [k for k,v in enumerate(p_info['pd-1d'])
117                           if v in vol_pars]
118
119        start = 0
120        par_map['p_fixed'] = np.arange(start, start+num_p_fixed)
121        # User doesn't set scale, background or effect_radius for S in P*S,
122        # so borrow values from end of p_fixed.  This makes volfraction the
123        # first S parameter.
124        start += num_p_fixed
125        par_map['s_fixed'] = np.hstack(([start,start],
126                                        np.arange(start, start+num_s_fixed-2)))
127        par_map['volfraction'] = num_p_fixed
128        start += num_s_fixed-2
129        # vol pars offset from the start of pd pars
130        par_map['vol_pars'] = [start+k for k in vol_par_idx]
131        par_map['p_pd'] = np.arange(start, start+num_p_pd)
132        start += num_p_pd-1
133        par_map['s_pd'] = np.hstack((start,
134                                     np.arange(start, start+num_s_pd-1)))
135
136        self.fixed_pars = model_info['partype']['fixed-' + dim]
137        self.pd_pars = model_info['partype']['pd-' + dim]
138        self.info = model_info
139        self.p_kernel = p_kernel
140        self.s_kernel = s_kernel
141        self.par_map = par_map
142
143    def __call__(self, fixed_pars, pd_pars, cutoff=1e-5):
144        pars = fixed_pars + pd_pars
145        scale = pars[SCALE]
146        background = pars[BACKGROUND]
147        s_volfraction = pars[self.par_map['volfraction']]
148        p_fixed = [pars[k] for k in self.par_map['p_fixed']]
149        s_fixed = [pars[k] for k in self.par_map['s_fixed']]
150        p_pd = [pars[k] for k in self.par_map['p_pd']]
151        s_pd = [pars[k] for k in self.par_map['s_pd']]
152        vol_pars = [pars[k] for k in self.par_map['vol_pars']]
153
154        effect_radius, vol_ratio = call_ER_VR(self.p_kernel.info, vol_pars)
155
156        p_fixed[SCALE] = s_volfraction
157        p_fixed[BACKGROUND] = 0.0
158        s_fixed[SCALE] = scale
159        s_fixed[BACKGROUND] = 0.0
160        s_fixed[2] = s_volfraction/vol_ratio
161        s_pd[0] = [effect_radius], [1.0]
162
163        p_res = self.p_kernel(p_fixed, p_pd, cutoff)
164        s_res = self.s_kernel(s_fixed, s_pd, cutoff)
165        #print s_fixed, s_pd, p_fixed, p_pd
166
167        return p_res*s_res + background
168
169    def release(self):
170        self.p_kernel.release()
171        self.q_kernel.release()
172
Note: See TracBrowser for help on using the repository browser.