Changeset cd5e29b in sasview for src/sas/models


Ignore:
Timestamp:
Sep 1, 2015 9:20:05 AM (9 years ago)
Author:
ajj
Branches:
master, ESS_GUI, ESS_GUI_Docs, ESS_GUI_batch_fitting, ESS_GUI_bumps_abstraction, ESS_GUI_iss1116, ESS_GUI_iss879, ESS_GUI_iss959, ESS_GUI_opencl, ESS_GUI_ordering, ESS_GUI_sync_sascalc, costrafo411, magnetic_scatt, release-4.1.1, release-4.1.2, release-4.2.2, release_4.0.1, ticket-1009, ticket-1094-headless, ticket-1242-2d-resolution, ticket-1243, ticket-1249, ticket885, unittest-saveload
Children:
f0d720b
Parents:
40c5104 (diff), 600bea1 (diff)
Note: this is a merge changeset, the changes displayed below correspond to the merge itself.
Use the (diff) links above to see all the changes relative to each parent.
Message:

Merge branch 'master' into sasmodels-integration

Location:
src/sas/models
Files:
3 added
18 edited

Legend:

Unmodified
Added
Removed
  • src/sas/models/BEPolyelectrolyte.py

    r79492222 rac7be54  
    1 """     
    2  Provide F(x) = K*1/(4*pi*Lb*(alpha)^(2))*(q^(2)+k2)/(1+(r02)^(2))*(q^(2)+k2)\ 
    3                        *(q^(2)-(12*h*C/b^(2))) 
     1""" 
    42 BEPolyelectrolyte as a BaseComponent model 
    53""" 
     
    1210        Class that evaluates a BEPolyelectrolyte. 
    1311         
    14         F(x) = K*1/(4*pi*Lb*(alpha)^(2))*(q^(2)+k2)/(1+(r02)^(2))*(q^(2)+k2)\ 
    15                        *(q^(2)-(12*h*C/b^(2)))  
     12        F(x) = K/(4 pi Lb (alpha)^(2)) (q^(2)+k2)/(1+(r02)^(2)) (q^(2)+k2)\ 
     13                        (q^(2)-(12 h C/b^(2))) 
    1614         
    17         The model has Eight parameters:  
    18             K        =  Constrast factor of the polymer 
    19             Lb       =  Bjerrum length 
    20             H        =  virial parameter 
    21             B        =  monomer length 
    22             Cs       =  Concentration of monovalent salt  
    23             alpha    =  ionazation degree  
     15        The model has Eight parameters:: 
     16 
     17            K        = Constrast factor of the polymer 
     18            Lb       = Bjerrum length 
     19            H        = virial parameter 
     20            B        = monomer length 
     21            Cs       = Concentration of monovalent salt 
     22            alpha    = ionazation degree 
    2423            C        = polymer molar concentration 
    2524            bkd      = background 
     
    7574        """ 
    7675            Evaluate   
    77             F(x) = K*1/(4*pi*Lb*(alpha)^(2))*(q^(2)+k2)/(1+(r02)^(2)) 
    78                 *(q^(2)+k2)*(q^(2)-(12*h*C/b^(2))) 
     76            F(x) = K 1/(4 pi Lb (alpha)^(2)) (q^(2)+k2)/(1+(r02)^(2)) 
     77                 (q^(2)+k2) (q^(2)-(12 h C/b^(2))) 
    7978         
    8079            has 3 internal parameters : 
    81                    The inverse Debye Length: K2 = 4*pi*Lb*(2*Cs+alpha*C) 
    82                    r02 =1/alpha/Ca^(0.5)*(B/(48*pi*Lb)^(0.5)) 
    83                    Ca = C*6.022136e-4 
     80                   The inverse Debye Length: K2 = 4 pi Lb (2 Cs+alpha C) 
     81                   r02 =1/alpha/Ca^(0.5) (B/(48 pi Lb)^(0.5)) 
     82                   Ca = 6.022136e-4 C 
    8483        """ 
    8584        Ca = self.params['c'] * 6.022136e-4 
  • src/sas/models/CoreMultiShellModel.py

    r79492222 re0c16ce  
    5353        ## parameters with orientation: can be removed since there is no orientational params 
    5454        self._set_orientation_params() 
    55                  
    56          
     55 
    5756    def _clone(self, obj): 
    5857        """ 
     
    6766 
    6867        return obj 
    69      
    70      
     68 
    7169    def _set_dispersion(self): 
    7270        """ 
    7371        model dispersions 
    7472        Polydispersion should not be applied to s_model 
    75         """  
    76         ##set dispersion from model  
     73        """ 
     74        ##set dispersion from model 
    7775        for name , value in self.model.dispersion.iteritems():       
    7876            nshell = 0 
     
    8280                    if name.split('_')[-1] == 'shell%s' % str(nshell): 
    8381                        self.dispersion[name] = value 
    84                     else:  
     82                    else: 
    8583                        continue 
    8684            else: 
    8785                self.dispersion[name] = value 
    88                  
     86 
    8987    def _set_orientation_params(self): 
    9088        """ 
    9189        model orientation and magnetic parameters, same params for this model 
    92         """  
     90        """ 
    9391        ##set dispersion from model  
    9492        for param in self.model.orientation_params:      
     
    104102                    self.orientation_params.append(param) 
    105103                    self.magnetic_params.append(param) 
    106                     continue                            
     104                    continue 
    107105 
    108106    def _set_params(self): 
    109107        """ 
    110108        Concatenate the parameters of the model to create 
    111         this model parameters  
     109        this model parameters 
    112110        """ 
    113111        # rearrange the parameters for the given # of shells 
     
    128126            else: 
    129127                self.params[name]= value 
    130              
     128 
    131129        # set constrained values for the original model params 
    132         self._set_xtra_model_param()        
    133    
     130        self._set_xtra_model_param() 
     131 
    134132    def _set_details(self): 
    135133        """ 
    136134        Concatenate details of the original model to create 
    137         this model details  
     135        this model details 
    138136        """ 
    139137        for name ,detail in self.model.details.iteritems(): 
    140138            if name in self.params.iterkeys(): 
    141139                self.details[name]= detail 
    142              
    143      
     140 
     141 
    144142    def _set_xtra_model_param(self): 
    145143        """ 
     
    163161                                self.model.setParam(key, 0.0) 
    164162                        except: pass 
    165                       
     163 
    166164 
    167165    def getProfile(self): 
    168166        """ 
    169         Get SLD profile  
    170          
    171         : return: (r, beta) where r is a list of radius of the transition points 
    172                 beta is a list of the corresponding SLD values  
    173         : Note: This works only for func_shell# = 2. 
     167        Get SLD profile 
     168        **Note:** This works only for func_shell num = 2. 
     169 
     170        :return: (r, beta) where r is a list of radius of the transition points\ 
     171         and beta is a list of the corresponding SLD values. 
    174172        """ 
    175173        r = [] 
     
    181179        r.append(self.params['rad_core0']) 
    182180        beta.append(self.params['sld_core0']) 
    183          
     181 
    184182        # for shells 
    185183        for n in range(1, self.n_shells+1): 
    186184            # Left side of each shells 
    187             r0 = r[len(r)-1]             
     185            r0 = r[len(r)-1] 
    188186            r.append(r0) 
    189187            exec "beta.append(self.params['sld_shell%s'% str(n)])" 
     
    193191            r.append(r0) 
    194192            exec "beta.append(self.params['sld_shell%s'% str(n)])" 
    195              
     193 
    196194        # for solvent 
    197195        r0 = r[len(r)-1]             
     
    201199        r.append(r_solv) 
    202200        beta.append(self.params['sld_solv']) 
    203          
     201 
    204202        return r, beta 
    205203 
    206204    def setParam(self, name, value): 
    207         """  
     205        """ 
    208206        Set the value of a model parameter 
    209      
    210         : param name: name of the parameter 
    211         : param value: value of the parameter 
     207 
     208        :param name: name of the parameter 
     209        :param value: value of the parameter 
    212210        """ 
    213211        # set param to new model 
    214212        self._setParamHelper( name, value) 
    215         ## setParam to model  
     213        ## setParam to model 
    216214        if name == 'sld_solv': 
    217215            # the sld_*** model.params not in params must set to value of sld_solv 
     
    243241                self.params[item] = value 
    244242                return 
    245          
    246243        #raise ValueError, "Model does not contain parameter %s" % name 
    247               
    248     
     244 
     245 
    249246    def _set_fixed_params(self): 
    250247        """ 
     
    252249        """ 
    253250        for item in self.model.fixed: 
    254             if item.split('.')[0] in self.params.keys():  
     251            if item.split('.')[0] in self.params.keys(): 
    255252                self.fixed.append(item) 
    256253 
    257254        self.fixed.sort() 
    258                  
     255 
    259256    def run(self, x = 0.0): 
    260         """  
     257        """ 
    261258        Evaluate the model 
    262          
    263         : param x: input q-value (float or [float, float] as [r, theta]) 
    264         : return: (DAB value) 
     259 
     260        :param x: input q-value (float or [float, float] as [r, theta]) 
     261        :return: (DAB value) 
    265262        """ 
    266263        # set effective radius and scaling factor before run 
     
    269266 
    270267    def runXY(self, x = 0.0): 
    271         """  
     268        """ 
    272269        Evaluate the model 
    273          
    274         : param x: input q-value (float or [float, float] as [qx, qy]) 
    275         : return: DAB value 
     270 
     271        :param x: input q-value (float or [float, float] as [qx, qy]) 
     272        :return: DAB value 
    276273        """   
    277274        # set effective radius and scaling factor before run 
    278275 
    279276        return self.model.runXY(x) 
    280      
     277 
    281278    ## Now (May27,10) directly uses the model eval function  
    282279    ## instead of the for-loop in Base Component. 
    283280    def evalDistribution(self, x = []): 
    284         """  
     281        """ 
    285282        Evaluate the model in cartesian coordinates 
    286          
    287         : param x: input q[], or [qx[], qy[]] 
    288         : return: scattering function P(q[]) 
     283 
     284        :param x: input q[], or [qx[], qy[]] 
     285        :return: scattering function P(q[]) 
    289286        """ 
    290287        # set effective radius and scaling factor before run 
    291288        return self.model.evalDistribution(x) 
    292      
     289 
    293290    def calculate_ER(self): 
    294         """  
     291        """ 
    295292        Calculate the effective radius for P(q)*S(q) 
    296          
     293 
    297294        :return: the value of the effective radius 
    298          
    299         """        
     295        """ 
    300296        return self.model.calculate_ER()  
    301      
     297 
    302298    def calculate_VR(self): 
    303         """  
     299        """ 
    304300        Calculate the volf ratio for P(q)*S(q) 
    305          
     301 
    306302        :return: the value of the volf ratio 
    307          
    308         """        
     303        """ 
    309304        return self.model.calculate_VR() 
    310      
     305 
    311306    def set_dispersion(self, parameter, dispersion): 
    312307        """ 
    313308        Set the dispersion object for a model parameter 
    314          
    315         : param parameter: name of the parameter [string] 
    316         :dispersion: dispersion object of type DispersionModel 
     309 
     310        :param parameter: name of the parameter [string] 
     311        :param dispersion: dispersion object of type DispersionModel 
    317312        """ 
    318313        value = None 
     
    323318            return value 
    324319        except: 
    325             raise  
     320            raise 
  • src/sas/models/GuinierPorodModel.py

    r79492222 rac7be54  
    11"""  
    2     I(q) = scale/q^s* exp ( - R_g^2 q^2 / (3-s) ) for q<= ql 
    3         = scale/q^m*exp((-ql^2*Rg^2)/(3-s))*ql^(m-s) for q>=ql 
    4     Guinier function as a BaseComponent model 
     2Guinier function as a BaseComponent model 
    53""" 
    64from sas.models.BaseComponent import BaseComponent 
     
    119    Class that evaluates a GuinierPorod model. 
    1210 
    13     I(q) = scale/q^s* exp ( - R_g^2 q^2 / (3-s) ) for q<= ql 
    14         = scale/q^m*exp((-ql^2*Rg^2)/(3-s))*ql^(m-s) for q>=ql 
     11    Calculate:: 
     12 
     13        I(q) = scale/q^s exp(-q^2 Rg^2 / (3-s) ) for q<= ql 
     14        I(q) = scale/q^m exp(-ql^2 Rg^2 / (3-s)) ql^(m-s) for q>=ql 
    1515    """ 
    1616    def __init__(self): 
  • src/sas/models/MultiplicationModel.py

    r79492222 rfb3f9af  
    55#from sas.models.pluginmodel import Model1DPlugin 
    66class MultiplicationModel(BaseComponent): 
    7     """ 
    8         Use for P(Q)*S(Q); function call must be in the order of P(Q) and then S(Q): 
     7    r""" 
     8        Use for P(Q)\*S(Q); function call must be in the order of P(Q) and then S(Q): 
    99        The model parameters are combined from both models, P(Q) and S(Q), except 1) 'effect_radius' of S(Q) 
    1010        which will be calculated from P(Q) via calculate_ER(),  
    1111        and 2) 'scale' in P model which is synchronized w/ volfraction in S  
    12         then P*S is multiplied by a new param, 'scale_factor'. 
     12        then P*S is multiplied by a new parameter, 'scale_factor'. 
    1313        The polydispersion is applicable only to P(Q), not to S(Q). 
    14         Note: P(Q) refers to 'form factor' model while S(Q) does to 'structure factor'. 
     14 
     15        .. note:: P(Q) refers to 'form factor' model while S(Q) does to 'structure factor'. 
    1516    """ 
    1617    def __init__(self, p_model, s_model ): 
     
    8182    def _clone(self, obj): 
    8283        """ 
    83             Internal utility function to copy the internal 
    84             data members to a fresh copy. 
     84        Internal utility function to copy the internal data members to a 
     85        fresh copy. 
    8586        """ 
    8687        obj.params     = copy.deepcopy(self.params) 
     
    9697    def _set_dispersion(self): 
    9798        """ 
    98            combined the two models dispersions 
    99            Polydispersion should not be applied to s_model 
     99        combine the two models' dispersions. Polydispersity should not be 
     100        applied to s_model 
    100101        """ 
    101102        ##set dispersion only from p_model  
     
    107108        Get SLD profile of p_model if exists 
    108109         
    109         : return: (r, beta) where r is a list of radius of the transition points 
    110                 beta is a list of the corresponding SLD values  
    111         : Note: This works only for func_shell# = 2 (exp function). 
     110        :return: (r, beta) where r is a list of radius of the transition points\ 
     111                beta is a list of the corresponding SLD values 
     112 
     113        .. note:: This works only for func_shell num = 2 (exp function). 
    112114        """ 
    113115        try: 
     
    121123    def _set_params(self): 
    122124        """ 
    123             Concatenate the parameters of the two models to create 
    124             this model parameters  
     125        Concatenate the parameters of the two models to create 
     126        these model parameters  
    125127        """ 
    126128 
     
    141143    def _set_details(self): 
    142144        """ 
    143             Concatenate details of the two models to create 
    144             this model details  
     145        Concatenate details of the two models to create 
     146        this model's details  
    145147        """ 
    146148        for name, detail in self.p_model.details.iteritems(): 
     
    154156    def _set_scale_factor(self): 
    155157        """ 
    156             Set scale=volfraction to P model 
     158        Set scale=volfraction for P model 
    157159        """ 
    158160        value = self.params['volfraction'] 
     
    168170    def _set_effect_radius(self): 
    169171        """ 
    170             Set effective radius to S(Q) model 
     172        Set effective radius to S(Q) model 
    171173        """ 
    172174        if not 'effect_radius' in self.s_model.params.keys(): 
     
    206208    def _setParamHelper(self, name, value): 
    207209        """ 
    208             Helper function to setparam 
     210        Helper function to setparam 
    209211        """ 
    210212        # Look for dispersion parameters 
     
    229231    def _set_fixed_params(self): 
    230232        """ 
    231              fill the self.fixed list with the p_model fixed list 
     233        Fill the self.fixed list with the p_model fixed list 
    232234        """ 
    233235        for item in self.p_model.fixed: 
     
    240242        """  
    241243        Evaluate the model 
     244         
    242245        :param x: input q-value (float or [float, float] as [r, theta]) 
    243246        :return: (scattering function value) 
     
    250253 
    251254    def runXY(self, x = 0.0): 
    252         """ Evaluate the model 
    253             @param x: input q-value (float or [float, float] as [qx, qy]) 
    254             @return: scattering function value 
     255        """  
     256        Evaluate the model 
     257         
     258        :param x: input q-value (float or [float, float] as [qx, qy]) 
     259        :return: scattering function value 
    255260        """   
    256261        # set effective radius and scaling factor before run 
     
    266271        """  
    267272        Evaluate the model in cartesian coordinates 
     273         
    268274        :param x: input q[], or [qx[], qy[]] 
    269275        :return: scattering function P(q[]) 
     
    279285        """ 
    280286        Set the dispersion object for a model parameter 
     287         
    281288        :param parameter: name of the parameter [string] 
    282289        :dispersion: dispersion object of type DispersionModel 
     
    293300    def fill_description(self, p_model, s_model): 
    294301        """ 
    295             Fill the description for P(Q)*S(Q) 
     302        Fill the description for P(Q)*S(Q) 
    296303        """ 
    297304        description = "" 
  • src/sas/models/PeakGaussModel.py

    r79492222 rac7be54  
    11#!/usr/bin/env python 
    22"""  
    3     Model describes a Gaussian shaped peak including a flat background 
    4     Provide F(q) = scale*exp( -1/2 *[(q-q0)/B]^2 )+ background 
    5     PeakGaussModel function as a BaseComponent model 
     3PeakGaussModel function as a BaseComponent model 
    64""" 
    75 
     
    1210    
    1311    """ 
    14         Class that evaluates a gaussian  shaped peak. 
     12        Class that evaluates a gaussian shaped peak with a flat background. 
    1513         
    16         F(q) = scale*exp( -1/2 *[(q-qo)/B]^2 )+ background 
     14        F(q) = scale exp( -1/2 [(q-qo)/B]^2 )+ background 
    1715         
    1816        The model has three parameters:  
     
    5654    def _PeakGauss(self, x): 
    5755        """ 
    58             Evaluate  F(x) = scale*exp( -1/2 *[(x-q0)/B]^2 )+ background 
     56            Evaluate  F(x) = scale exp( -1/2 [(x-q0)/B]^2 )+ background 
    5957            
    6058        """ 
  • src/sas/models/TwoPowerLawModel.py

    r79492222 rac7be54  
    11#!/usr/bin/env python 
    22"""  
    3 Provide I(q) = A*pow(qval,-1.0*m1) for q<=qc 
    4     =scale*pow(qval,-1.0*m2) for q>qc 
    53TwoPowerLaw function as a BaseComponent model 
     4 
     5Calculate:: 
     6 
     7    I(q) = A pow(qval,-m1) for q<=qc 
     8    I(q) = scale pow(qval,-m2) for q>qc 
    69""" 
    710 
     
    1417    Class that evaluates a TwoPowerLawModel. 
    1518 
    16     I(q) = coef_A*pow(qval,-1.0*power1) for q<=qc 
    17         =C*pow(qval,-1.0*power2) for q>qc 
    18     where C=coef_A*pow(qc,-1.0*power1)/pow(qc,-1.0*power2). 
     19    Calculate:: 
     20 
     21       I(q) = coef_A pow(qval,-power1) for q<=qc 
     22       I(q) = C pow(qval,-power2) for q>qc 
     23 
     24    where C=coef_A pow(qc,-power1)/pow(qc,-power2). 
    1925     
    2026    List of default parameters: 
  • src/sas/models/c_extension/c_models/GelFit.cpp

    r79492222 r1d115ef  
    3434    radius = Parameter(104.0,true); 
    3535    radius.set_min(2.0); 
    36     scale = Parameter(2.0,true); 
     36    FractalExp = Parameter(2.0,true); 
    3737    background = Parameter(0.01); 
    3838} 
     
    4343    dp[0] = zeta(); 
    4444    dp[1] = radius(); 
    45     dp[2] = scale(); 
     45    dp[2] = FractalExp(); 
    4646     
    4747    if (dp[2] <= 0) 
  • src/sas/models/c_extension/c_models/lamellarPS.cpp

    r79492222 r37649847  
    6868  ii=0; 
    6969  Sq = 0.0; 
    70   for(ii=1;ii<(NNint-1);ii+=1) { 
     70  for(ii=1;ii<=(NNint-1);ii+=1) { 
    7171 
    7272    fii = (double)ii;   //do I really need to do this? 
     
    144144  for(int i=0; i< (int)weights_spacing.size(); i++) { 
    145145    dp[1] = weights_spacing[i].value; 
    146     for(int j=0; j< (int)weights_spacing.size(); j++) { 
    147       dp[2] = weights_delta[i].value; 
     146    //for(int j=0; j< (int)weights_spacing.size(); j++) {    BUGS fixed March 2015 
     147    for(int j=0; j< (int)weights_delta.size(); j++) { 
     148      //dp[2] = weights_delta[i].value;        BUG 
     149      dp[2] = weights_delta[j].value; 
    148150 
    149151      sum += weights_spacing[i].weight * weights_delta[j].weight * LamellarPS_kernel(dp, q); 
  • src/sas/models/c_extension/c_models/pearlnecklace.cpp

    r79492222 r422e7e8  
    1616  double edge_separation = dp[2]; 
    1717  double thick_string = dp[3]; 
    18   double num_pearls = dp[4]; 
     18  double num_pearls = floor(dp[4]+0.5);  // Force integer number of pearls 
    1919  double sld_pearl = dp[5]; 
    2020  double sld_string = dp[6]; 
  • src/sas/models/c_extension/libigor/libCylinder.c

    r79492222 r8d302cd  
    13791379        ii=0; 
    13801380        Sq = 0.0; 
    1381         for(ii=1;ii<(NNint-1);ii+=1) { 
     1381        for(ii=1;ii<=(NNint-1);ii+=1) { 
    13821382         
    13831383                fii = (double)ii;               //do I really need to do this? 
     
    14511451        ii=0; 
    14521452        Sq = 0.0; 
    1453         for(ii=1;ii<(NNint-1);ii+=1) { 
     1453        for(ii=1;ii<=(NNint-1);ii+=1) { 
    14541454         
    14551455                fii = (double)ii;               //do I really need to do this? 
  • src/sas/models/c_extension/python_wrapper/WrapperGenerator.py

    rfd5ac0d r1f5f206  
    33""" 
    44 
    5 import os, sys,re 
     5import os, sys, re 
    66import lineparser 
    77 
    8 class WrapperGenerator: 
     8class WrapperGenerator(object): 
    99    """ Python wrapper generator for C models 
    10      
    11         The developer must provide a header file describing  
     10 
     11        The developer must provide a header file describing 
    1212        the new model. 
    13          
     13 
    1414        To provide the name of the Python class to be 
    15         generated, the .h file must contain the following  
     15        generated, the .h file must contain the following 
    1616        string in the comments: 
    17          
     17 
    1818        // [PYTHONCLASS] = my_model 
    19          
     19 
    2020        where my_model must be replaced by the name of the 
    2121        class that you want to import from sas.models. 
    2222        (example: [PYTHONCLASS] = MyModel 
    2323          will create a class MyModel in sas.models.MyModel. 
    24           It will also create a class CMyModel in  
     24          It will also create a class CMyModel in 
    2525          sas_extension.c_models.) 
    26            
    27         Also in comments, each parameter of the params  
     26 
     27        Also in comments, each parameter of the params 
    2828        dictionary must be declared with a default value 
    2929        in the following way: 
    30          
     30 
    3131        // [DEFAULT]=param_name=default_value 
    32          
     32 
    3333        (example: 
    3434            //  [DEFAULT]=radius=20.0 
    3535        ) 
    36            
     36 
    3737        See cylinder.h for an example. 
    38          
    39          
     38 
    4039        A .c file corresponding to the .h file should also 
    4140        be provided (example: my_model.h, my_model.c). 
    42      
     41 
    4342        The .h file should define two function definitions. For example, 
    4443        cylinder.h defines the following: 
    45          
     44 
    4645        /// 1D scattering function 
    4746        double cylinder_analytical_1D(CylinderParameters *pars, double q); 
    48              
     47 
    4948        /// 2D scattering function 
    5049        double cylinder_analytical_2D(CylinderParameters *pars, double q, double phi); 
    51              
     50 
    5251        The .c file implements those functions. 
    53          
     52 
    5453        @author: Mathieu Doucet / UTK 
    5554        @contact: mathieu.doucet@nist.gov 
    5655    """ 
    57      
     56 
    5857    def __init__(self, filename, output_dir='.', c_wrapper_dir='.'): 
    5958        """ Initialization """ 
    60          
     59 
    6160        ## Name of .h file to generate wrapper from 
    6261        self.file = filename 
    63          
     62 
    6463        # Info read from file 
    65          
     64 
    6665        ## Name of python class to write 
    6766        self.pythonClass = None 
     
    8382        self.disp_params = [] 
    8483        #model description 
    85         self.description='' 
     84        self.description = '' 
    8685        # paramaters for fittable 
    87         self.fixed= [] 
     86        self.fixed = [] 
    8887        # paramaters for non-fittable 
    89         self.non_fittable= [] 
     88        self.non_fittable = [] 
    9089        ## parameters with orientation 
    91         self.orientation_params =[] 
     90        self.orientation_params = [] 
    9291        ## parameter with magnetism 
    9392        self.magentic_params = [] 
     
    10099        self.c_wrapper_dir = c_wrapper_dir 
    101100 
    102          
    103          
    104101    def __repr__(self): 
    105102        """ Simple output for printing """ 
    106          
    107         rep  = "\n Python class: %s\n\n" % self.pythonClass 
     103 
     104        rep = "\n Python class: %s\n\n" % self.pythonClass 
    108105        rep += "  struc name: %s\n\n" % self.structName 
    109106        rep += "  params:     %s\n\n" % self.params 
    110107        rep += "  description:    %s\n\n" % self.description 
    111         rep += "  Fittable parameters:     %s\n\n"% self.fixed 
    112         rep += "  Non-Fittable parameters:     %s\n\n"% self.non_fittable 
    113         rep += "  Orientation parameters:  %s\n\n"% self.orientation_params 
    114         rep += "  Magnetic parameters:  %s\n\n"% self.magnetic_params 
     108        rep += "  Fittable parameters:     %s\n\n" % self.fixed 
     109        rep += "  Non-Fittable parameters:     %s\n\n" % self.non_fittable 
     110        rep += "  Orientation parameters:  %s\n\n" % self.orientation_params 
     111        rep += "  Magnetic parameters:  %s\n\n" % self.magnetic_params 
    115112        return rep 
    116          
     113 
    117114    def read(self): 
    118115        """ Reads in the .h file to catch parameters of the wrapper """ 
    119          
     116 
    120117        # Check if the file is there 
    121118        if not os.path.isfile(self.file): 
    122119            raise ValueError, "File %s is not a regular file" % self.file 
    123          
     120 
    124121        # Read file 
    125         f = open(self.file,'r') 
     122        f = open(self.file, 'r') 
    126123        buf = f.read() 
    127          
     124 
    128125        self.default_list = "\n    List of default parameters:\n\n" 
    129126        #lines = string.split(buf,'\n') 
    130127        lines = buf.split('\n') 
    131         self.details  = "## Parameter details [units, min, max]\n" 
     128        self.details = "## Parameter details [units, min, max]\n" 
    132129        self.details += "        self.details = {}\n" 
    133          
     130 
    134131        #open item in this case Fixed 
    135         text='text' 
    136         key2="<%s>"%text.lower() 
     132        text = 'text' 
     133        key2 = "<%s>" % text.lower() 
    137134        # close an item in this case fixed 
    138         text='TexT' 
    139         key3="</%s>"%text.lower() 
    140          
     135        text = 'TexT' 
     136        key3 = "</%s>" % text.lower() 
     137 
    141138        ## Catch fixed parameters 
    142139        key = "[FIXED]" 
    143140        try: 
    144             self.fixed= lineparser.readhelper(lines, key,  
    145                                               key2, key3, file=self.file) 
     141            self.fixed = lineparser.readhelper(lines, key, 
     142                                               key2, key3, file=self.file) 
    146143        except: 
    147            raise    
     144            raise 
    148145        ## Catch non-fittable parameters parameters 
    149146        key = "[NON_FITTABLE_PARAMS]" 
    150147        try: 
    151             self.non_fittable= lineparser.readhelper(lines, key, key2, 
    152                                                      key3, file=self.file) 
     148            self.non_fittable = lineparser.readhelper(lines, key, key2, 
     149                                                      key3, file=self.file) 
    153150        except: 
    154            raise    
     151            raise 
    155152 
    156153        ## Catch parameters with orientation 
    157         key = "[ORIENTATION_PARAMS]"     
     154        key = "[ORIENTATION_PARAMS]" 
    158155        try: 
    159             self.orientation_params = lineparser.readhelper(lines, key,  
    160                                                     key2, key3, file=self.file) 
     156            self.orientation_params = lineparser.readhelper(lines, key, 
     157                                                            key2, key3, file=self.file) 
    161158        except: 
    162            raise  
    163         
     159            raise 
     160 
    164161        ## Catch parameters with orientation 
    165         key = "[MAGNETIC_PARAMS]"     
     162        key = "[MAGNETIC_PARAMS]" 
    166163        try: 
    167             self.magnetic_params = lineparser.readhelper( lines,key,  
    168                                                     key2,key3, file= self.file) 
     164            self.magnetic_params = lineparser.readhelper(lines, key, 
     165                                                         key2, key3, file=self.file) 
    169166        except: 
    170            raise  
    171         
     167            raise 
     168 
    172169        ## Catch Description 
    173170        key = "[DESCRIPTION]" 
    174          
     171 
    175172        find_description = False 
    176         temp="" 
     173        temp = "" 
    177174        for line in lines: 
    178             if line.count(key)>0 : 
    179                  
     175            if line.count(key) > 0: 
    180176                try: 
    181                     find_description= True 
     177                    find_description = True 
    182178                    index = line.index(key) 
    183                     toks = line[index:].split("=",1 ) 
    184                     temp=toks[1].lstrip().rstrip() 
    185                     text='text' 
    186                     key2="<%s>"%text.lower() 
    187                     if re.match(key2,temp)!=None: 
    188      
    189                         toks2=temp.split(key2,1) 
    190                         self.description=toks2[1] 
    191                         text='text' 
    192                         key2="</%s>"%text.lower() 
    193                         if re.search(key2,toks2[1])!=None: 
    194                             temp=toks2[1].split(key2,1) 
    195                             self.description=temp[0] 
     179                    toks = line[index:].split("=", 1) 
     180                    temp = toks[1].lstrip().rstrip() 
     181                    text = 'text' 
     182                    key2 = "<%s>" % text.lower() 
     183                    if re.match(key2, temp) != None: 
     184 
     185                        toks2 = temp.split(key2, 1) 
     186                        self.description = toks2[1] 
     187                        text = 'text' 
     188                        key2 = "</%s>" % text.lower() 
     189                        if re.search(key2, toks2[1]) != None: 
     190                            temp = toks2[1].split(key2, 1) 
     191                            self.description = temp[0] 
    196192                            break 
    197                        
     193 
    198194                    else: 
    199                         self.description=temp 
     195                        self.description = temp 
    200196                        break 
    201197                except: 
    202                      raise ValueError, "Could not parse file %s" % self.file 
     198                    raise ValueError, "Could not parse file %s" % self.file 
    203199            elif find_description: 
    204                 text='text' 
    205                 key2="</%s>"%text.lower() 
    206                 if re.search(key2,line)!=None: 
    207                     tok=line.split(key2,1) 
    208                     temp=tok[0].split("//",1) 
    209                     self.description+=tok[1].lstrip().rstrip() 
     200                text = 'text' 
     201                key2 = "</%s>" % text.lower() 
     202                if re.search(key2, line) != None: 
     203                    tok = line.split(key2, 1) 
     204                    temp = tok[0].split("//", 1) 
     205                    self.description += tok[1].lstrip().rstrip() 
    210206                    break 
    211207                else: 
    212                     if re.search("//",line)!=None: 
    213                         temp=line.split("//",1) 
    214                         self.description+='\n\t\t'+temp[1].lstrip().rstrip() 
    215                          
     208                    if re.search("//", line) != None: 
     209                        temp = line.split("//", 1) 
     210                        self.description += '\n\t\t' + temp[1].lstrip().rstrip() 
     211 
    216212                    else: 
    217                         self.description+='\n\t\t'+line.lstrip().rstrip() 
    218                      
    219                  
    220       
     213                        self.description += '\n\t\t' + line.lstrip().rstrip() 
     214 
     215 
     216 
    221217        for line in lines: 
    222              
     218 
    223219            # Catch class name 
    224220            key = "[PYTHONCLASS]" 
    225             if line.count(key)>0: 
     221            if line.count(key) > 0: 
    226222                try: 
    227223                    index = line.index(key) 
    228                     toks = line[index:].split("=" ) 
     224                    toks = line[index:].split("=") 
    229225                    self.pythonClass = toks[1].lstrip().rstrip() 
    230226 
    231227                except: 
    232228                    raise ValueError, "Could not parse file %s" % self.file 
    233                  
     229 
    234230            key = "[CATEGORY]" 
    235             if line.count(key)>0: 
     231            if line.count(key) > 0: 
    236232                try: 
    237233                    index = line.index(key) 
     
    255251            # Catch struct name 
    256252            # C++ class definition 
    257             if line.count("class")>0: 
     253            if line.count("class") > 0: 
    258254                # We are entering a class definition 
    259255                self.inParDefs = True 
    260256                self.foundCPP = True 
    261                  
     257 
    262258            # Old-Style C struct definition 
    263             if line.count("typedef struct")>0: 
     259            if line.count("typedef struct") > 0: 
    264260                # We are entering a struct block 
    265261                self.inParDefs = True 
    266262                self.inStruct = True 
    267              
    268             if self.inParDefs and line.count("}")>0: 
     263 
     264            if self.inParDefs and line.count("}") > 0: 
    269265                # We are exiting a struct block 
    270266                self.inParDefs = False 
    271                  
     267 
    272268                if self.inStruct: 
    273269                    self.inStruct = False 
    274270                    # Catch the name of the struct 
    275271                    index = line.index("}") 
    276                     toks = line[index+1:].split(";") 
     272                    toks = line[index + 1:].split(";") 
    277273                    # Catch pointer definition 
    278274                    toks2 = toks[0].split(',') 
    279275                    self.structName = toks2[0].lstrip().rstrip() 
    280             
     276 
    281277            # Catch struct content 
    282278            key = "[DEFAULT]" 
    283             if self.inParDefs and line.count(key)>0: 
     279            if self.inParDefs and line.count(key) > 0: 
    284280                # Found a new parameter 
    285281                try: 
     
    295291                    self.default_list += "    * %-15s = %s %s\n" % \ 
    296292                        (toks[1], val, units) 
    297                      
     293 
    298294                    # Check for min and max 
    299                     min = "None" 
    300                     max = "None" 
     295                    value_min = "None" 
     296                    value_max = "None" 
    301297                    if len(toks2) == 4: 
    302                         min = toks2[2] 
    303                         max = toks2[3] 
    304                      
     298                        value_min = toks2[2] 
     299                        value_max = toks2[3] 
     300 
    305301                    self.details += "        self.details['%s'] = ['%s', %s, %s]\n" % \ 
    306                         (toks[1].lstrip().rstrip(), units.lstrip().rstrip(), min, max) 
     302                        (toks[1].lstrip().rstrip(), units.lstrip().rstrip(), value_min, value_max) 
    307303                except: 
    308304                    raise ValueError, "Could not parse input file %s \n  %s" % \ 
    309305                        (self.file, sys.exc_value) 
    310                  
    311                  
     306 
     307 
    312308            # Catch need for numerical calculations 
    313309            key = "CalcParameters calcPars" 
    314             if line.count(key)>0: 
     310            if line.count(key) > 0: 
    315311                self.modelCalcFlag = True 
    316                  
     312 
    317313            # Catch list of dispersed parameters  
    318314            key = "[DISP_PARAMS]" 
    319             if line.count(key)>0: 
     315            if line.count(key) > 0: 
    320316                try: 
    321317                    index = line.index(key) 
     
    330326            The file is written in C[PYTHONCLASS].c 
    331327        """ 
    332         file_path = os.path.join(self.c_wrapper_dir,  
    333                                  "C"+self.pythonClass+'.cpp') 
     328        file_path = os.path.join(self.c_wrapper_dir, 
     329                                 "C" + self.pythonClass + '.cpp') 
    334330        file = open(file_path, 'w') 
    335          
    336         template = open(os.path.join(os.path.dirname(__file__),  
     331 
     332        template = open(os.path.join(os.path.dirname(__file__), 
    337333                                     "classTemplate.txt"), 'r') 
    338          
     334 
    339335        tmp_buf = template.read() 
    340336        #tmp_lines = string.split(tmp_buf,'\n') 
    341337        tmp_lines = tmp_buf.split('\n') 
    342          
     338 
    343339        for tmp_line in tmp_lines: 
    344              
     340 
    345341            # Catch class name 
    346             newline = self.replaceToken(tmp_line,  
    347                                         "[PYTHONCLASS]", 'C'+self.pythonClass) 
     342            newline = self.replaceToken(tmp_line, 
     343                                        "[PYTHONCLASS]", 'C' + self.pythonClass) 
    348344            #Catch model description 
    349345            #newline = self.replaceToken(tmp_line,  
    350346            #                            "[DESCRIPTION]", self.description) 
    351347            # Catch C model name 
    352             newline = self.replaceToken(newline,  
     348            newline = self.replaceToken(newline, 
    353349                                        "[CMODEL]", self.pythonClass) 
    354              
     350 
    355351            # Catch class name 
    356             newline = self.replaceToken(newline,  
     352            newline = self.replaceToken(newline, 
    357353                                        "[MODELSTRUCT]", self.structName) 
    358354 
    359355            # Sort model initialization based on multifunc 
    360             if(self.is_multifunc): 
     356            if self.is_multifunc: 
    361357                line = "int level = 1;\nPyArg_ParseTuple(args,\"i\",&level);\n" 
    362358                line += "self->model = new " + self.pythonClass + "(level);" 
    363359            else: 
    364360                line = "self->model = new " + self.pythonClass + "();" 
    365      
    366             newline = self.replaceToken(newline,"[INITIALIZE_MODEL]", 
    367                                             line) 
    368              
     361 
     362            newline = self.replaceToken(newline, "[INITIALIZE_MODEL]", line) 
     363 
    369364            # Dictionary initialization 
    370             param_str = "// Initialize parameter dictionary\n"             
     365            param_str = "// Initialize parameter dictionary\n" 
    371366            for par in self.params: 
    372367                param_str += "        PyDict_SetItemString(self->params,\"%s\",Py_BuildValue(\"d\",%10.12f));\n" % \ 
    373368                    (par, self.params[par]) 
    374369 
    375             if len(self.disp_params)>0: 
     370            if len(self.disp_params) > 0: 
    376371                param_str += "        // Initialize dispersion / averaging parameter dict\n" 
    377372                param_str += "        DispersionVisitor* visitor = new DispersionVisitor();\n" 
     
    384379                    param_str += "        self->model->%s.dispersion->accept_as_source(visitor, self->model->%s.dispersion, disp_dict);\n" % (par, par) 
    385380                    param_str += "        PyDict_SetItemString(self->dispersion, \"%s\", disp_dict);\n" % par 
    386                  
     381 
    387382            # Initialize dispersion object dictionnary 
    388383            param_str += "\n" 
    389              
    390                  
     384 
     385 
    391386            newline = self.replaceToken(newline, 
    392387                                        "[INITDICTIONARY]", param_str) 
    393              
     388 
    394389            # Read dictionary 
    395390            param_str = "    // Reader parameter dictionary\n" 
     
    397392                param_str += "    self->model->%s = PyFloat_AsDouble( PyDict_GetItemString(self->params, \"%s\") );\n" % \ 
    398393                    (par, par) 
    399                      
    400             if len(self.disp_params)>0: 
     394 
     395            if len(self.disp_params) > 0: 
    401396                param_str += "    // Read in dispersion parameters\n" 
    402397                param_str += "    PyObject* disp_dict;\n" 
     
    408403                    param_str += "    disp_dict = PyDict_GetItemString(self->dispersion, \"%s\");\n" % par 
    409404                    param_str += "    self->model->%s.dispersion->accept_as_destination(visitor, self->model->%s.dispersion, disp_dict);\n" % (par, par) 
    410                  
     405 
    411406            newline = self.replaceToken(newline, "[READDICTIONARY]", param_str) 
    412                  
     407 
    413408            # Name of .c file 
    414409            #toks = string.split(self.file,'.') 
     
    416411            toks = basename.split('.') 
    417412            newline = self.replaceToken(newline, "[C_FILENAME]", toks[0]) 
    418              
     413 
    419414            # Include file 
    420415            basename = os.path.basename(self.file) 
    421             newline = self.replaceToken(newline,  
    422                                         "[INCLUDE_FILE]", self.file)   
     416            newline = self.replaceToken(newline, 
     417                                        "[INCLUDE_FILE]", self.file) 
    423418            if self.foundCPP: 
    424                 newline = self.replaceToken(newline,  
    425                             "[C_INCLUDE_FILE]", "")   
    426                 newline = self.replaceToken(newline,  
    427                             "[CPP_INCLUDE_FILE]", "#include \"%s\"" % basename)   
    428             else:   
    429                 newline = self.replaceToken(newline,  
    430                             "[C_INCLUDE_FILE]", "#include \"%s\"" % basename)    
    431                 newline = self.replaceToken(newline,  
    432                             "[CPP_INCLUDE_FILE]", "#include \"models.hh\"")   
    433                  
     419                newline = self.replaceToken(newline, "[C_INCLUDE_FILE]", "") 
     420                newline = self.replaceToken(newline, 
     421                                            "[CPP_INCLUDE_FILE]", 
     422                                            "#include \"%s\"" % basename) 
     423            else: 
     424                newline = self.replaceToken(newline, 
     425                                            "[C_INCLUDE_FILE]", 
     426                                            "#include \"%s\"" % basename) 
     427                newline = self.replaceToken(newline, 
     428                                            "[CPP_INCLUDE_FILE]", 
     429                                            "#include \"models.hh\"") 
     430 
    434431            # Numerical calcs dealloc 
    435432            dealloc_str = "\n" 
    436433            if self.modelCalcFlag: 
    437434                dealloc_str = "    modelcalculations_dealloc(&(self->model_pars.calcPars));\n" 
    438             newline = self.replaceToken(newline,  
    439                                         "[NUMERICAL_DEALLOC]", dealloc_str)      
    440                  
     435            newline = self.replaceToken(newline, 
     436                                        "[NUMERICAL_DEALLOC]", dealloc_str) 
     437 
    441438            # Numerical calcs init 
    442439            init_str = "\n" 
    443440            if self.modelCalcFlag: 
    444441                init_str = "        modelcalculations_init(&(self->model_pars.calcPars));\n" 
    445             newline = self.replaceToken(newline,  
    446                                         "[NUMERICAL_INIT]", init_str)      
    447                  
     442            newline = self.replaceToken(newline, 
     443                                        "[NUMERICAL_INIT]", init_str) 
     444 
    448445            # Numerical calcs reset 
    449446            reset_str = "\n" 
    450447            if self.modelCalcFlag: 
    451448                reset_str = "modelcalculations_reset(&(self->model_pars.calcPars));\n" 
    452             newline = self.replaceToken(newline,  
    453                                         "[NUMERICAL_RESET]", reset_str)      
    454                  
     449            newline = self.replaceToken(newline, 
     450                                        "[NUMERICAL_RESET]", reset_str) 
     451 
    455452            # Setting dispsertion weights 
    456453            set_weights = "    // Ugliness necessary to go from python to C\n" 
     
    463460                set_weights += "        self->model->%s.dispersion = dispersion;\n" % par 
    464461                set_weights += "    } else" 
    465             newline = self.replaceToken(newline,  
    466                                         "[SET_DISPERSION]", set_weights)      
    467              
     462            newline = self.replaceToken(newline, 
     463                                        "[SET_DISPERSION]", set_weights) 
     464 
    468465            # Write new line to the wrapper .c file 
    469             file.write(newline+'\n') 
    470              
    471              
     466            file.write(newline + '\n') 
     467 
     468 
    472469        file.close() 
    473          
     470 
    474471    def write_python_wrapper(self): 
    475472        """ Writes the python file to create the python extension class  
    476473            The file is written in ../[PYTHONCLASS].py 
    477474        """ 
    478         file_path = os.path.join(self.output_dir, self.pythonClass+'.py') 
     475        file_path = os.path.join(self.output_dir, self.pythonClass + '.py') 
    479476        file = open(file_path, 'w') 
    480         template = open(os.path.join(os.path.dirname(__file__),  
     477        template = open(os.path.join(os.path.dirname(__file__), 
    481478                                     "modelTemplate.txt"), 'r') 
    482          
     479 
    483480        tmp_buf = template.read() 
    484481        tmp_lines = tmp_buf.split('\n') 
    485          
     482 
    486483        for tmp_line in tmp_lines: 
    487              
     484 
    488485            # Catch class name 
    489             newline = self.replaceToken(tmp_line,  
    490                                         "[CPYTHONCLASS]",  
     486            newline = self.replaceToken(tmp_line, 
     487                                        "[CPYTHONCLASS]", 
    491488                                        'C' + self.pythonClass) 
    492              
     489 
    493490            # Catch class name 
    494             newline = self.replaceToken(newline,  
     491            newline = self.replaceToken(newline, 
    495492                                        "[PYTHONCLASS]", self.pythonClass) 
    496              
     493 
    497494            # Include file 
    498             newline = self.replaceToken(newline,  
    499                                         "[INCLUDE_FILE]", self.file)     
    500                     
     495            newline = self.replaceToken(newline, 
     496                                        "[INCLUDE_FILE]", self.file) 
     497 
    501498            # Include file 
    502             newline = self.replaceToken(newline,  
     499            newline = self.replaceToken(newline, 
    503500                                        "[DEFAULT_LIST]", self.default_list) 
    504501            # model description 
    505             newline = self.replaceToken(newline,  
     502            newline = self.replaceToken(newline, 
    506503                                        "[DESCRIPTION]", self.description) 
    507504            # Parameter details 
    508             newline = self.replaceToken(newline,  
     505            newline = self.replaceToken(newline, 
    509506                                        "[PAR_DETAILS]", self.details) 
    510              
     507 
    511508            # Call base constructor 
    512509            if self.is_multifunc: 
    513                 newline = self.replaceToken(newline,"[CALL_CPYTHON_INIT]", 
    514                     'C' + self.pythonClass + \ 
     510                newline = self.replaceToken(newline, "[CALL_CPYTHON_INIT]", 
     511                                            'C' + self.pythonClass + \ 
    515512                    ".__init__(self,multfactor)\n\tself.is_multifunc = True") 
    516                 newline = self.replaceToken(newline,"[MULTIPLICITY_INFO]",  
     513                newline = self.replaceToken(newline, "[MULTIPLICITY_INFO]", 
    517514                                            self.multiplicity_info) 
    518515            else: 
    519                 newline = self.replaceToken(newline,"[CALL_CPYTHON_INIT]", 
    520                     'C' + self.pythonClass + \ 
     516                newline = self.replaceToken(newline, "[CALL_CPYTHON_INIT]", 
     517                                            'C' + self.pythonClass + \ 
    521518                    ".__init__(self)\n        self.is_multifunc = False") 
    522                 newline = self.replaceToken(newline,  
     519                newline = self.replaceToken(newline, 
    523520                                            "[MULTIPLICITY_INFO]", "None") 
    524521 
    525             
    526522            # fixed list  details 
    527523            fixed_str = str(self.fixed) 
    528524            fixed_str = fixed_str.replace(', ', ',\n                      ') 
    529525            newline = self.replaceToken(newline, "[FIXED]", fixed_str) 
    530              
     526 
    531527            # non-fittable list details 
    532528            pars_str = str(self.non_fittable) 
    533             pars_str = pars_str.replace(', ',  
     529            pars_str = pars_str.replace(', ', 
    534530                                        ',\n                             ') 
    535             newline = self.replaceToken(newline,  
     531            newline = self.replaceToken(newline, 
    536532                                        "[NON_FITTABLE_PARAMS]", pars_str) 
    537              
     533 
    538534            ## parameters with orientation 
    539535            oriented_str = str(self.orientation_params) 
    540536            formatted_endl = ',\n                                   ' 
    541537            oriented_str = oriented_str.replace(', ', formatted_endl) 
    542             newline = self.replaceToken(newline,  
    543                                "[ORIENTATION_PARAMS]", oriented_str) 
    544            ## parameters with magnetism 
    545             newline = self.replaceToken(newline,  
    546                                "[MAGNETIC_PARAMS]", str(self.magnetic_params)) 
     538            newline = self.replaceToken(newline, 
     539                                        "[ORIENTATION_PARAMS]", oriented_str) 
     540            ## parameters with magnetism 
     541            newline = self.replaceToken(newline, 
     542                                        "[MAGNETIC_PARAMS]", 
     543                                        str(self.magnetic_params)) 
    547544 
    548545            if self.category: 
    549                 newline = self.replaceToken(newline, "[CATEGORY]",  
     546                newline = self.replaceToken(newline, "[CATEGORY]", 
    550547                                            '"' + self.category + '"') 
    551548            else: 
    552549                newline = self.replaceToken(newline, "[CATEGORY]", 
    553550                                            "None") 
    554              
     551 
    555552 
    556553 
    557554            # Write new line to the wrapper .c file 
    558             file.write(newline+'\n') 
    559                 
     555            file.write(newline + '\n') 
     556 
    560557        file.close() 
    561          
    562          
     558 
     559 
    563560    def replaceToken(self, line, key, value): #pylint: disable-msg=R0201 
    564561        """ Replace a token in the template file  
    565             @param line: line of text to inspect 
    566             @param key: token to look for 
    567             @param value: string value to replace the token with 
    568             @return: new string value 
     562            :param line: line of text to inspect 
     563            :param key: token to look for 
     564            :param value: string value to replace the token with 
     565            :return: new string value 
    569566        """ 
     567        _str_value = str(value) 
     568        _new_value = _str_value.replace('\\','/') 
    570569        lenkey = len(key) 
    571570        newline = line 
    572         
    573         while newline.count(key)>0: 
     571 
     572        while newline.count(key) > 0: 
    574573            index = newline.index(key) 
    575             newline = newline[:index]+value+newline[index+lenkey:] 
    576          
     574            newline = newline[:index] + _new_value + newline[index + lenkey:] 
     575 
    577576        return newline 
    578          
     577 
    579578    def getModelName(self): 
    580579        return self.pythonClass 
    581          
     580 
    582581 
    583582 
    584583# main 
    585584if __name__ == '__main__': 
    586     if len(sys.argv)>1: 
     585    if len(sys.argv) > 1: 
    587586        print "Will look for file %s" % sys.argv[1] 
    588587        app = WrapperGenerator(sys.argv[1]) 
     
    593592    app.write_python_wrapper() 
    594593    print app 
    595     
     594 
    596595# End of file         
  • src/sas/models/c_extension/python_wrapper/modelTemplate.txt

    r8836849 r1f5f206  
    1313############################################################################## 
    1414 
    15 """  
     15""" 
    1616Provide functionality for a C extension model 
    1717 
    1818.. WARNING:: 
    19  
    2019   THIS FILE WAS GENERATED BY WRAPPERGENERATOR.PY 
    2120   DO NOT MODIFY THIS FILE, MODIFY 
     
    3029def create_[PYTHONCLASS](): 
    3130    """ 
    32        Create a model instance 
     31    Create a model instance 
    3332    """ 
    3433    obj = [PYTHONCLASS]() 
     
    3837 
    3938class [PYTHONCLASS]([CPYTHONCLASS], BaseComponent): 
    40     """  
    41     Class that evaluates a [PYTHONCLASS] model.  
     39    """ 
     40    Class that evaluates a [PYTHONCLASS] model. 
    4241    This file was auto-generated from [INCLUDE_FILE]. 
    4342    Refer to that file and the structure it contains 
     
    4544    [DEFAULT_LIST] 
    4645    """ 
    47          
     46 
    4847    def __init__(self, multfactor=1): 
    4948        """ Initialization """ 
    5049        self.__dict__ = {} 
    51          
     50 
    5251        # Initialize BaseComponent first, then sphere 
    5352        BaseComponent.__init__(self) 
     
    5554 
    5655        [CALL_CPYTHON_INIT] 
    57                          
     56 
    5857        ## Name of the model 
    5958        self.name = "[PYTHONCLASS]" 
     
    6261        [DESCRIPTION] 
    6362        """ 
    64         
     63 
    6564        [PAR_DETAILS] 
    6665        ## fittable parameters 
    6766        self.fixed = [FIXED] 
    68          
     67 
    6968        ## non-fittable parameters 
    7069        self.non_fittable = [NON_FITTABLE_PARAMS] 
    71          
     70 
    7271        ## parameters with orientation 
    7372        self.orientation_params = [ORIENTATION_PARAMS] 
     
    7877        self.category = [CATEGORY] 
    7978        self.multiplicity_info = [MULTIPLICITY_INFO] 
    80          
     79 
    8180    def __setstate__(self, state): 
    8281        """ 
     
    8483        """ 
    8584        self.__dict__, self.params, self.dispersion = state 
    86          
     85 
    8786    def __reduce_ex__(self, proto): 
    8887        """ 
    89         Overwrite the __reduce_ex__ of PyTypeObject *type call in the init of  
     88        Overwrite the __reduce_ex__ of PyTypeObject *type call in the init of 
    9089        c model. 
    9190        """ 
    9291        state = (self.__dict__, self.params, self.dispersion) 
    9392        return (create_[PYTHONCLASS], tuple(), state, None, None) 
    94          
     93 
    9594    def clone(self): 
    9695        """ Return a identical copy of self """ 
    97         return self._clone([PYTHONCLASS]())    
    98          
     96        return self._clone([PYTHONCLASS]()) 
     97 
    9998    def run(self, x=0.0): 
    100         """  
     99        """ 
    101100        Evaluate the model 
    102          
     101 
    103102        :param x: input q, or [q,phi] 
    104          
    105103        :return: scattering function P(q) 
    106          
    107104        """ 
    108105        return [CPYTHONCLASS].run(self, x) 
    109     
     106 
    110107    def runXY(self, x=0.0): 
    111         """  
     108        """ 
    112109        Evaluate the model in cartesian coordinates 
    113          
     110 
    114111        :param x: input q, or [qx, qy] 
    115          
    116112        :return: scattering function P(q) 
    117          
    118113        """ 
    119114        return [CPYTHONCLASS].runXY(self, x) 
    120          
     115 
    121116    def evalDistribution(self, x): 
    122         """  
     117        """ 
    123118        Evaluate the model in cartesian coordinates 
    124          
     119 
    125120        :param x: input q[], or [qx[], qy[]] 
    126          
    127121        :return: scattering function P(q[]) 
    128          
    129122        """ 
    130123        return [CPYTHONCLASS].evalDistribution(self, x) 
    131          
     124 
    132125    def calculate_ER(self): 
    133         """  
     126        """ 
    134127        Calculate the effective radius for P(q)*S(q) 
    135          
     128 
    136129        :return: the value of the effective radius 
    137          
    138         """        
     130        """ 
    139131        return [CPYTHONCLASS].calculate_ER(self) 
    140          
     132 
    141133    def calculate_VR(self): 
    142         """  
     134        """ 
    143135        Calculate the volf ratio for P(q)*S(q) 
    144          
     136 
    145137        :return: the value of the volf ratio 
    146          
    147         """        
     138        """ 
    148139        return [CPYTHONCLASS].calculate_VR(self) 
    149                
     140 
    150141    def set_dispersion(self, parameter, dispersion): 
    151142        """ 
    152143        Set the dispersion object for a model parameter 
    153          
     144 
    154145        :param parameter: name of the parameter [string] 
    155146        :param dispersion: dispersion object of type DispersionModel 
    156          
    157147        """ 
    158148        return [CPYTHONCLASS].set_dispersion(self, 
    159149               parameter, dispersion.cdisp) 
    160          
    161     
     150 
    162151# End of file 
  • src/sas/models/include/GelFit.h

    r79492222 r1d115ef  
    3333  Parameter radius; 
    3434 
    35   //  [DEFAULT]=scale= 2 
    36   Parameter scale; 
     35  //  [DEFAULT]=FractalExp= 2 
     36  Parameter FractalExp; 
    3737 
    3838  //  [DEFAULT]=background= 0.01 
  • src/sas/models/include/dabmodel.h

    r79492222 rf008ee2  
    1717// [PYTHONCLASS] = DABModel 
    1818// [DISP_PARAMS] = length, scale, background 
    19 // [DESCRIPTION] = <text>Provide F(x) = scale/( 1 + (x*L)^2 )^(2) + background 
    20 //    DAB (Debye Anderson Brumberger) function as a BaseComponent model 
     19// [DESCRIPTION] = <text>DAB (Debye Anderson Brumberger) Model 
     20//    F(x) = scale * L^3/( 1 + (q*L)^2 )^2 + background 
     21//    L: the correlation length 
    2122//     </text> 
    2223// [FIXED] =  
  • src/sas/models/media/model_functions.rst

    rcd06a5f ra342928  
    1010 
    1111.. To do: 
    12 .. Remove the 'This is xi' & 'This is zeta' lines before release! 
    1312.. Add example parameters/plots for the CoreShellEllipsoidXTModel 
    1413.. Add example parameters/plots for the RectangularPrism models 
     
    2019.. ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ 
    2120 
     21 
     22.. note::  The contents of this document are presented in good faith and are  
     23           believed to be mostly correct and accurate, however they have not  
     24           yet been rigorously checked for errors. June2015 
    2225 
    2326 
     
    7780.. Actual document starts here... 
    7881 
     82.. _SasView_model_functions: 
     83 
    7984SasView Model Functions 
    8085======================= 
    81  
    82 Contents 
    83 -------- 
    84 1. Background_ 
    85  
    86 2. Model_ Functions 
    87  
    88  2.1 Shape-based_ Functions 
    89   
    90  2.2 Shape-independent_ Functions 
    91   
    92  2.3 Structure-factor_ Functions 
    93   
    94  2.4 Customised_ Functions 
    95  
    96 3. References_ 
    97  
    98  
    99  
    100 .. ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ 
    101  
    102  
    10386 
    10487.. _Background: 
     
    169152- RaspBerryModel_ 
    170153- CoreShellModel_ (including magnetic 2D version) 
     154- MicelleSphCoreModel_ 
    171155- CoreMultiShellModel_ (including magnetic 2D version) 
    172156- Core2ndMomentModel_ 
     
    286270- sph_bessel_jn_ 
    287271 
     272Also see the documentation on :ref:`Adding_your_own_models` under Fitting Data.  
     273 
    288274 
    289275 
     
    22532239 
    22542240  *equat_core* = equatorial core radius = *Rminor_core* 
     2241   
    22552242  *X_core* = *polar_core* / *equat_core* = *Rmajor_core* / *Rminor_core* 
     2243   
    22562244  *T_shell* = *equat_outer* - *equat_core* = *Rminor_outer* - *Rminor_core* 
     2245   
    22572246  *XpolarShell* = *Tpolar_shell* / *T_shell* = (*Rmajor_outer* - *Rmajor_core*)/(*Rminor_outer* - *Rminor_core*) 
    22582247 
     
    22602249 
    22612250  *polar_core* = *equat_core* \* *X_core* 
     2251   
    22622252  *equat_shell* = *equat_core* + *T_shell* 
     2253   
    22632254  *polar_shell* = *equat_core* \* *X_core* + *T_shell* \* *XpolarShell* 
    22642255 
     
    24442435 
    24452436where |delta|\ T = tail length (or *t_length*), |delta|\ H = head thickness (or *h_thickness*), 
    2446 |drho|\ H = SLD(headgroup) - SLD(solvent), and |drho|\ T = SLD(tail) - SLD(solvent). 
     2437|drho|\ H = SLD(headgroup) - SLD(solvent), and |drho|\ T = SLD(tail) - SLD(solvent). The total thickness is 2(H+T). 
    24472438 
    24482439The 2D scattering intensity is calculated in the same way as 1D, where the *q* vector is defined as 
     
    33723363 
    33733364 
     3365.. _MicelleSphCoreModel: 
     3366 
     3367**2.1.42. MicelleSphCoreModel** 
     3368 
     3369This model provides the form factor, *P(q)*, for a micelle with a spherical core  
     3370and Gaussian polymer chains attached to the surface. 
     3371 
     3372*2.1.42.1. Definition* 
     3373 
     3374The 1D scattering intensity for this model is calculated according to the equations given by Pedersen 
     3375(Pedersen, 2000). 
     3376 
     3377*2.1.42.2. Validation of the MicelleSphCoreModel* 
     3378 
     3379This model has not yet been validated. Feb2015 
     3380 
     3381REFERENCES 
     3382 
     3383J Pedersen, *J. Appl. Cryst.*, 33 (2000) 637-640 
     3384 
     3385 
     3386 
    337433872.2 Shape-independent Functions 
    33753388------------------------------- 
     
    35543567*2.2.5.1. Definition* 
    35553568 
    3556 .. image:: img/image180.PNG 
     3569.. image:: img/image180_corrected.PNG 
    35573570 
    35583571The parameter *L* is the correlation length. 
     
    40704083This model fits the Porod function 
    40714084 
    4072 .. image:: img/image197.PNG 
     4085.. image:: img/image197_corrected.PNG 
    40734086 
    40744087to the data directly without any need for linearisation (*cf*. Log *I(q)* vs Log *q*). 
     
    47764789**2.3.3. HayterMSAStructure Factor** 
    47774790 
    4778 This calculates the structure factor (the Fourier transform of the pair correlation function *g(r)*) for a system of 
    4779 charged, spheroidal objects in a dielectric medium. When combined with an appropriate form factor (such as sphere, 
    4780 core+shell, ellipsoid, etc), this allows for inclusion of the interparticle interference effects due to screened coulomb 
    4781 repulsion between charged particles. 
     4791This is an implementation of the Rescaled Mean Spherical Approximation which calculates the structure factor (the  
     4792Fourier transform of the pair correlation function *g(r)*) for a system of charged, spheroidal objects in a 
     4793dielectric medium. When combined with an appropriate form factor (such as sphere,core+shell, ellipsoid, etc), this 
     4794allows for inclusion of the interparticle interference effects due to screened coulomb repulsion between charged particles. 
    47824795 
    47834796**This routine only works for charged particles**. If the charge is set to zero the routine will self-destruct! 
  • src/sas/models/qsmearing.py

    rfd5ac0d ra3f125f0  
    5959    if _found_resolution == True: 
    6060        return QSmearer(data1D, model) 
     61        #return pinhole_smear(data1D, model) 
    6162 
    6263    # Look for slit smearing data 
     
    8182    # If we found slit smearing data, return a slit smearer 
    8283    if _found_slit == True: 
    83         return SlitSmearer(data1D, model) 
     84        #return SlitSmearer(data1D, model) 
     85        return slit_smear(data1D, model) 
    8486    return None 
    8587             
     
    198200                iq_in[len(iq_in) - 1] = iq_in_high[0] 
    199201            # Append the extrapolated points to the data points 
    200             if self.nbins_low > 0:                              
     202            if self.nbins_low > 0: 
    201203                iq_in_temp = numpy.append(iq_in_low, iq_in) 
    202204            if self.nbins_high > 0: 
     
    583585    return nbins_low, nbins_high, \ 
    584586             new_width[data_x_ext > 0], data_x_ext[data_x_ext > 0] 
     587 
     588 
     589 
     590from .resolution import Slit1D, Pinhole1D 
     591class PySmear(object): 
     592    """ 
     593    Wrapper for pure python sasmodels resolution functions. 
     594    """ 
     595    def __init__(self, resolution, model): 
     596        self.model = model 
     597        self.resolution = resolution 
     598        self.offset = numpy.searchsorted(self.resolution.q_calc, self.resolution.q[0]) 
     599 
     600    def apply(self, iq_in, first_bin=0, last_bin=None): 
     601        """ 
     602        Apply the resolution function to the data. 
     603 
     604        Note that this is called with iq_in matching data.x, but with 
     605        iq_in[first_bin:last_bin] set to theory values for these bins, 
     606        and the remainder left undefined.  The first_bin, last_bin values 
     607        should be those returned from get_bin_range. 
     608 
     609        The returned value is of the same length as iq_in, with the range 
     610        first_bin:last_bin set to the resolution smeared values. 
     611        """ 
     612        if last_bin is None: last_bin = len(iq_in) 
     613        start, end = first_bin + self.offset, last_bin + self.offset 
     614        q_calc = self.resolution.q_calc 
     615        iq_calc = numpy.empty_like(q_calc) 
     616        if start > 0: 
     617            iq_calc[:start] = self.model.evalDistribution(q_calc[:start]) 
     618        if end+1 < len(q_calc): 
     619            iq_calc[end+1:] = self.model.evalDistribution(q_calc[end+1:]) 
     620        iq_calc[start:end+1] = iq_in[first_bin:last_bin+1] 
     621        smeared = self.resolution.apply(iq_calc) 
     622        return smeared 
     623    __call__ = apply 
     624 
     625    def get_bin_range(self, q_min=None, q_max=None): 
     626        """ 
     627        For a given q_min, q_max, find the corresponding indices in the data. 
     628 
     629        Returns first, last. 
     630 
     631        Note that these are indexes into q from the data, not the q_calc 
     632        needed by the resolution function.  Note also that these are the 
     633        indices, not the range limits.  That is, the complete range will be 
     634        q[first:last+1]. 
     635        """ 
     636        q = self.resolution.q 
     637        first = numpy.searchsorted(q, q_min) 
     638        last = numpy.searchsorted(q, q_max) 
     639        return first, min(last,len(q)-1) 
     640 
     641def slit_smear(data, model=None): 
     642    q = data.x 
     643    width = data.dxw if data.dxw is not None else 0 
     644    height = data.dxl if data.dxl is not None else 0 
     645    # TODO: width and height seem to be reversed 
     646    return PySmear(Slit1D(q, height, width), model) 
     647 
     648def pinhole_smear(data, model=None): 
     649    q = data.x 
     650    width = data.dx if data.dx is not None else 0 
     651    return PySmear(Pinhole1D(q, width), model) 
  • src/sas/models/sas_extension/__init__.py

    r79492222 rfb3f9af  
     1""" 
     2This is an empty package - should probably delete 
     3""" 
  • src/sas/models/dispersion_models.py

    rfd5ac0d r0e4e554  
    154154        c_models.set_dispersion_weights(self.cdisp, values, weights) 
    155155         
    156 models = {"gaussian":GaussianDispersion,  "rectangula":RectangleDispersion, 
     156models = {"gaussian":GaussianDispersion,  "rectangular":RectangleDispersion, 
    157157          "array":ArrayDispersion, "schulz":SchulzDispersion,  
    158158          "lognormal":LogNormalDispersion}        
Note: See TracChangeset for help on using the changeset viewer.