Beispiel #1
0
 def __init__(self, parent):
     framework.Template.__init__(self, parent)
     plotpanel = self.NewPlotFolder('Test')
     inputpanel = self.NewInputFolder('Test')
     datapanel = self.NewDataFolder('Test')
     menu = self.NewMenu('Test')
     iprint('Everyting tested, should be visible :-)')
Beispiel #2
0
    def __init__(self, fn, userext=[], **kwargs):
        """Initialize SpecDataFile

        Parameters
        ----------
        fn : string
             Filename of spec file to open
        userext : list
             A list of user extension classes to run on data

        Returns a SpecDataFile object

        """
        self.filename = fn
        self.mode = 'concat'  # Set the default to concatenate multiple files

        # User extensions for adding functionality
        self.userExtensions = userext
        self.userExtensions = self.userExtensions + DefaultUserExtensions

        if __verbose__:
            for ext in self.userExtensions:
                iprint("**** Defining extension %s" % ext.getName())

        for ext in self.userExtensions:
            ext.initSpec(self)

        for arg in kwargs:
            # Set any keyword args into the base class
            setattr(self, arg, kwargs[arg])

        self._loadSpecFile()
        return
Beispiel #3
0
def AmpElfield2(kx, k, n, z):
    kz = sqrt(n[:, newaxis]**2 * k**2 - kx**2)
    r = (kz[:-1] - kz[1:]) / (kz[:-1] + kz[1:])
    t = 1 + r
    X = 0 * ones(kx.shape)
    for i in range(len(n) - 2, -1, -1):
        X = exp(
            -2j * kz[i] * z[i]) * (r[i] + X * exp(2j * kz[i + 1] * z[i])) / (
                1 + r[i] * X * exp(2j * kz[i + 1] * z[i]))
        iprint(i)
    # X=reflected amplitude...
    r = (kz[1:] - kz[:-1]) / (kz[:-1] + kz[1:])
    t = 1 + r
    R = [X]
    T = [1 * ones(X.shape)]
    for i in range(0, len(n) - 1, 1):
        R.append(1 / t[i] * (T[i] * r[i] * exp(-1.0j *
                                               (kz[i + 1] + kz[i]) * z[i]) +
                             R[i] * exp(-1.0j * (kz[i + 1] - kz[i]) * z[i])))
        T.append(1 / t[i] * (T[i] * exp(1.0j * (kz[i + 1] - kz[i]) * z[i]) +
                             R[i] * r[i] * exp(1.0j *
                                               (kz[i + 1] + kz[i]) * z[i])))
    #R[len(n)-1]=0*ones(X.shape)
    R = array(R)
    T = array(T)
    return (T, R, kz)
Beispiel #4
0
    def __init__(self, parent):
        #print "__init__ SXRD Plugin"

        framework.Template.__init__(self, parent)
        self.setup_script_interactor()
        if self.GetModelScript() == '':
            self.script_interactor.parse_code(code)
            self.SetModelScript(self.script_interactor.get_code())
        else:
            try:
                self.script_interactor.parse_code(self.GetModelScript())
            except Exception as e:
                iprint("Reflectivity plugin model could not be read.")
                self.script_interactor.parse_code(code)
                self.SetModelScript(self.script_interactor.get_code())

        self.layout_sample_edit()
        self.layout_simulation_edit()
        self.layout_misc_edit()
        self.layout_domain_viewer()
        self.create_main_window_menu()

        self.OnInteractorChanged(None)
        self.update_data_names()
        self.simulation_edit_widget.Update()
        self.update_widgets()
Beispiel #5
0
    def simulate(self, instrument, h, k, qz):
        self.layer_dic = {}
        # Add a q = 0 point for the mean scattering potential
        q = np.c_[h * 2 * np.pi / self.a(), k * 2 * np.pi / self.b(), -qz].T
        kwargs = {'z': 0.0, 'q': q}
        wavelength = instrument.wl(**kwargs)
        kwargs['wl'] = wavelength

        area_uc = (self.a * self.b)(**kwargs)
        dic = self.build_layer_list(['d', 'sld'], kwargs)
        vf, d = 4 * np.pi * np.array(dic['sld']), np.array(dic['d'])
        kwargs['q'] = np.array([0, 0, 0])
        vmean = 4 * np.pi * np.array(
            self.build_layer_list(['sld'], kwargs)['sld']) / area_uc
        self.layer_dic['sld_mean'] = vmean / 4 / np.pi
        self.layer_dic['d'] = d
        iprint(vmean.shape, vf.shape)
        k_in, k_out = instrument.reflectometer_3axis_kinout(q)
        R = grating.coherent_refl(k_in,
                                  k_out,
                                  wavelength,
                                  vf.T,
                                  vmean,
                                  d,
                                  area_uc,
                                  kin=False)
        return R
