Exemple #1
0
 def addMagAtom(self, magAtom, symmetry):
     # add a secondary magnetic atom object to the model
     if self.magAtoms != None:
         self.magAtoms.append(magAtom)
     else:
         self.magAtoms = [magAtom]
     self.matom_index += 1
     matom = self.magAtoms[self.matom_index]
     matom.setLabel(rstrip(matom.label()))
     self.symmetry = symmetry
     self.magnetic = True
     self.numVectors = self.symmetry.numBasisFunc()[self.magAtoms[self.matom_index].irrepNum()[0]-1]
     if self.matom_index != 0:
         param_label = " kvect: " + str(self.matom_index+1)
     else:
         param_label = ""        
     if self.coeffs == None:
         self.coeffs = [None] * self.numVectors
         j = 0
     else:
         self.coeffs.extend([None] * self.numVectors)
         j = len(self.coeffs)
     for i in xrange(self.numVectors):
         self.coeffs[i+j] = Parameter(matom.basis()[0][i], name=self.atom.label() + " C" + str(i) + param_label)
     if self.phases == None:
         self.phases = [Parameter(matom.phase[0], name=self.atom.label() + " phase"+param_label)]
     else:
         self.phases.append(Parameter(matom.phase[0], name=self.atom.label() + " phase"+param_label))
     self.magAtoms[self.matom_index] = matom
Exemple #2
0
def load_model(model, name=None, **kw):
    sans = __import__('sans.models.' + model)
    ModelClass = getattr(getattr(sans.models, model, None), model, None)
    if ModelClass is None:
        raise ValueError("could not find model %r in sans.models" % model)
    M = ModelClass()
    prefix = (name if name else _model_name(M)) + " "
    M._bumps_pars = {}
    valid_pars = M.getParamList()
    for k, v in kw.items():
        # dispersion parameters initialized with _field instead of .field
        if k.endswith('_width'): k = k[:-6] + '.width'
        elif k.endswith('_npts'): k = k[:-5] + '.npts'
        elif k.endswith('_nsigmas'): k = k[:-7] + '.nsigmas'
        elif k.endswith('_type'): k = k[:-5] + '.type'
        if k not in valid_pars:
            formatted_pars = ", ".join(valid_pars)
            raise KeyError("invalid parameter %r for %s--use one of: %s" %
                           (k, model, formatted_pars))
        if '.' in k and not k.endswith('.width'):
            M.setParam(k, v)
        elif isinstance(v, BaseParameter):
            M._bumps_pars[k] = v
        elif isinstance(v, (tuple, list)):
            low, high = v
            P = Parameter((low + high) / 2, bounds=v, name=prefix + k)
            M._bumps_pars[k] = P
        else:
            P = Parameter(v, name=prefix + k)
            M._bumps_pars[k] = P
    return M
Exemple #3
0
 def __init__(self, a, b, c, beta):
     self.cell = CrystalCell()
     self.a = Parameter(a, name='a')
     self.b = Parameter(b, name='b')
     self.c = Parameter(c, name='c')
     self.beta = Parameter(beta, name='beta')
     self.update()
Exemple #4
0
    def __init__(self, data, model, cutoff=1e-5, **kw):
        from bumps.names import Parameter

        # remember inputs so we can inspect from outside
        self.data = data
        self.model = model
        self.cutoff = cutoff

        partype = model.info['partype']

        # interpret data
        if hasattr(data, 'qx_data'):
            self.index = (data.mask==0) & (~np.isnan(data.data))
            self.iq = data.data[self.index]
            self.diq = data.err_data[self.index]
            self._theory = np.zeros_like(data.data)
            if not partype['orientation'] and not partype['magnetic']:
                q_vectors = [np.sqrt(data.qx_data**2+data.qy_data**2)]
            else:
                q_vectors = [data.qx_data, data.qy_data]
        else:
            self.index = (data.x>=data.qmin) & (data.x<=data.qmax) & ~np.isnan(data.y)
            self.iq = data.y[self.index]
            self.diq = data.dy[self.index]
            self._theory = np.zeros_like(data.y)
            q_vectors = [data.x]

        # Remember function inputs so we can delay loading the function and
        # so we can save/restore state
        self._fn_inputs = [v[self.index] for v in q_vectors]
        self._fn = None

        # define bumps parameters
        pars = []
        for p in model.info['parameters']:
            name, default, limits, ptype = p[0], p[2], p[3], p[4]
            value = kw.pop(name, default)
            setattr(self, name, Parameter.default(value, name=name, limits=limits))
            pars.append(name)
        for name in partype['pd-2d']:
            for xpart,xdefault,xlimits in [
                    ('_pd', 0, limits),
                    ('_pd_n', 35, (0,1000)),
                    ('_pd_nsigma', 3, (0, 10)),
                    ('_pd_type', 'gaussian', None),
                ]:
                xname = name+xpart
                xvalue = kw.pop(xname, xdefault)
                if xlimits is not None:
                    xvalue = Parameter.default(xvalue, name=xname, limits=xlimits)
                    pars.append(xname)
                setattr(self, xname, xvalue)
        self._parameter_names = pars
        if kw:
            raise TypeError("unexpected parameters: %s"%(", ".join(sorted(kw.keys()))))
        self.update()