Beispiel #6
0
def reflq_kin(q, lamda, n, d, sigma, correct_q=True, return_int=True):
    """Calculates the reflectivity in the kinematical approximation"""
    d = d[:-1]
    d[0] = 0
    z = d.sum() - d.cumsum()
    sigma = sigma[:-1]
    q0 = 4 * pi / lamda
    # Kinematical reflectivity for the interfaces
    iprint(n.shape, len(n.shape))
    if len(n.shape) == 1:
        if correct_q:
            # The internal wave vector calacuted with the thickness averaged refractive index.
            n_mean = (n[1:-1] * d[1:] / d.sum()).sum()
            q_corr = sqrt((n_mean**2 - n[-1]**2) * q0**2 + (n[-1] * q)**2)
        else:
            q_corr = q
        rp = (n[:-1] - n[1:])[:, newaxis] * exp(
            -(q_corr * sigma[:, newaxis])**2 / 2)
    else:
        if correct_q:
            # The internal wave vector calacuted with the thickness averaged refractive index.
            n_mean = (n[1:-1] * d[1:][:, newaxis] / d.sum()).sum(axis=0)
            q_corr = sqrt((n_mean**2 - n[-1]**2) * q0**2 + (n[-1] * q)**2)
        else:
            q_corr = q
        rp = (n[:-1] - n[1:]) * exp(-(q_corr * sigma[:, newaxis])**2 / 2)
    p = exp(1.0j * z[:, newaxis] * q_corr)

    r = (rp * p).sum(axis=0) * q0**2 / q_corr**2 / 2.

    if return_int:
        return abs(r)**2
    else:
        return r
Beispiel #7
0
    def _getLine(self):
        """Read line from datafile"""

        line = self.file.readline()
        if __verbose__ & 0x10:
            iprint("xxxx %s" % line.strip())
        return line
Beispiel #8
0
    def readHeader(self):
        """Read the spec header from the datafile.

        Currently supported header items:
                '#O'    (Motor positions)
        """

        self.file = open(self.filename, 'r')

        if __verbose__:
            iprint("---- Reading Header.")

        self.motors = []
        self.file.seek(0, 0)
        line = self.file.readline()
        while line[0:2] != "#S":
            if line[0:2] == "#O":
                self.motors = self.motors + splitSpecString(line[4:])
            else:
                # Run user extensions
                for ext in self.userExtensions:
                    ext.parseSpecHeader(self, line)

            line = self.file.readline()

        for ext in self.userExtensions:
            ext.postProcessSpecHeader(self)

        self.file.close()
        return
Beispiel #9
0
    def show(self, prefix="", nperline=4):
        """Return string of statistics on SpecScan"""
        p = ""
        p = p + "Scan:\n\n"
        p = p + "\t%s\n\n" % self.scan
        p = p + "Datafile:\n\n"
        p = p + "\t%s\n\n" % self.datafile.file.name
        p = p + "Scan Command:\n\n"
        p = p + "\t%s\n\n" % self.scan_command
        p = p + "Scan Constants:\n\n"

        j = nperline
        typestoprint = [float, str, numpy.ndarray, int, numpy.float64]

        for d in self.__dict__:
            if d not in self.scandata.values:
                if typestoprint.count(type(getattr(self, d))):
                    p = p + "%-19s " % d
                    iprint(d, type(getattr(self, d)))
                    j -= 1
                    if j == 0:
                        p = p + "\n"
                        j = nperline

        p = p + "\n\n"
        p = p + self.scandata.show(prefix, nperline)
        return p
Beispiel #10
0
    def highlight(self, actor):
        # outline = vtk.vtkOutlineFilter()
        # print dir(actor)
        # print dir(actor.GetProperty())

        sphere = vtkSphereSource()
        sphere.SetRadius(self.radius * 1.1)
        sphere.SetCenter(actor.GetCenter())
        sphere.SetThetaResolution(self.theta_res)
        sphere.SetPhiResolution(self.phi_res)

        spheremapper = vtkPolyDataMapper()
        spheremapper.SetInputConnection(sphere.GetOutputPort())

        sphereActor = vtkActor()
        sphereActor.SetMapper(spheremapper)
        sphereActor.GetProperty().SetColor((0.0, 0.0, 0.0))
        sphereActor.GetProperty().SetOpacity(0.5)

        # sphereActor.GetProperty().SetRepresentationToWireframe()
        try:
            self.ren.RemoveViewProp(self.sphereActor)
        except Exception as e:
            iprint(e)
        self.ren.AddActor(sphereActor)
        self.sphereActor = sphereActor
        self.Render()