Exemple #5
0
 def __init__(self, data, model, dtype='float32', **kw):
     self.__dict__['_parameters'] = {}
     #self.name = data.filename
     self.is2D = hasattr(data,'qx_data')
     self.data = data
     if self.is2D:
         self.index = (data.mask==0) & (~np.isnan(data.data))
         self.iq = data.data[self.index]
         self.diq = data.err_data[self.index]
         self.qx = data.qx_data
         self.qy = data.qy_data
         self.gpu = model(self.qx, self.qy, dtype=dtype)
     else:
         self.index = (data.mask==0) & (~np.isnan(data.y))
         self.iq = data.y[self.index]
         self.diq = data.dy[self.index]
         self.q = data.x
         self.gpu = model(self.q, dtype=dtype)
     pd_pars = set(base+attr for base in model.PD_PARS for attr in ('_pd','_pd_n','_pd_nsigma'))
     total_pars = set(model.PARS.keys()) | pd_pars
     extra_pars = set(kw.keys()) - total_pars
     if extra_pars:
         raise TypeError("unexpected parameters %s"%(str(extra_pars,)))
     pars = model.PARS.copy()
     pars.update((base+'_pd', 0) for base in model.PD_PARS)
     pars.update((base+'_pd_n', 35) for base in model.PD_PARS)
     pars.update((base+'_pd_nsigma', 3) for base in model.PD_PARS)
     pars.update(kw)
     for k,v in pars.items():
         setattr(self, k, Parameter.default(v, name=k))
     self._parameter_names = set(pars.keys())
     self.update()
Exemple #6
0
 def __init__(self, data, model, dtype='float32', **kw):
     self.__dict__['_parameters'] = {}
     #self.name = data.filename
     self.is2D = hasattr(data, 'qx_data')
     self.data = data
     if self.is2D:
         self.index = (data.mask == 0) & (~np.isnan(data.data))
         self.iq = data.data[self.index]
         self.diq = data.err_data[self.index]
         self.qx = data.qx_data
         self.qy = data.qy_data
         self.gpu = model(self.qx, self.qy, dtype=dtype)
     else:
         self.index = (data.mask == 0) & (~np.isnan(data.y))
         self.iq = data.y[self.index]
         self.diq = data.dy[self.index]
         self.q = data.x
         self.gpu = model(self.q, dtype=dtype)
     pd_pars = set(base + attr for base in model.PD_PARS
                   for attr in ('_pd', '_pd_n', '_pd_nsigma'))
     total_pars = set(model.PARS.keys()) | pd_pars
     extra_pars = set(kw.keys()) - total_pars
     if extra_pars:
         raise TypeError("unexpected parameters %s" % (str(extra_pars, )))
     pars = model.PARS.copy()
     pars.update((base + '_pd', 0) for base in model.PD_PARS)
     pars.update((base + '_pd_n', 35) for base in model.PD_PARS)
     pars.update((base + '_pd_nsigma', 3) for base in model.PD_PARS)
     pars.update(kw)
     for k, v in pars.items():
         setattr(self, k, Parameter.default(v, name=k))
     self._parameter_names = set(pars.keys())
     self.update()
Exemple #7
0
def _sas_parameter(model, pid, prefix):
    par = getattr(model, '_bumps_pars', {}).get(pid, None)
    if par is None:
        ## Don't have bounds on dispersion parameters with model details
        #bounds = model.details.get(pid,[None,None,None])[1:3]
        value = model.getParam(pid)
        par = Parameter(value, name=prefix + pid)
    return par
Exemple #8
0
def create_parameters(model_info, **kwargs):
    """
    Generate Bumps parameters from the model info.

    *model_info* is returned from :func:`generate.model_info` on the
    model definition module.

    Any additional *key=value* pairs are initial values for the parameters
    to the models.  Uninitialized parameters will use the model default
    value.

    Returns a dictionary of *{name: Parameter}* containing the bumps
    parameters for each model parameter, and a dictionary of
    *{name: str}* containing the polydispersity distribution types.
    """
    # lazy import; this allows the doc builder and nosetests to run even
    # when bumps is not on the path.
    from bumps.names import Parameter

    pars = {}
    for p in model_info['parameters']:
        value = kwargs.pop(p.name, p.default)
        pars[p.name] = Parameter.default(value, name=p.name, limits=p.limits)
    for name in model_info['partype']['pd-2d']:
        for xpart, xdefault, xlimits in [
            ('_pd', 0., pars[name].limits),
            ('_pd_n', 35., (0, 1000)),
            ('_pd_nsigma', 3., (0, 10)),
        ]:
            xname = name + xpart
            xvalue = kwargs.pop(xname, xdefault)
            pars[xname] = Parameter.default(xvalue, name=xname, limits=xlimits)

    pd_types = {}
    for name in model_info['partype']['pd-2d']:
        xname = name + '_pd_type'
        xvalue = kwargs.pop(xname, 'gaussian')
        pd_types[xname] = xvalue

    if kwargs:  # args not corresponding to parameters
        raise TypeError("unexpected parameters: %s" %
                        (", ".join(sorted(kwargs.keys()))))

    return pars, pd_types
Exemple #9
0
def create_parameters(model_info, **kwargs):
    """
    Generate Bumps parameters from the model info.

    *model_info* is returned from :func:`generate.model_info` on the
    model definition module.

    Any additional *key=value* pairs are initial values for the parameters
    to the models.  Uninitialized parameters will use the model default
    value.

    Returns a dictionary of *{name: Parameter}* containing the bumps
    parameters for each model parameter, and a dictionary of
    *{name: str}* containing the polydispersity distribution types.
    """
    # lazy import; this allows the doc builder and nosetests to run even
    # when bumps is not on the path.
    from bumps.names import Parameter

    pars = {}
    for p in model_info['parameters']:
        value = kwargs.pop(p.name, p.default)
        pars[p.name] = Parameter.default(value, name=p.name, limits=p.limits)
    for name in model_info['partype']['pd-2d']:
        for xpart, xdefault, xlimits in [
                ('_pd', 0., pars[name].limits),
                ('_pd_n', 35., (0, 1000)),
                ('_pd_nsigma', 3., (0, 10)),
            ]:
            xname = name + xpart
            xvalue = kwargs.pop(xname, xdefault)
            pars[xname] = Parameter.default(xvalue, name=xname, limits=xlimits)

    pd_types = {}
    for name in model_info['partype']['pd-2d']:
        xname = name + '_pd_type'
        xvalue = kwargs.pop(xname, 'gaussian')
        pd_types[xname] = xvalue

    if kwargs:  # args not corresponding to parameters
        raise TypeError("unexpected parameters: %s"
                        % (", ".join(sorted(kwargs.keys()))))

    return pars, pd_types
Exemple #10
0
def create_parameters(
        model_info,  # type: ModelInfo
        **kwargs  # type: Union[float, str, Parameter]
):
    # type: (...) -> Tuple[Dict[str, Parameter], Dict[str, str]]
    """
    Generate Bumps parameters from the model info.

    *model_info* is returned from :func:`generate.model_info` on the
    model definition module.

    Any additional *key=value* pairs are initial values for the parameters
    to the models.  Uninitialized parameters will use the model default
    value.  The value can be a float, a bumps parameter, or in the case
    of the distribution type parameter, a string.

    Returns a dictionary of *{name: Parameter}* containing the bumps
    parameters for each model parameter, and a dictionary of
    *{name: str}* containing the polydispersity distribution types.
    """
    pars = {}  # type: Dict[str, Parameter]
    pd_types = {}  # type: Dict[str, str]
    for p in model_info.parameters.call_parameters:
        value = kwargs.pop(p.name, p.default)
        pars[p.name] = Parameter.default(value, name=p.name, limits=p.limits)
        if p.polydisperse:
            for part, default, limits in [
                ('_pd', 0., pars[p.name].limits),
                ('_pd_n', 35., (0, 1000)),
                ('_pd_nsigma', 3., (0, 10)),
            ]:
                name = p.name + part
                value = kwargs.pop(name, default)
                pars[name] = Parameter.default(value, name=name, limits=limits)
            name = p.name + '_pd_type'
            pd_types[name] = str(kwargs.pop(name, 'gaussian'))

    if kwargs:  # args not corresponding to parameters
        raise TypeError("unexpected parameters: %s" %
                        (", ".join(sorted(kwargs.keys()))))

    return pars, pd_types