Beispiel #11
0
def ass_X_test(k_b, k_u, k_l, dd_u, dd_l,
                        sigma, sigma_l, sigma_u, dtype = _ctype):
    ''' Just a simpler version of ass_X to locate an error somewhere...
    '''
    k_jm1_b = k_b[...,1:]
    k_j_b = k_b[...,:-1]
    k_jm1_l = k_l[...,1:]
    k_j_u = k_u[...,:-1]
    sigma_jm1_l = sigma_l[...,1:]
    sigma_j_b = sigma[...,:-1]
    sigma_j_u = sigma_u[...,:-1]
    dd_jm1_l = dd_l[...,1:]
    dd_j_u = dd_u[...,:-1]
    
    iprint(dd_j_u, dd_jm1_l)

    #Reflectivites
    r_j_b = refl(k_j_b, k_j_u)
    #print 'r_j_b', r_j_b
    r_jm1_l = refl(k_jm1_l, k_jm1_b) 
    #print 'r_jm1_l', r_jm1_l
    r_j_u = refl(k_j_u, k_jm1_l)
    #print 'r_j_u', r_j_u
    p_jm1_l = np.exp(-1.0J*dd_jm1_l*k_jm1_l)
    p_j_u = np.exp(-1.0J*dd_j_u*k_j_u)
    
    #Defining the X matrix
    X = np.empty((2,2) + k_j_b.shape, dtype = dtype)
    
    X[0,0] = p_jm1_l*r_j_u*p_j_u
    X[0,1] = -(p_jm1_l*r_j_u-p_jm1_l)/p_j_u
    X[1,0] = -((r_j_u-1)*p_j_u)/p_jm1_l
    X[1,1] = r_j_u/(p_jm1_l*p_j_u)
    
    return X
Beispiel #12
0
    def update_data_cols(self, cols, autom=False):
        ''' Update the choices for the different values'''
        iprint(cols)
        self.x_val = cols[0]
        self.det_val = cols[1]
        self.mon_val = cols[2]
        self.error_val = cols[3]
        xval = self.scan.values[self.x_val]
        yvals = [
            self.scan.values[self.det_val],
        ]
        if self.mon_val != 'None':
            yvals.append(self.scan.values[self.mon_val])
        if self.error_val != 'None' and self.error_val != '':
            yvals.append(self.scan.values[self.error_val])
        if autom:
            xval, yvals = automerge(xval, yvals)
        # self.dataset.set_extra_data('det', self.scan.values[self.det_val])
        self.dataset.set_extra_data('det', yvals[0])
        if self.mon_val != 'None':
            # self.dataset.set_extra_data('mon', self.scan.values[self.mon_val])
            self.dataset.set_extra_data('mon', yvals[1])

            if self.error_val != 'None' and self.error_val != '':
                self.dataset.error_raw = yvals[2]
        elif self.error_val != 'None' and self.error_val != '':
            self.dataset.error_raw = yvals[1]

        # self.dataset.x_raw = self.scan.values[self.x_val]
        self.dataset.x_raw = xval
Beispiel #13
0
    def reload(self):
        """Reload the data file

        This routine reloads (reindexes) the datafile"""

        if __verbose__:
            iprint("**** Reloading SpecFile")
        self._loadSpecFile()
Beispiel #14
0
 def lookup_value(self, name):
     '''lookup_value(self, name) --> object
     
     Used to (externally) lookup a value in a database to be inserted in
     local one for this object.
     '''
     iprint('Looking up value')
     return 1
Beispiel #15
0
    def reset(self):
        """Reset the specfile class

        This routine resets the SpecDataFile, as if no scans
        had been read."""

        self.scandata = {}
        if __verbose__:
            iprint("**** SpecFile reset (all scans removed)")
Beispiel #16
0
 def update_domain_view(self):
     domain = self.sample_edit_widget.get_selected_domain_name()
     if domain:
         try:
             domain = self.GetModel().eval_in_model(domain)
         except Exception:
             iprint("Could not load domain ", domain)
         else:
             self.sample_view.build_sample(domain, use_opacity=False)