Exemple #11
0
def create_parameters(model_info, **kwargs):
    # type: (ModelInfo, **Union[float, str, Parameter]) -> Tuple[Dict[str, Parameter], Dict[str, str]]
    """
    Generate Bumps parameters from the model info.

    *model_info* is returned from :func:`generate.model_info` on the
    model definition module.

    Any additional *key=value* pairs are initial values for the parameters
    to the models.  Uninitialized parameters will use the model default
    value.  The value can be a float, a bumps parameter, or in the case
    of the distribution type parameter, a string.

    Returns a dictionary of *{name: Parameter}* containing the bumps
    parameters for each model parameter, and a dictionary of
    *{name: str}* containing the polydispersity distribution types.
    """
    pars = {}     # type: Dict[str, Parameter]
    pd_types = {} # type: Dict[str, str]
    for p in model_info.parameters.call_parameters:
        value = kwargs.pop(p.name, p.default)
        pars[p.name] = Parameter.default(value, name=p.name, limits=p.limits)
        if p.polydisperse:
            for part, default, limits in [
                    ('_pd', 0., pars[p.name].limits),
                    ('_pd_n', 35., (0, 1000)),
                    ('_pd_nsigma', 3., (0, 10)),
                ]:
                name = p.name + part
                value = kwargs.pop(name, default)
                pars[name] = Parameter.default(value, name=name, limits=limits)
            name = p.name + '_pd_type'
            pd_types[name] = str(kwargs.pop(name, 'gaussian'))

    if kwargs:  # args not corresponding to parameters
        raise TypeError("unexpected parameters: %s"
                        % (", ".join(sorted(kwargs.keys()))))

    return pars, pd_types
Exemple #12
0
    def __init__(self, atom, sgmultip):
#        if isSequence(atoms):
            # changes properties of both a regular atom and a magnetic atom
            #   (they should correspond to the same atomic position)
#            self.atom = atoms[0]
#            self.magAtom = atoms[1]
#            self.magAtom.label = rstrip(self.magAtom.label)
#            self.magnetic = True
#        else:
        self.atom = atom
        self.magnetic = False
        self.magAtoms = None
        self.matom_index = -1
        self.coeffs = None
        self.phases = None
        self.sgmultip = sgmultip
        self.atom.set_atom_lab(rstrip(self.atom.label()))
        self.B = Parameter(self.atom.BIso(), name=self.atom.label() + " B")
        occ = self.atom.occupancy() / self.atom.multip() * self.sgmultip
        self.occ = Parameter(occ, name=getAtom_lab(self.atom) + " occ")
        self.x = Parameter(self.atom.coords()[0], name=self.atom.label() + " x")
        self.y = Parameter(self.atom.coords()[1], name=self.atom.label() + " y")
        self.z = Parameter(self.atom.coords()[2], name=self.atom.label() + " z")
Exemple #13
0
 def __init__(self, a, b, c, alpha, beta, gamma):
     self.cell = CrystalCell()
     self.a = Parameter(a, name='a')
     self.b = Parameter(b, name='b')
     self.c = Parameter(c, name='c')
     self.alpha = Parameter(alpha, name='alpha')
     self.beta = Parameter(beta, name='beta')
     self.gamma = Parameter(gamma, name='gamma')
     self.update()
Exemple #14
0
 def __init__(self, tt, observed, background, u, v, w,
              wavelength, spaceGroupName, cell, atoms, exclusions=None,
              magnetic=False, symmetry=None, newSymmetry=None, base=None, scale=1, eta=0,zero=None, error=None, hkls=None, muR=None):
     if (isinstance(spaceGroupName, SpaceGroup)):
         self.spaceGroup = spaceGroupName
     else:
         self.spaceGroup = SpaceGroup(spaceGroupName)
     self.tt = np.array(tt)
     self.observed = observed
     self.background = background
     self.u = Parameter(u, name='u')
     self.v = Parameter(v, name='v')
     self.w = Parameter(w, name='w')
     self.scale = Parameter(scale, name='scale')
     self.eta = Parameter(eta, name='eta')
     self.error = error
     self.muR = muR
     # hkls for single crystal only
     if hkls != None:
         self.refList = hkls
     if base != None:
         self.base = Parameter(base, name='base')
         self.has_base = True
     else:
         self.base=0
         self.has_base = False
     if zero != None:
         self.zero = Parameter(zero, name='zero')
         self.has_zero = True
     else:
         self.zero = 0
         self.has_zero = False
     self.wavelength = wavelength
     self.cell = cell
     self.exclusions = exclusions
     self.ttMin = min(self.tt)
     self.ttMax = max(self.tt)
     self.sMin = getS(self.ttMin, self.wavelength)
     self.sMax = getS(self.ttMax, self.wavelength)
     self.magnetic = magnetic
     if magnetic:
         self.symmetry = symmetry
         # used for basis vector structure factor generation
         self.newSymmetry = newSymmetry
         self.atomListModel = AtomListModel(atoms, self.spaceGroup.get_space_group_multip(),
                                            True, self.newSymmetry)            
     else:
         self.atomListModel = AtomListModel(atoms, self.spaceGroup.get_space_group_multip(), False)
     self._set_reflections()           
     self.update()
Exemple #15
0
def load_fit(filename):
    data = FitReader(call_back=lambda **kw: None).read('FitPage2.fitv')
    data = data[0]  # no support for multiset files
    fit = data.meta_data['fitstate']
    model_name = fit.formfactorcombobox
    pars = dict((p[1], float(p[2])) for p in fit.parameters)
    for k, v in pars.items():
        if abs(v) < 1e-5 and v != 0:
            pars[k] = 1e-6 * Parameter(v * 1e6, name=model_name + " " + k)
    model = load_model(model_name, **pars)
    experiment = Experiment(model=model, data=data)
    for p in fit.parameters:
        if p[0]:
            low = float(p[5][1]) if p[5][1] else -np.inf
            high = float(p[6][1]) if p[6][1] else np.inf
            try:
                experiment[p[1]].range(low, high)
            except KeyError:
                print("%s not in experiment" % p[1])
    return experiment
Exemple #16
0
def build_problem(mydirectory, myfilebase, myend, cost="poisson"):

    monitor_efficiency = 0.1
    resolution = 0.001
    scale = resolution**2 / monitor_efficiency
    scale = 1e-6
    M = Peaks(
        [
            Gaussian(name="G1-"),
            Gaussian(name="G2-"),
            #Gaussian(name="G3-"),
            #Gaussian(name="G4-"),
            Background()
        ],
        scale,
        data=read_data(mydirectory, myfilebase, myend),
        #cost='poisson',
        cost=cost,
    )

    # Peak intensity and background
    background = 1
    M.parts[-1].C.value = background
    M.parts[-1].C.range(0, 1000)
    for peak in M.parts[:-1]:
        peak.A.value = 1. / (len(M.parts) - 1)  # Equal size peaks
        peak.A.range(0, 1)

    peak1 = M.parts[0]
    if 0:
        # Peak centers are independent
        for peak in M.parts[:-1]:
            peak.xc.range(0.45, 0.55)
            peak.yc.range(-0.55, -0.4)
    else:
        # Peak centers lie on a line
        alpha = Parameter(45.0, name="alpha")
        alpha.range(-90., 90.)
        peak1.xc.range(0.40, 0.55)
        peak1.yc.range(0.40, 0.55)
        #peak1.yc.range(-0.55,-0.4)
        for i, peak in enumerate(M.parts[1:-1]):
            delta = Parameter(.0045, name="delta-%d" % (i + 1))
            delta.range(0.00, 0.03)
            peak.xc = peak1.xc + delta * pmath.cosd(alpha)
            peak.yc = peak1.yc + delta * pmath.sind(alpha)

        # Initial values
        cx, cy = 0.4996 - 0.4957, -0.4849 + 0.4917
        alpha.value = np.degrees(np.arctan2(cy, cx))
        delta.value = np.sqrt(cx**2 + cy**2)
        peak1.xc.value, peak1.yc.value = 0.4957, 0.4917

    # Peak location and shape
    dx, dy = 0.4997 - 0.4903, -0.4969 + 0.4851
    dxm, dym = 0.4951 - 0.4960, -0.4941 + 0.4879
    peak1.s1.value = np.sqrt(dx**2 + dy**2) / 2.35 / 2
    peak1.s2.value = np.sqrt(dxm**2 + dym**2) / 2.35 / 2
    peak1.theta.value = np.degrees(np.arctan2(dy, dx))

    # Peak shape is the same across all peaks
    peak1.s1.range(0.001, 0.010)
    peak1.s2.range(0.001, 0.010)
    peak1.theta.range(-90, 90)
    for peak in M.parts[1:-1]:
        peak.s1 = peak1.s1
        peak.s2 = peak1.s2
        peak.theta = peak1.theta

    if 1:
        print "shape", peak1.s1.value, peak1.s2.value, peak1.theta.value
        print "centers alpha,delta", alpha.value, delta.value
        print "centers",(peak1.xc.value,peak1.yc.value),\
            (M.parts[1].xc.value,M.parts[1].yc.value)
    return FitProblem(M)