Beispiel #17
0
    def _loadSpecFile(self):
        if __verbose__:
            iprint("**** Opening specfile %s." % self.filename)

        self.index()
        self.readHeader()
        iprint(self.getStats())

        self.scandata = {}
        return
Beispiel #18
0
 def __init__(self):
     if os.path.exists(config_file):
         try:
             known_materials = json.loads(open(config_file, 'r').read())
         except json.JSONDecodeError:
             iprint("Can't reload material list, file corrupted.")
             known_materials = default_materials
     else:
         known_materials = default_materials
     data = [self.prepare(mi) for mi in known_materials]
     list.__init__(self, data)
Beispiel #19
0
    def get_data_choices(self):
        '''Function to return the data choices
        '''
        try:
            choices = self.scan.cols
        except Exception as e:
            iprint("Could not load the scan cols error: ", e.__str__())
            ShowErrorDialog(
                self.parent,
                "Could not load the scan cols, error:\n%s " % e.__str__())
            choices = []

        return choices
Beispiel #20
0
    def _moveto(self, item):
        """Move to a location in the datafile for scan"""

        if item in self.findex:
            self.file.seek(self.findex[item])
        else:
            # Try re-indexing the file here.
            if __verbose__:
                iprint("**** Re-indexing scan file\n")
            self.index()
            if item in self.findex:
                self.file.seek(self.findex[item])
            else:
                raise Exception("Scan %s is not in datafile ....." % item)
Beispiel #21
0
def test_correlation_function_h05():
    """Test so that the correlation function for h=0.5 matches the analytical solution."""
    eta_r = 1050.
    q_r = np.logspace(-5., 0., 100)
    c_func = grating_diffuse.correlation_function(q_r, 0.5, eta_r, 0.0, 1e-10)
    a = 1 / eta_r
    analytical_func = 2. * a / (a**2 + q_r**2)

    iprint((np.abs((c_func - analytical_func) / c_func).max()))

    if True:
        plt.loglog(q_r, c_func)
        plt.loglog(q_r, analytical_func)
        plt.show()
Beispiel #22
0
 def load_specfile(self, filename):
     self.specfile = spec.SpecDataFile(filename)
     names = list(self.specfile.findex.keys())
     names.sort()
     try:
         sc = self.specfile.scan_commands
         names = ['%s ' % (name, ) + sc[name] for name in names]
     except Exception as e:
         iprint("Could not create full names, error: ", e.__str__())
         ShowErrorDialog(
             self.parent,
             "Could not create full names, error:\n %s" % e.__str__())
         names = ['%s ' % name for name in names]
     self.specfile_name = filename
     self.scan_names = names
     return self.scan_names
Beispiel #23
0
    def __init__(self, **kargs):
        # Setup all the parameters in the class
        for par in self._parameters:
            setattr(self, par, self._parameters[par])
            iscomplex = type(self._parameters[par]) is complex
            # Making the set function
            self._make_set_func(par, iscomplex)
            # Creating the get function
            self._make_get_func(par, iscomplex)

        # Set all parameters given as keyword arguments
        for k in kargs:
            if not k in self._parameters and not k in dir(self):
                iprint('%s is not an parameter in %s so it is ignored' %
                       (k, self.__class__.__name__))
            else:
                setattr(self, k, kargs[k])
Beispiel #24
0
 def update_script(self):
     """Updates the script with new data"""
     old_script = self.GetModelScript()
     if old_script == "":
         self.SetModelScript(self.script_interactor.get_code())
     else:
         try:
             self.SetModelScript(self.script_interactor.update_code(old_script))
         except Exception as e:
             outp = io.StringIO()
             traceback.print_exc(200, outp)
             tbtext = outp.getvalue()
             outp.close()
             iprint("Error updating the script: ")
             iprint(tbtext)
             if self.ShowQuestionDialog('Could not update the script due to syntax issues. Python error: %s\n\n'
                                         'Do you wish to reset the model to the one defined in the user interface?'):
                 self.SetModelScript(self.script_interactor.get_code())
Beispiel #25
0
    def _setcols(self):
        if self.data.shape[0] > 0:
            for i in range(len(self.cols)):
                if len(self.data.shape) == 2:
                    self.scandata.setValue(removeIllegals(self.cols[i]),
                                           self.data[:, i])
                else:
                    self.scandata.setValue(removeIllegals(self.cols[i]),
                                           array([self.data[i]]))

        # Now set the variables into the scan class from the data

            if self.setkeys:
                for i in list(self.scandata.values.keys()):
                    if __verbose__ & 0x02:
                        iprint("oooo Setting variable %s" % i)
                    setattr(self, i, self.scandata.values[i])
                self.values = self.scandata.values