Exemple #17
0
 def __init__(self, a, c):
     self.cell = CrystalCell()
     self.a = Parameter(a, name='a')
     self.c = Parameter(c, name='c')
     self.update()
Exemple #18
0
def build_problem():

    M = Peaks(
        [
            Gaussian(name="G1-"),
            Gaussian(name="G2-"),
            #Gaussian(name="G3-"),
            #Gaussian(name="G4-"),
            Background()
        ],
        *read_data())
    background = np.min(M.data)
    background += np.sqrt(background)
    signal = np.sum(M.data) - M.data.size * background
    M.parts[-1].C.value = background
    peak1 = M.parts[0]

    peak1.xc.range(0.45, 0.55)
    peak1.yc.range(-0.55, -0.4)
    peak1.xc.value = 0.500
    peak1.yc.value = -0.485

    if 0:
        # Peak centers are independent
        for peak in M.parts[1:-1]:
            peak.xc.range(0.45, 0.55)
            peak.yc.range(-0.55, -0.4)
        M.parts[1].xc.value = 0.495
        M.parts[1].yc.value = -0.495
    else:
        # Peak centers lie on a line
        theta = Parameter(45, name="theta")
        theta.range(0, 90)
        for i, peak in enumerate(M.parts[1:-1]):
            delta = Parameter(0.0045, name="delta-%d" % (i + 1))
            delta.range(0.0, 0.015)
            peak.xc = peak1.xc + delta * cosd(theta)
            peak.yc = peak1.yc + delta * sind(theta)

        # Initial values
        cx, cy = 0.4996 - 0.4957, -0.4849 + 0.4917
        theta.value = np.degrees(np.arctan2(cy, cx))
        delta.value = np.sqrt(cx**2 + cy**2)

    # Initial values
    for peak in M.parts[:-1]:
        peak.A.value = signal / (len(M.parts) - 1)  # Equal size peaks
    dx, dy = 0.4997 - 0.4903, -0.4969 + 0.4851
    dxm, dym = 0.4951 - 0.4960, -0.4941 + 0.4879
    peak1.s1.value = np.sqrt(dx**2 + dy**2) / 2.35 / 2
    peak1.s2.value = np.sqrt(dxm**2 + dym**2) / 2.35 / 2
    peak1.theta.value = np.degrees(np.arctan2(dy, dx))

    # Peak intensity varies
    for peak in M.parts[:-1]:
        peak.A.range(0.1 * signal, 1.1 * signal)

    peak1.s1.range(0.002, 0.02)
    peak1.s2.range(0.001, 0.02)
    peak1.theta.range(-90, -0)

    if 1:
        # Peak shape is the same across all peaks
        for peak in M.parts[1:-1]:
            peak.s1 = peak1.s1
            peak.s2 = peak1.s2
            peak.theta = peak1.theta
    else:
        for peak in M.parts[1:-1]:
            peak.s1.range(*peak1.s1.bounds.limits)
            peak.s2.range(*peak1.s2.bounds.limits)
            peak.theta.range(*peak1.theta.bounds.limits)

    if 1:
        M.parts[-1].C.pmp(100.0)

    if 1:
        for peak in M.parts[:-1]:
            peak.s1.value = 0.006
            peak.s2.value = 0.002
            peak.theta.value = -60.0
            peak.A.value = signal / 2

    if 0:
        print("shape", peak1.s1.value, peak1.s2.value, peak1.theta.value)
        print("centers theta,delta", theta.value, delta.value)
        print("centers", (peak1.xc.value, peak1.yc.value),
              (M.parts[1].xc.value, M.parts[1].yc.value))
    return FitProblem(M)
Exemple #19
0
def build_problem():

    M = Peaks([Gaussian(name="G1-"),
               Gaussian(name="G2-"),
               #Gaussian(name="G3-"),
               #Gaussian(name="G4-"),
               Background()],
               *read_data())
    background = np.min(M.data)
    background += np.sqrt(background)
    signal = np.sum(M.data) - M.data.size*background
    M.parts[-1].C.value = background
    peak1 = M.parts[0]

    if 0:
        # Peak centers are independent
        for peak in M.parts[:-1]:
            peak.xc.range(0.45,0.55)
            peak.yc.range(-0.55,-0.4)
    else:
        # Peak centers lie on a line
        theta=Parameter(45, name="theta")
        theta.range(0,90)
        peak1.xc.range(0.45,0.55)
        peak1.yc.range(-0.55,-0.4)
        for i,peak in enumerate(M.parts[1:-1]):
            delta=Parameter(.0045, name="delta-%d"%(i+1))
            delta.range(0.0,0.015)
            peak.xc = peak1.xc + delta*pmath.cosd(theta)
            peak.yc = peak1.yc + delta*pmath.sind(theta)

        # Initial values
        cx, cy = 0.4996-0.4957, -0.4849+0.4917
        theta.value = np.degrees(np.arctan2(cy,cx))
        delta.value = np.sqrt(cx**2+cy**2)
        peak1.xc.value,peak1.yc.value = 0.4957,-0.4917

    # Initial values
    for peak in M.parts[:-1]:
        peak.A.value = signal/(len(M.parts)-1)  # Equal size peaks
    dx, dy = 0.4997-0.4903, -0.4969+0.4851
    dxm, dym = 0.4951-0.4960, -0.4941+0.4879
    peak1.s1.value = np.sqrt(dx**2+dy**2)/2.35/2
    peak1.s2.value = np.sqrt(dxm**2+dym**2)/2.35/2
    peak1.theta.value = np.degrees(np.arctan2(dy,dx))


    # Peak intensity varies
    for peak in M.parts[:-1]:
        peak.A.range(0.25*signal,1.1*signal)

    # Peak shape is the same across all peaks
    peak1.s1.range(0.002,0.02)
    peak1.s2.range(0.001,0.02)
    peak1.theta.range(-90, -0)
    for peak in M.parts[1:-1]:
        peak.s1 = peak1.s1
        peak.s2 = peak1.s2
        peak.theta = peak1.theta

    if 1:
        print "shape",peak1.s1.value,peak1.s2.value,peak1.theta.value
        print "centers theta,delta",theta.value,delta.value
        print "centers",(peak1.xc.value,peak1.yc.value),\
            (M.parts[1].xc.value,M.parts[1].yc.value)
    return FitProblem(M)