Beispiel #26
0
def test_marginal_distributions_bvn_int():
    """Test so that the marginal distributions of polynomial_coefficentis_bvn_int is as expected"""
    delta_z_slice_int1 = np.linspace(-2.9, 2.9, 200.0)
    delta_z_slice_int2 = 2.9 * np.ones_like(delta_z_slice_int1)
    sigma1 = 2.0
    sigma2 = 1.0
    poly = grating_diffuse.polynomial_cofficents_bvn_int(
        delta_z_slice_int1, delta_z_slice_int2, sigma1, sigma2)
    values = np.polyval(poly, 0.5 * np.ones_like(delta_z_slice_int1))

    ref_values = 0.5 * (1 + erf(delta_z_slice_int1 / np.sqrt(2) / sigma1))

    iprint((np.abs((values - ref_values) / (ref_values)).max()))

    if True:
        plt.plot(delta_z_slice_int1, values)
        plt.plot(delta_z_slice_int1, ref_values)
        plt.show()
Beispiel #27
0
 def set_manip(self, choices):
     '''Sets the manipulations to defualt values as given by
     the choices in the form (x, det, mon, error)
     '''
     iprint(choices)
     self.xCtrl.ChangeValue(choices[0])
     if choices[2] == 'None':
         self.yCtrl.ChangeValue(choices[1])
         if choices[3] == 'None':
             self.errorCtrl.ChangeValue("sqrt(%s)" % (choices[1], ))
         else:
             self.errorCtrl.ChangeValue(choices[3])
     else:
         self.yCtrl.ChangeValue("%s/%s" % (choices[1], choices[2]))
         if choices[3] == 'None':
             self.errorCtrl.ChangeValue(
                 "sqrt(1.0/%s + 1.0/%s)*%s/%s" %
                 (choices[1], choices[2], choices[1], choices[2]))
         else:
             self.errorCtrl.ChangeValue(choices[3])
Beispiel #28
0
def test_calc_fields_single_interface():
    qz = np.linspace(0.0001, 0.5, 500)
    t, r, k_z = grating.calc_fields(
        qz / 2., 1.54, np.array([9e-5, 9e-5, 0], dtype=np.complex128),
        np.array([0.0, 0.0, 0.0]))

    t_theory = 2 * k_z[:, -1] / (k_z[:, 0] + k_z[:, -1])
    r_theory = (k_z[:, -1] - k_z[:, 0]) / (k_z[:, 0] + k_z[:, -1])

    iprint((t_theory - t[:, 0]).max())
    iprint((r_theory - r[:, 1]).max())

    if False:
        plt.subplot(211)
        plt.plot(qz, np.abs(t[:, 0])**2)
        plt.plot(qz, np.abs(t_theory)**2)
        plt.subplot(212)
        plt.semilogy(qz, np.abs(r[:, -1])**2)
        plt.semilogy(np.abs(r_theory)**2)
        plt.show()
Beispiel #29
0
    def setMode(self, mode='concatenate'):
        """Set the modee to deal with multiple scans

        mode : string
           If mode is 'concatenate' then concatenate scans together.
           If mode is 'bin' then bin (numerically the scans together.
        """

        if mode == 'concatenate':
            self.mode = 'concat'
            iprint("**** Multiple scans will be concatenated.")
            return
        elif mode == 'bin':
            self.mode = 'bin'
            iprint("**** Multiple scans will be binned.")
            return
        else:
            raise Exception("Unknown mode %s" % mode)

        return
Beispiel #30
0
 def OnChangeCursorState(self, event):
     """Callback when changing the cursor state between select, orbit, zoom and pan"""
     iprint(self.toolbar)
     if self.toolbar:
         [self.toolbar.ToggleTool(cid, False) for cid in self.cursor_ids]
         self.toolbar.ToggleTool(event.GetId(), True)
         name = self.toolbar.FindById(event.GetId()).GetLabel()
         if self.cursor_mode == 'select':
             self.textActor.VisibilityOff()
             self.sphereActor.VisibilityOff()
             self.Render()
         if name == 'Select':
             self.cursor_mode = 'select'
         elif name == 'Orbit':
             self.cursor_mode = 'orbit'
         elif name == 'Zoom':
             self.cursor_mode = 'zoom'
         elif name == 'Pan':
             self.cursor_mode = 'pan'
         else:
             iprint('VTKView.OnChangeCursorState: Button name ', name, 'is not a known button')