Exemple #20
0
def build_problem(mydirectory, myfilebase, myend):

    M = Peaks(
        [
            Gaussian(name="G1-"),
            Gaussian(name="G2-"),
            #Gaussian(name="G3-"),
            #Gaussian(name="G4-"),
            Background()
        ],
        *read_data(mydirectory, myfilebase, myend))
    background = np.min(M.data)
    background += np.sqrt(background)
    signal = np.sum(M.data) - M.data.size * background
    M.parts[-1].C.value = background
    M.parts[-1].C.range(0, 200)
    peak1 = M.parts[0]

    if 0:
        # Peak centers are independent
        for peak in M.parts[:-1]:
            peak.xc.range(0.45, 0.55)
            peak.yc.range(-0.55, -0.4)
    else:
        # Peak centers lie on a line
        alpha = Parameter(45.0, name="alpha")
        alpha.range(-90., 90.)
        peak1.xc.range(0.40, 0.55)
        peak1.yc.range(0.40, 0.55)
        #peak1.yc.range(-0.55,-0.4)
        for i, peak in enumerate(M.parts[1:-1]):
            delta = Parameter(.0045, name="delta-%d" % (i + 1))
            delta.range(0.00, 0.03)
            peak.xc = peak1.xc + delta * pmath.cosd(alpha)
            peak.yc = peak1.yc + delta * pmath.sind(alpha)

        # Initial values
        cx, cy = 0.4996 - 0.4957, -0.4849 + 0.4917
        alpha.value = np.degrees(np.arctan2(cy, cx))
        delta.value = np.sqrt(cx**2 + cy**2)
        peak1.xc.value, peak1.yc.value = 0.4957, -0.4917

    # Initial values
    for peak in M.parts[:-1]:
        peak.A.value = signal / (len(M.parts) - 1)  # Equal size peaks
    dx, dy = 0.4997 - 0.4903, -0.4969 + 0.4851
    dxm, dym = 0.4951 - 0.4960, -0.4941 + 0.4879
    peak1.s1.value = np.sqrt(dx**2 + dy**2) / 2.35 / 2
    peak1.s2.value = np.sqrt(dxm**2 + dym**2) / 2.35 / 2
    peak1.theta.value = np.degrees(np.arctan2(dy, dx))

    # Peak intensity varies
    for peak in M.parts[:-1]:
        peak.A.range(0.10 * signal, 1.1 * signal)

    # Peak shape is the same across all peaks
    peak1.s1.range(0.001, 0.010)
    peak1.s2.range(0.001, 0.004)
    peak1.theta.range(0, 90)
    for peak in M.parts[1:-1]:
        peak.s1 = peak1.s1
        peak.s2 = peak1.s2
        peak.theta = peak1.theta

    if 1:
        print "shape", peak1.s1.value, peak1.s2.value, peak1.theta.value
        print "centers alpha,delta", alpha.value, delta.value
        print "centers",(peak1.xc.value,peak1.yc.value),\
            (M.parts[1].xc.value,M.parts[1].yc.value)
    return FitProblem(M)
Exemple #21
0
 def __init__(self,
              tt,
              observed,
              background,
              wavelength,
              spaceGroupName,
              cell,
              atoms,
              exclusions=None,
              magnetic=False,
              symmetry=None,
              newSymmetry=None,
              scale=1,
              zero=None,
              error=None,
              hkls=None,
              extinction=[0]):
     if (isinstance(spaceGroupName, SpaceGroup)):
         self.spaceGroup = spaceGroupName
     else:
         self.spaceGroup = SpaceGroup(spaceGroupName)
     self.tt = np.array(tt)
     self.obspeaks = makeXtalPeaks(
         observed, [getS(ttval, wavelength) for ttval in self.tt],
         refList=hkls,
         error=error)
     self.sList = np.array([peak.svalue for peak in self.obspeaks])
     self.observed = np.array([peak.sfs2 for peak in self.obspeaks])
     self.background = background
     self.scale = Parameter(scale, name='scale')
     self.extinctions = [
         Parameter(extinction[i], name="Extinction" + str(i))
         for i in range(len(extinction))
     ]
     self.error = error
     self.refList = hkls
     self.base = 0
     if zero != None:
         self.zero = Parameter(zero, name='zero')
         self.has_zero = True
     else:
         self.zero = 0
         self.has_zero = False
     self.wavelength = wavelength
     self.cell = cell
     self.exclusions = exclusions
     if len(tt) != 0:
         self.ttMin = min(self.tt)
         self.ttMax = max(self.tt)
         self.sMin = getS(self.ttMin, self.wavelength)
         self.sMax = getS(self.ttMax, self.wavelength)
     self.magnetic = magnetic
     if magnetic:
         self.symmetry = symmetry
         # used for basis vector structure factor generation
         self.newSymmetry = newSymmetry
         self.atomListModel = AtomListModel(
             atoms, self.spaceGroup.get_space_group_multip(), True,
             self.newSymmetry)
     else:
         self.atomListModel = AtomListModel(
             atoms, self.spaceGroup.get_space_group_multip(), False)
     self._set_reflections()
     self._set_observations(observed)
     self.update()