Ejemplo n.º 1
0
def rasd_menu(rasddata, cell = None, bulk_file = None, sur_file = None, f1f2_file = None, E0 = 0.):
    """
    Interactively create RasdList object and inspect/analyze data in it 
    """
    if cell == None:
        ok = False
        while not ok:
            cell = get_flt_list(prompt='Enter unit cell [a,b,c,alpha,beta,gamma,delta1,delta2]')
            if len(cell) != 8:
                print 'invalid unit cell'
            else: ok = True
        
    if bulk_file == None:
        ok = False
        while not ok:
            bulk_file = get_str(prompt='Enter path and\or name of your bulk file (ROD .bul file without header and cell definition)')
            if not os.path.exists(bulk_file):
                print bulk_file+' not found'
            else:
                ok = True
    bulk = []
    f = file(bulk_file,'r')
    data = f.readlines()
    f.close()
    for i in range(len(data)):
        if '#' not in data[i]:
            tmp = str.rsplit(data[i])
            bulk.append([tmp[0],float(tmp[1]),float(tmp[2]),float(tmp[3]),float(tmp[4])])
                
    if sur_file == None:
        ok = False
        while not ok:
            sur_file = get_str(prompt='Enter path and\or name of your surface file (ROD .sur file without header and cell definition)')
            if not os.path.exists(sur_file):
                print sur_file+' not found'
            else:
                ok = True
    surface = []
    f = file(sur_file,'r')
    data = f.readlines()
    f.close()
    for i in range(len(data)):
        if '#' not in data[i]:
            tmp = str.rsplit(data[i])
            surface.append([tmp[0],float(tmp[1]),float(tmp[2]),float(tmp[3]),float(tmp[4]),float(tmp[5])])

    if f1f2_file == None:
        ok = False
        while not ok:
            f1f2_file = get_str(prompt='Enter path and\or name of your f1f2 file (HEPHAESTUS or experimental f1f2 file)')
            if not os.path.exists(f1f2_file):
                print f1f2_file+' not found'
            else:
                ok = True
    f = file(f1f2_file, 'r')
    data = f.readlines()
    f.close()
    f1f2 = num.ndarray((0,3),float)
    for i in range(len(data)):
        if '#' not in data[i]:
            tmp = str.rsplit(data[i])
            f1f2 = num.append(f1f2, [[int(float(tmp[0])),float(tmp[1]),float(tmp[2])]], axis = 0)
    f1f2 = f1f2.transpose()

    if E0 == 0:
        E0 = get_flt(prompt='Enter E0 in eV')

    allrasd = rasd_ana.read_RSD(cell, bulk, surface, database, rasddata, f1f2, E0)
        
    prompt   = 'Select option >'
    ret      = ''

    # make menu
    m = Menu(labels=RASD_LABELS,
                 descr=RASD_DESCR,
                 sort=False, matchidx=True)
    scan_pnt = 0
    norm = True
    
    # loop
    while ret != 'done':
        allrasd.list[scan_pnt] = rasd_ana.RASD_Fourier(allrasd,scan_pnt)
        header   = RASD_HEADER % (str(allrasd.dims),str(scan_pnt),
                                 str(allrasd.list[scan_pnt].AR),str(allrasd.list[scan_pnt].PR),
                                 str(allrasd.list[scan_pnt].e0shift))
        m.header = header
        allrasd.list[scan_pnt].plot(norm = norm, fig = 1)
        ret      = m.prompt(prompt)
        if ret == 'plot_norm':
            norm = get_tf(prompt = 'Plot normalized or not (True/False)', default = norm)
        elif ret == 'setE0shift':
            allrasd.list[scan_pnt].e0shift = get_flt(prompt = 'Enter e0 shift for this scan',
                                                       default = allrasd.list[scan_pnt].e0shift)
            allrasd.list[scan_pnt].E = allrasd.list[scan_pnt].Eorig + allrasd.list[scan_pnt].e0shift
            allrasd.list[scan_pnt].E0 = allrasd.E0 + allrasd.list[scan_pnt].e0shift
        elif ret == 'setPRstart':
            allrasd.list[scan_pnt].PR = get_flt(prompt = 'Enter PR start (0-1)', default = allrasd.list[scan_pnt].PR,
                                                min = 0, max = 1)
        elif ret == 'useInFourier':
            allrasd.list[scan_pnt].use_in_Fourier = get_tf(prompt= 'Use this scan in Fourier synthesis (True/False)?',
                                                           default = allrasd.list[scan_pnt].use_in_Fourier)
        elif ret == 'useInRefine':
            allrasd.list[scan_pnt].use_in_Refine = get_tf(prompt= 'Use this scan for Structure Refinement (True/False)?',
                                                           default = allrasd.list[scan_pnt].use_in_Refine)
        elif ret == 'FourierParams':
            allrasd.ZR = get_int(prompt= 'Atomic number of resonant element', default = allrasd.ZR)
            allrasd.xf = get_flt(prompt= 'number of unit cells along a', default = allrasd.xf)
            allrasd.yf = get_flt(prompt= 'number of unit cells along b', default = allrasd.yf)
            allrasd.zf = get_flt(prompt= 'number of unit cells along c', default = allrasd.zf)
            allrasd.an = get_int(prompt= 'number of datapoints along a', default = allrasd.an)
            allrasd.bn = get_int(prompt= 'number of datapoints along b', default = allrasd.bn)
            allrasd.cn = get_int(prompt= 'number of datapoints along c', default = allrasd.cn)
            allrasd.Plusminus = get_tf(prompt= 'calculate rho(e-) above and below surface', default = allrasd.Plusminus)
        elif ret == 'runFourier':
            allrasd.Fourier = []
            data = []
            for rasd in allrasd.list:
                if rasd.use_in_Fourier:
                    allrasd.Fourier.append([rasd.Q[0],rasd.Q[1],rasd.Q[2],rasd.AR,rasd.PR])
                    data.append(rasd.file)
            if allrasd.Fourier == []: print 'No scans specified for use in Fourier'
            else:
                rasd_ana.Fourier_synthesis(allrasd.Fourier, allrasd.cell, allrasd.ZR,allrasd.xf,allrasd.yf,allrasd.zf,
                                             allrasd.an,allrasd.bn,allrasd.cn,allrasd.Plusminus)
                print 'Scans used for Fourier synthesis: \n'+str(data) 
        elif ret == 'RefinementParams':
            allrasd.natoms = get_int(prompt = 'How many atoms in structure model?', default = allrasd.natoms)
            if allrasd.Rmin == None or len(allrasd.thetamin) != allrasd.natoms:
                allrasd.Rmin = num.zeros((allrasd.natoms,3),float)
                allrasd.Rmax = num.ndarray((0,3),float)
                for i in range(allrasd.natoms):
                    allrasd.Rmax = num.append(allrasd.Rmax, [[allrasd.cell[0],allrasd.cell[1],allrasd.cell[2]]],axis = 0)
                allrasd.thetamin = num.ones((allrasd.natoms),float) *0.05
                allrasd.thetamax = num.ones((allrasd.natoms),float) *0.999
                allrasd.DWmin = num.zeros((allrasd.natoms,6),float)
                for i in range(allrasd.natoms):
                    allrasd.DWmin[i] = [0.001,0.001,0.001,0.,0.,0.]
                allrasd.DWmax = num.zeros((allrasd.natoms,6),float)
                for i in range(allrasd.natoms):
                    allrasd.DWmax[i] = [1.,1.,1.,0.,0.,0.]
            for i in range(allrasd.natoms):
                allrasd.Rmin[i] = get_flt_list(prompt = ('Rmin of atom '+str(i+1)+' [xmin,ymin,zmin] (Angstroem)'), default = allrasd.Rmin[i])
            for i in range(allrasd.natoms):
                allrasd.Rmax[i] = get_flt_list(prompt = ('Rmax of atom '+str(i+1)+' [xmax,ymax,zmax] (Angstroem)'), default = allrasd.Rmax[i])
            for i in range(allrasd.natoms):
                allrasd.thetamin[i] = get_flt(prompt = ('min. occupancy of atom '+str(i+1)), default = allrasd.thetamin[i])
            for i in range(allrasd.natoms):
                allrasd.thetamax[i] = get_flt(prompt = ('max. occupancy of atom '+str(i+1)), default = allrasd.thetamax[i])
            for i in range(allrasd.natoms):
                allrasd.DWmin[i] = get_flt_list(prompt = ('min. DW-factor for atom '+str(i+1)+' [b11,b22,b33,b12,b13,b23]'), default = allrasd.DWmin[i])
            for i in range(allrasd.natoms):
                allrasd.DWmax[i] = get_flt_list(prompt = ('max. DW-factor for atom '+str(i+1)+' [b11,b22,b33,b12,b13,b23]'), default = allrasd.DWmax[i])
            allrasd.Tstart = get_flt(prompt = 'Startimg Temperature for simmulated annealing', default = allrasd.Tstart)
            allrasd.Tend = get_flt(prompt = 'End Temperature for simmulated annealing', default = allrasd.Tend)
            allrasd.cool = get_flt(prompt = 'cooling factor for simmulated annealing (usually 0.7 - 0.95)', default = allrasd.cool, min = 0.1, max = 0.99)
            allrasd.maxrun = get_flt(prompt = 'max. repeats at one Temp.', default = allrasd.maxrun)
            allrasd.MC = get_flt(prompt = 'max fractional parameter change at T = 100', default = allrasd.MC)
            allrasd.RMS_count_max = get_flt(prompt = 'max. annealing (T) steps without improvement', default = allrasd.RMS_count_max)
            allrasd.factor = get_flt(prompt = 'some factor (Boltz. = exp(d(RMS)*factor/T)) in decision process (~1e4 - 1e7)', default = allrasd.factor)
Ejemplo n.º 2
0
def ctr_menu(ctr,
             scans=None,
             I=None,
             Inorm=None,
             Ierr=None,
             corr_params=None,
             scan_type=None):
    """
    Interactively inspect/integrate CtrData

    Parameters:
    -----------
    * ctr is a ctr data object
    * scans is a [list] of scan data objects
    * I, Inorm, Ierr are string tags corresponding to
      the values from the scandata object to used in computing
      structure factors
    * corr_params is a (optional) dictionary of correction parameters
    * scan_type is the type of scan (e.g. 'image')
    
    """
    #if not isinstance(ctr,ctr_data.CtrData):
    #    print "Error CtrData object required"
    #    return
    prompt = 'Select option >'
    ret = ''
    point = 0
    set = []
    npts = len(ctr.L)

    # append new data
    if scans != None:
        ctr.append_scans(scans,
                         I=I,
                         Inorm=Inorm,
                         Ierr=Ierr,
                         corr_params=corr_params,
                         scan_type=scan_type)
        set = range(npts, len(ctr.L))
        point = npts
        npts = len(ctr.L)

    # make menu
    m = Menu(labels=CTR_LABELS, descr=CTR_DESCR, sort=False, matchidx=True)

    # make a plot
    def _ctr_plot(ctr, I=False):
        #pyplot.close(0)
        pyplot.figure(0)
        pyplot.clf()
        if I == False:
            ctr.plot(fig=0, spnt=point)
        else:
            ctr.plot_I(fig=0, spnt=point)

    _ctr_plot(ctr)

    # loop
    while ret != 'done':
        if point in ctr.bad:
            bad_flag = True
        else:
            bad_flag = False
        header = CTR_HEADER % (
            str(npts), str(set), str(point), str(ctr.scan_type[point]),
            str(ctr.labels['I'][point]), str(ctr.labels['Inorm'][point]),
            str(ctr.labels['Ierr'][point]), str(ctr.labels['Ibgr'][point]),
            str(ctr.corr_params[point].get('geom')),
            str(ctr.corr_params[point].get('beam_slits')),
            str(ctr.corr_params[point].get('det_slits')),
            str(ctr.corr_params[point].get('sample')),
            str(ctr.corr_params[point].get('scale')), str(bad_flag),
            ctr.H[point], ctr.K[point], ctr.L[point], ctr.I[point],
            ctr.Ierr[point], ctr.Ibgr[point], ctr.ctot[point], ctr.F[point],
            ctr.Ferr[point])
        m.header = header
        ret = m.prompt(prompt)
        #
        if ret == 'plot':
            _ctr_plot(ctr)
        elif ret == 'iplot':
            _ctr_plot(ctr, I=True)
        elif ret == 'labels':
            (scan, spnt) = ctr.get_scan(point)
            lbls = scan.scalers.keys()
            if scan.image:
                lbls.extend(scan.image.peaks.keys())
            print "Labels: \n", lbls
            Ilbl = get_str(prompt='Enter Intensity lbl',
                           default=ctr.labels['I'][point],
                           valid=lbls)
            Ierrlbl = get_str(prompt='Enter Intensity error lbl',
                              default=ctr.labels['Ierr'][point],
                              valid=lbls)
            Inormlbl = get_str(prompt='Enter Intensity norm lbl',
                               default=ctr.labels['Inorm'][point],
                               valid=lbls)
            Ibgrlbl = get_str(prompt='Enter Intensity background lbl',
                              default=ctr.labels['Ibgr'][point],
                              valid=lbls)
            pp = "Apply to 'p' current point, 's' to set, "
            pp = pp + "'a' to all, 'n' for none"
            app = get_str(prompt=pp, default='p', valid=['p', 'a', 's', 'n'])
            if app == 'p':
                ctr.labels['I'][point] = Ilbl
                ctr.labels['Ierr'][point] = Ierrlbl
                ctr.labels['Inorm'][point] = Inormlbl
                ctr.labels['Ibgr'][point] = Ibgrlbl
                print "Integrate point index %i" % point
                ctr.integrate_point(point)
            elif app == 's':
                for j in set:
                    ctr.labels['I'][j] = Ilbl
                    ctr.labels['Ierr'][j] = Ierrlbl
                    ctr.labels['Inorm'][j] = Inormlbl
                    ctr.labels['Ibgr'][j] = Ibgrlbl
                    print "Integrate point index %i" % j
                    ctr.integrate_point(j)
            elif app == 'a':
                for j in range(npts):
                    ctr.labels['I'][j] = Ilbl
                    ctr.labels['Ierr'][j] = Ierrlbl
                    ctr.labels['Inorm'][j] = Inormlbl
                    ctr.labels['Ibgr'][j] = Ibgrlbl
                    print "Integrate point index %i" % j
                    ctr.integrate_point(j)
            elif app == 'n':
                print "Ignoring updates"
            _ctr_plot(ctr)
        elif ret == 'correction':
            corr_params = {}
            #
            check = get_yn(prompt='Edit geometry', default='y')
            if check == 'yes':
                geom = get_str(prompt='Enter geometry',
                               default=ctr.corr_params[point]['geom'],
                               valid=['psic'])
                corr_params['geom'] = geom
            #
            check = get_yn(prompt='Edit beam slits', default='y')
            if check == 'yes':
                beam_slits = ctr.corr_params[point]['beam_slits']
                if beam_slits == None: beam_slits = {'horz': 1., 'vert': 1.}
                print "Horizontal = total slit width in lab-z,or horizontal scatt plane"
                beam_slits['horz'] = get_flt('Beam horizontal slit (mm)',
                                             default=beam_slits['horz'])
                print "Vertical = total slit width in lab-x,or vertical scatt plane"
                beam_slits['vert'] = get_flt('Beam vertical slit (mm)',
                                             default=beam_slits['vert'])
                corr_params['beam_slits'] = beam_slits
            #
            check = get_yn(prompt='Edit detector slits', default='y')
            if check == 'yes':
                det_slits = ctr.corr_params[point]['det_slits']
                if det_slits == None: det_slits = {'horz': 1., 'vert': 1.}
                print "Horizontal = total slit width in lab-z,or horizontal scatt plane"
                det_slits['horz'] = get_flt('Det horizontal slit (mm)',
                                            default=det_slits['horz'])
                print "Vertical = total slit width in lab-x,or vertical scatt plane"
                det_slits['vert'] = get_flt('Det vertical slit (mm)',
                                            default=det_slits['vert'])
                corr_params['det_slits'] = det_slits
            #
            check = get_yn(prompt='Edit sample shape/size', default='y')
            if check == 'yes':
                sample = ctr.corr_params[point]['sample']
                check2 = get_str(
                    prompt="Sample described by diameter 'd' or polygon 'p'?",
                    default='d',
                    valid=['d', 'p'])
                if check2 == 'd':
                    if type(sample) == types.DictType: sample = 1.
                    sample = get_flt('Sample diameter (mm)', default=sample)
                elif check2 == 'p':
                    xx = "Sample is described by a polygon which is a collection \n"
                    xx = xx + "of [x,y,(z)] points (minimum of three points);\n"
                    xx = xx + "x is lab frame vertical, y is along ki, z is horizontal.\n"
                    xx = xx + "These points need to be specified along with the set of\n"
                    xx = xx + "gonio angles at the time of the polygon determination.\n"
                    xx = xx + "If phi and chi are at the 'flat' values, and the sample is\n"
                    xx = xx + "on the beam center, then z = 0 (and only [x,y] points are needed).\n"
                    print xx
                    sample = {
                        'polygon': [],
                        'angles': {
                            'phi': 0.0,
                            'chi': 0.0
                        }
                    }
                    while 1:
                        xx = "Enter a sample polygon point, '[]' to end"
                        sp = get_flt_list(prompt=xx, default=[])
                        if sp == []:
                            break
                        else:
                            sample['polygon'].append(sp)
                    xx = "Enter gonio angles"
                    sample['angles']['phi'] = get_flt(
                        'phi', default=sample['angles']['phi'])
                    sample['angles']['chi'] = get_flt(
                        'chi', default=sample['angles']['chi'])
                    print 'Sample: ', sample
                corr_params['sample'] = sample
            #
            check = get_yn(prompt='Edit scale', default='y')
            if check == 'yes':
                scale = get_flt(prompt='Enter scale factor',
                                default=ctr.corr_params[point]['scale'])
                corr_params['scale'] = scale
            #
            pp = "Apply to 'p' current point, 's' to set, 'a' to all, 'n' for none"
            app = get_str(prompt=pp, default='p', valid=['p', 'a', 's', 'n'])
            if app == 'p':
                ctr.corr_params[point].update(corr_params)
                print "Integrate point index %i" % point
                ctr.integrate_point(point)
            elif app == 's':
                for j in set:
                    ctr.corr_params[j].update(corr_params)
                    print "Integrate point index %i" % j
                    ctr.integrate_point(j)
            elif app == 'a':
                for j in range(npts):
                    ctr.corr_params[j].update(corr_params)
                    print "Integrate point index %i" % j
                    ctr.integrate_point(j)
            elif app == 'n':
                print "Ignoring updates"
            #
            _ctr_plot(ctr)
        elif ret == 'cplot':
            (scan, spnt) = ctr.get_scan(point)
            corr_params = ctr.corr_params[point]
            corr = ctr_data._get_corr(scan, spnt, corr_params)
            if ctr.scan_type[point] == 'image':
                corr.ctot_stationary(plot=True, fig=2)
        elif ret == 'integrate':
            if ctr.scan_type[point] == 'image':
                (sc_idx, scan_pnt) = ctr.scan_index[point]
                scan = ctr.scan[sc_idx]
                image_menu.image_menu(scan, scan_pnt)
                #
                pp = "Apply / copy integration parameters to\n"
                pp = pp + "(note image max is not copied)\n"
                pp = pp + "'p' current point only, 's' to set, 'a' to all"
                app = get_str(prompt=pp, default='p', valid=['p', 'a', 's'])
                if app == 'p':
                    print "Integrate point index %i" % point
                    ctr.integrate_point(point)
                elif app == 's':
                    roi = scan.image.rois[scan_pnt]
                    rotangle = scan.image.rotangle[scan_pnt]
                    bgrpar = scan.image.bgrpar[scan_pnt]
                    for j in set:
                        print "Integrate point index %i" % j
                        ctr.integrate_point(j,
                                            roi=roi,
                                            rotangle=rotangle,
                                            bgrpar=bgrpar)
                elif app == 'a':
                    roi = scan.image.rois[scan_pnt]
                    rotangle = scan.image.rotangle[scan_pnt]
                    bgrpar = scan.image.bgrpar[scan_pnt]
                    for j in range(npts):
                        print "Integrate point index %i" % j
                        ctr.integrate_point(j,
                                            roi=roi,
                                            rotangle=rotangle,
                                            bgrpar=bgrpar)
            _ctr_plot(ctr)
        elif ret == 'copyint':
            idx = get_int(prompt='Enter point index to copy FROM',
                          default=point,
                          min=0,
                          max=npts - 1)
            if ctr.scan_type[idx] == 'image':
                (sc_idx, scan_pnt) = ctr.scan_index[idx]
                scan = ctr.scan[sc_idx]
                #
                roi = scan.image.rois[scan_pnt]
                rotangle = scan.image.rotangle[scan_pnt]
                bgrpar = scan.image.bgrpar[scan_pnt]
                #
                pp = "Apply / copy integration parameters to\n"
                pp = pp + "(note image max is not copied)\n"
                pp = pp + "'p' current point only, 's' to set, 'a' to all"
                app = get_str(prompt=pp, default='p', valid=['p', 'a', 's'])
                if app == 'p':
                    print "Integrate point index %i" % point
                    ctr.integrate_point(point,
                                        roi=roi,
                                        rotangle=rotangle,
                                        bgrpar=bgrpar)
                elif app == 's':
                    for j in set:
                        print "Integrate point index %i" % j
                        ctr.integrate_point(j,
                                            roi=roi,
                                            rotangle=rotangle,
                                            bgrpar=bgrpar)
                elif app == 'a':
                    for j in range(npts):
                        print "Integrate point index %i" % j
                        ctr.integrate_point(j,
                                            roi=roi,
                                            rotangle=rotangle,
                                            bgrpar=bgrpar)
            _ctr_plot(ctr)
        elif ret == 'pointselect':
            idx = ctr.get_idx()
            point = idx[0]
        elif ret == 'pplot':
            idx = ctr.get_idx()
            point = idx[0]
            ctr.plot_point(idx=point, fig=3, show_int=True)
        elif ret == 'zoomselect':
            set = ctr.get_points()
            point = set[0]
        elif ret == 'selpoint':
            point = get_int(prompt='Enter point',
                            default=point,
                            min=0,
                            max=npts - 1)
        elif ret == 'next':
            if point + 1 < npts:
                point = point + 1
        elif ret == 'previous':
            if point - 1 > -1:
                point = point - 1
        elif ret == 'flag':
            if point in ctr.bad:
                ctr.bad.remove(point)
            else:
                ctr.bad.append(point)
        else:
            pass
Ejemplo n.º 3
0
Archivo: ctr_menu.py Proyecto: FHe/tdl
def ctr_menu(ctr,scans=None,I=None,Inorm=None,Ierr=None,
             corr_params=None,scan_type=None):
    """
    Interactively inspect/integrate CtrData

    Parameters:
    -----------
    * ctr is a ctr data object
    * scans is a [list] of scan data objects
    * I, Inorm, Ierr are string tags corresponding to
      the values from the scandata object to used in computing
      structure factors
    * corr_params is a (optional) dictionary of correction parameters
    * scan_type is the type of scan (e.g. 'image')
    
    """
    #if not isinstance(ctr,ctr_data.CtrData):
    #    print "Error CtrData object required"
    #    return
    prompt   = 'Select option >'
    ret      = ''
    point    = 0
    set      = []
    npts     = len(ctr.L)

    # append new data
    if scans!=None:
        ctr.append_scans(scans,I=I,Inorm=Inorm,Ierr=Ierr,
                         corr_params=corr_params,scan_type=scan_type)
        set   = range(npts,len(ctr.L))
        point = npts
        npts  = len(ctr.L)
        
    # make menu
    m = Menu(labels=CTR_LABELS,descr=CTR_DESCR,sort=False,matchidx=True)

    # make a plot
    def _ctr_plot(ctr,I=False):
        #pyplot.close(0)
        pyplot.figure(0)
        pyplot.clf()
        if I == False:
            ctr.plot(fig=0,spnt=point)
        else:
            ctr.plot_I(fig=0,spnt=point)
    _ctr_plot(ctr)
    
    # loop
    while ret != 'done':
        if point in ctr.bad:
            bad_flag = True
        else:
            bad_flag = False
        header   = CTR_HEADER % (str(npts),str(set),str(point),
                                 str(ctr.scan_type[point]),
                                 str(ctr.labels['I'][point]),
                                 str(ctr.labels['Inorm'][point]),
                                 str(ctr.labels['Ierr'][point]),
                                 str(ctr.labels['Ibgr'][point]),
                                 str(ctr.corr_params[point].get('geom')),
                                 str(ctr.corr_params[point].get('beam_slits')),
                                 str(ctr.corr_params[point].get('det_slits')),
                                 str(ctr.corr_params[point].get('sample')),
                                 str(ctr.corr_params[point].get('scale')),
                                 str(bad_flag),
                                 ctr.H[point],ctr.K[point],ctr.L[point],
                                 ctr.I[point],ctr.Ierr[point],ctr.Ibgr[point],
                                 ctr.ctot[point],ctr.F[point],ctr.Ferr[point])
        m.header = header
        ret      = m.prompt(prompt)
        #
        if ret == 'plot':
            _ctr_plot(ctr)
        elif ret == 'iplot':
            _ctr_plot(ctr,I=True)
        elif ret == 'labels':
            (scan,spnt) = ctr.get_scan(point)
            lbls = scan.scalers.keys()
            if scan.image:
                lbls.extend(scan.image.peaks.keys())
            print "Labels: \n", lbls 
            Ilbl = get_str(prompt='Enter Intensity lbl',
                           default=ctr.labels['I'][point],valid=lbls)
            Ierrlbl = get_str(prompt='Enter Intensity error lbl',
                              default=ctr.labels['Ierr'][point],valid=lbls)
            Inormlbl = get_str(prompt='Enter Intensity norm lbl',
                               default=ctr.labels['Inorm'][point],valid=lbls)
            Ibgrlbl = get_str(prompt='Enter Intensity background lbl',
                               default=ctr.labels['Ibgr'][point],valid=lbls)
            pp = "Apply to 'p' current point, 's' to set, "
            pp = pp + "'a' to all, 'n' for none"
            app = get_str(prompt=pp,default='p',
                          valid=['p','a','s','n'])
            if app == 'p':
                ctr.labels['I'][point]     = Ilbl
                ctr.labels['Ierr'][point]  = Ierrlbl
                ctr.labels['Inorm'][point] = Inormlbl
                ctr.labels['Ibgr'][point]  = Ibgrlbl
                print "Integrate point index %i" % point
                ctr.integrate_point(point)
            elif app == 's':
                for j in set:
                    ctr.labels['I'][j]     = Ilbl
                    ctr.labels['Ierr'][j]  = Ierrlbl
                    ctr.labels['Inorm'][j] = Inormlbl
                    ctr.labels['Ibgr'][j]  = Ibgrlbl
                    print "Integrate point index %i" % j
                    ctr.integrate_point(j)
            elif app == 'a':
                for j in range(npts):
                    ctr.labels['I'][j]     = Ilbl
                    ctr.labels['Ierr'][j]  = Ierrlbl
                    ctr.labels['Inorm'][j] = Inormlbl
                    ctr.labels['Ibgr'][j]  = Ibgrlbl
                    print "Integrate point index %i" % j
                    ctr.integrate_point(j)
            elif app == 'n':
                print "Ignoring updates"
            _ctr_plot(ctr)
        elif ret == 'correction':
            corr_params = {}
            #
            check = get_yn(prompt='Edit geometry',default='y')
            if check=='yes':
                geom = get_str(prompt='Enter geometry',
                               default=ctr.corr_params[point]['geom'],
                               valid=['psic'])
                corr_params['geom'] = geom
            #
            check = get_yn(prompt='Edit beam slits',default='y')
            if check=='yes':
                beam_slits = ctr.corr_params[point]['beam_slits']
                if beam_slits == None: beam_slits = {'horz':1.,'vert':1.}
                print "Horizontal = total slit width in lab-z,or horizontal scatt plane"
                beam_slits['horz'] = get_flt('Beam horizontal slit (mm)',
                                             default=beam_slits['horz'])
                print "Vertical = total slit width in lab-x,or vertical scatt plane"
                beam_slits['vert'] = get_flt('Beam vertical slit (mm)',default=beam_slits['vert'])
                corr_params['beam_slits'] = beam_slits
            #
            check = get_yn(prompt='Edit detector slits',default='y')
            if check=='yes':
                det_slits = ctr.corr_params[point]['det_slits']
                if det_slits == None: det_slits = {'horz':1.,'vert':1.}
                print "Horizontal = total slit width in lab-z,or horizontal scatt plane"
                det_slits['horz'] = get_flt('Det horizontal slit (mm)',
                                            default=det_slits['horz'])
                print "Vertical = total slit width in lab-x,or vertical scatt plane"
                det_slits['vert'] = get_flt('Det vertical slit (mm)',
                                            default=det_slits['vert'])
                corr_params['det_slits'] = det_slits
            #
            check = get_yn(prompt='Edit sample shape/size',default='y')
            if check=='yes':
                sample = ctr.corr_params[point]['sample']
                check2 = get_str(prompt="Sample described by diameter 'd' or polygon 'p'?",
                                 default='d',valid=['d','p'])
                if check2 == 'd':
                    if type(sample) == types.DictType: sample = 1.
                    sample = get_flt('Sample diameter (mm)',default=sample)
                elif check2 == 'p':
                    xx = "Sample is described by a polygon which is a collection \n"
                    xx = xx + "of [x,y,(z)] points (minimum of three points);\n"
                    xx = xx + "x is lab frame vertical, y is along ki, z is horizontal.\n"
                    xx = xx + "These points need to be specified along with the set of\n"
                    xx = xx + "gonio angles at the time of the polygon determination.\n"
                    xx = xx + "If phi and chi are at the 'flat' values, and the sample is\n"
                    xx = xx + "on the beam center, then z = 0 (and only [x,y] points are needed).\n"
                    print xx
                    sample = {'polygon':[],'angles':{'phi':0.0,'chi':0.0}}
                    while 1:
                        xx = "Enter a sample polygon point, '[]' to end"
                        sp = get_flt_list(prompt=xx,default=[])
                        if sp == []:
                            break
                        else:
                            sample['polygon'].append(sp)
                    xx = "Enter gonio angles"
                    sample['angles']['phi'] = get_flt('phi',default=sample['angles']['phi'])
                    sample['angles']['chi'] = get_flt('chi',default=sample['angles']['chi'])
                    print 'Sample: ', sample
                corr_params['sample'] = sample
            #
            check = get_yn(prompt='Edit scale',default='y')
            if check=='yes':
                scale = get_flt(prompt='Enter scale factor',default=ctr.corr_params[point]['scale'])
                corr_params['scale'] = scale
            #
            pp = "Apply to 'p' current point, 's' to set, 'a' to all, 'n' for none"
            app = get_str(prompt=pp, default='p',
                          valid=['p','a','s','n'])
            if app == 'p':
                ctr.corr_params[point].update(corr_params)
                print "Integrate point index %i" % point
                ctr.integrate_point(point)
            elif app == 's':
                for j in set:
                    ctr.corr_params[j].update(corr_params)
                    print "Integrate point index %i" % j
                    ctr.integrate_point(j)
            elif app == 'a':
                for j in range(npts):
                    ctr.corr_params[j].update(corr_params)
                    print "Integrate point index %i" % j
                    ctr.integrate_point(j)
            elif app == 'n':
                print "Ignoring updates"
            #
            _ctr_plot(ctr)
        elif ret == 'cplot':
            (scan,spnt) = ctr.get_scan(point)
            corr_params = ctr.corr_params[point]
            corr = ctr_data._get_corr(scan,spnt,corr_params)
            if ctr.scan_type[point] == 'image':
                corr.ctot_stationary(plot=True,fig=2)
        elif ret == 'integrate':
            if ctr.scan_type[point] == 'image':
                (sc_idx,scan_pnt) = ctr.scan_index[point]
                scan = ctr.scan[sc_idx]
                image_menu.image_menu(scan,scan_pnt)
                #
                pp = "Apply / copy integration parameters to\n"
                pp = pp + "(note image max is not copied)\n"
                pp = pp + "'p' current point only, 's' to set, 'a' to all"
                app = get_str(prompt=pp,
                              default='p',valid=['p','a','s'])
                if app == 'p':
                    print "Integrate point index %i" % point
                    ctr.integrate_point(point)
                elif app == 's':
                    roi      = scan.image.rois[scan_pnt]
                    rotangle = scan.image.rotangle[scan_pnt]
                    bgrpar   = scan.image.bgrpar[scan_pnt]
                    for j in set:
                        print "Integrate point index %i" % j
                        ctr.integrate_point(j,roi=roi,rotangle=rotangle,bgrpar=bgrpar)
                elif app == 'a':
                    roi      = scan.image.rois[scan_pnt]
                    rotangle = scan.image.rotangle[scan_pnt]
                    bgrpar   = scan.image.bgrpar[scan_pnt]
                    for j in range(npts):
                        print "Integrate point index %i" % j
                        ctr.integrate_point(j,roi=roi,rotangle=rotangle,bgrpar=bgrpar)
            _ctr_plot(ctr)
        elif ret == 'copyint':
            idx = get_int(prompt='Enter point index to copy FROM',
                          default=point,min=0,max = npts-1)
            if ctr.scan_type[idx] == 'image':
                (sc_idx,scan_pnt) = ctr.scan_index[idx]
                scan = ctr.scan[sc_idx]
                #
                roi      = scan.image.rois[scan_pnt]
                rotangle = scan.image.rotangle[scan_pnt]
                bgrpar   = scan.image.bgrpar[scan_pnt]
                #
                pp = "Apply / copy integration parameters to\n"
                pp = pp + "(note image max is not copied)\n"
                pp = pp + "'p' current point only, 's' to set, 'a' to all"
                app = get_str(prompt=pp,
                              default='p',valid=['p','a','s'])
                if app == 'p':
                    print "Integrate point index %i" % point
                    ctr.integrate_point(point,roi=roi,rotangle=rotangle,bgrpar=bgrpar)
                elif app == 's':
                    for j in set:
                        print "Integrate point index %i" % j
                        ctr.integrate_point(j,roi=roi,rotangle=rotangle,bgrpar=bgrpar)
                elif app == 'a':
                    for j in range(npts):
                        print "Integrate point index %i" % j
                        ctr.integrate_point(j,roi=roi,rotangle=rotangle,bgrpar=bgrpar)
            _ctr_plot(ctr)
        elif ret == 'pointselect':
            idx = ctr.get_idx()
            point = idx[0]
        elif ret == 'pplot':
            idx = ctr.get_idx()
            point = idx[0]
            ctr.plot_point(idx=point,fig=3,show_int=True)
        elif ret == 'zoomselect':
            set = ctr.get_points()
            point = set[0]
        elif ret == 'selpoint':
            point = get_int(prompt='Enter point',
                            default=point,min=0,max = npts-1)
        elif ret == 'next':
            if point + 1 < npts: 
                point = point + 1
        elif ret == 'previous':
            if point - 1 > -1: 
                point = point - 1
        elif ret == 'flag':
            if point in ctr.bad:
                ctr.bad.remove(point)
            else:
                ctr.bad.append(point)
        else:
            pass
Ejemplo n.º 4
0
def rasd_menu(rasddata,
              cell=None,
              bulk_file=None,
              sur_file=None,
              f1f2_file=None,
              E0=0.):
    """
    Interactively create RasdList object and inspect/analyze data in it 
    """
    if cell == None:
        ok = False
        while not ok:
            cell = get_flt_list(
                prompt='Enter unit cell [a,b,c,alpha,beta,gamma,delta1,delta2]'
            )
            if len(cell) != 8:
                print 'invalid unit cell'
            else:
                ok = True

    if bulk_file == None:
        ok = False
        while not ok:
            bulk_file = get_str(
                prompt=
                'Enter path and\or name of your bulk file (ROD .bul file without header and cell definition)'
            )
            if not os.path.exists(bulk_file):
                print bulk_file + ' not found'
            else:
                ok = True
    bulk = []
    f = file(bulk_file, 'r')
    data = f.readlines()
    f.close()
    for i in range(len(data)):
        if '#' not in data[i]:
            tmp = str.rsplit(data[i])
            bulk.append([
                tmp[0],
                float(tmp[1]),
                float(tmp[2]),
                float(tmp[3]),
                float(tmp[4])
            ])

    if sur_file == None:
        ok = False
        while not ok:
            sur_file = get_str(
                prompt=
                'Enter path and\or name of your surface file (ROD .sur file without header and cell definition)'
            )
            if not os.path.exists(sur_file):
                print sur_file + ' not found'
            else:
                ok = True
    surface = []
    f = file(sur_file, 'r')
    data = f.readlines()
    f.close()
    for i in range(len(data)):
        if '#' not in data[i]:
            tmp = str.rsplit(data[i])
            surface.append([
                tmp[0],
                float(tmp[1]),
                float(tmp[2]),
                float(tmp[3]),
                float(tmp[4]),
                float(tmp[5])
            ])

    if f1f2_file == None:
        ok = False
        while not ok:
            f1f2_file = get_str(
                prompt=
                'Enter path and\or name of your f1f2 file (HEPHAESTUS or experimental f1f2 file)'
            )
            if not os.path.exists(f1f2_file):
                print f1f2_file + ' not found'
            else:
                ok = True
    f = file(f1f2_file, 'r')
    data = f.readlines()
    f.close()
    f1f2 = num.ndarray((0, 3), float)
    for i in range(len(data)):
        if '#' not in data[i]:
            tmp = str.rsplit(data[i])
            f1f2 = num.append(
                f1f2, [[int(float(tmp[0])),
                        float(tmp[1]),
                        float(tmp[2])]],
                axis=0)
    f1f2 = f1f2.transpose()

    if E0 == 0:
        E0 = get_flt(prompt='Enter E0 in eV')

    allrasd = rasd_ana.read_RSD(cell, bulk, surface, database, rasddata, f1f2,
                                E0)

    prompt = 'Select option >'
    ret = ''

    # make menu
    m = Menu(labels=RASD_LABELS, descr=RASD_DESCR, sort=False, matchidx=True)
    scan_pnt = 0
    norm = True

    # loop
    while ret != 'done':
        allrasd.list[scan_pnt] = rasd_ana.RASD_Fourier(allrasd, scan_pnt)
        header = RASD_HEADER % (str(
            allrasd.dims), str(scan_pnt), str(
                allrasd.list[scan_pnt].AR), str(allrasd.list[scan_pnt].PR),
                                str(allrasd.list[scan_pnt].e0shift))
        m.header = header
        allrasd.list[scan_pnt].plot(norm=norm, fig=1)
        ret = m.prompt(prompt)
        if ret == 'plot_norm':
            norm = get_tf(prompt='Plot normalized or not (True/False)',
                          default=norm)
        elif ret == 'setE0shift':
            allrasd.list[scan_pnt].e0shift = get_flt(
                prompt='Enter e0 shift for this scan',
                default=allrasd.list[scan_pnt].e0shift)
            allrasd.list[scan_pnt].E = allrasd.list[
                scan_pnt].Eorig + allrasd.list[scan_pnt].e0shift
            allrasd.list[
                scan_pnt].E0 = allrasd.E0 + allrasd.list[scan_pnt].e0shift
        elif ret == 'setPRstart':
            allrasd.list[scan_pnt].PR = get_flt(
                prompt='Enter PR start (0-1)',
                default=allrasd.list[scan_pnt].PR,
                min=0,
                max=1)
        elif ret == 'useInFourier':
            allrasd.list[scan_pnt].use_in_Fourier = get_tf(
                prompt='Use this scan in Fourier synthesis (True/False)?',
                default=allrasd.list[scan_pnt].use_in_Fourier)
        elif ret == 'useInRefine':
            allrasd.list[scan_pnt].use_in_Refine = get_tf(
                prompt='Use this scan for Structure Refinement (True/False)?',
                default=allrasd.list[scan_pnt].use_in_Refine)
        elif ret == 'FourierParams':
            allrasd.ZR = get_int(prompt='Atomic number of resonant element',
                                 default=allrasd.ZR)
            allrasd.xf = get_flt(prompt='number of unit cells along a',
                                 default=allrasd.xf)
            allrasd.yf = get_flt(prompt='number of unit cells along b',
                                 default=allrasd.yf)
            allrasd.zf = get_flt(prompt='number of unit cells along c',
                                 default=allrasd.zf)
            allrasd.an = get_int(prompt='number of datapoints along a',
                                 default=allrasd.an)
            allrasd.bn = get_int(prompt='number of datapoints along b',
                                 default=allrasd.bn)
            allrasd.cn = get_int(prompt='number of datapoints along c',
                                 default=allrasd.cn)
            allrasd.Plusminus = get_tf(
                prompt='calculate rho(e-) above and below surface',
                default=allrasd.Plusminus)
        elif ret == 'runFourier':
            allrasd.Fourier = []
            data = []
            for rasd in allrasd.list:
                if rasd.use_in_Fourier:
                    allrasd.Fourier.append(
                        [rasd.Q[0], rasd.Q[1], rasd.Q[2], rasd.AR, rasd.PR])
                    data.append(rasd.file)
            if allrasd.Fourier == []:
                print 'No scans specified for use in Fourier'
            else:
                rasd_ana.Fourier_synthesis(allrasd.Fourier, allrasd.cell,
                                           allrasd.ZR, allrasd.xf, allrasd.yf,
                                           allrasd.zf, allrasd.an, allrasd.bn,
                                           allrasd.cn, allrasd.Plusminus)
                print 'Scans used for Fourier synthesis: \n' + str(data)
        elif ret == 'RefinementParams':
            allrasd.natoms = get_int(
                prompt='How many atoms in structure model?',
                default=allrasd.natoms)
            if allrasd.Rmin == None or len(allrasd.thetamin) != allrasd.natoms:
                allrasd.Rmin = num.zeros((allrasd.natoms, 3), float)
                allrasd.Rmax = num.ndarray((0, 3), float)
                for i in range(allrasd.natoms):
                    allrasd.Rmax = num.append(
                        allrasd.Rmax,
                        [[allrasd.cell[0], allrasd.cell[1], allrasd.cell[2]]],
                        axis=0)
                allrasd.thetamin = num.ones((allrasd.natoms), float) * 0.05
                allrasd.thetamax = num.ones((allrasd.natoms), float) * 0.999
                allrasd.DWmin = num.zeros((allrasd.natoms, 6), float)
                for i in range(allrasd.natoms):
                    allrasd.DWmin[i] = [0.001, 0.001, 0.001, 0., 0., 0.]
                allrasd.DWmax = num.zeros((allrasd.natoms, 6), float)
                for i in range(allrasd.natoms):
                    allrasd.DWmax[i] = [1., 1., 1., 0., 0., 0.]
            for i in range(allrasd.natoms):
                allrasd.Rmin[i] = get_flt_list(
                    prompt=('Rmin of atom ' + str(i + 1) +
                            ' [xmin,ymin,zmin] (Angstroem)'),
                    default=allrasd.Rmin[i])
            for i in range(allrasd.natoms):
                allrasd.Rmax[i] = get_flt_list(
                    prompt=('Rmax of atom ' + str(i + 1) +
                            ' [xmax,ymax,zmax] (Angstroem)'),
                    default=allrasd.Rmax[i])
            for i in range(allrasd.natoms):
                allrasd.thetamin[i] = get_flt(
                    prompt=('min. occupancy of atom ' + str(i + 1)),
                    default=allrasd.thetamin[i])
            for i in range(allrasd.natoms):
                allrasd.thetamax[i] = get_flt(
                    prompt=('max. occupancy of atom ' + str(i + 1)),
                    default=allrasd.thetamax[i])
            for i in range(allrasd.natoms):
                allrasd.DWmin[i] = get_flt_list(
                    prompt=('min. DW-factor for atom ' + str(i + 1) +
                            ' [b11,b22,b33,b12,b13,b23]'),
                    default=allrasd.DWmin[i])
            for i in range(allrasd.natoms):
                allrasd.DWmax[i] = get_flt_list(
                    prompt=('max. DW-factor for atom ' + str(i + 1) +
                            ' [b11,b22,b33,b12,b13,b23]'),
                    default=allrasd.DWmax[i])
            allrasd.Tstart = get_flt(
                prompt='Startimg Temperature for simmulated annealing',
                default=allrasd.Tstart)
            allrasd.Tend = get_flt(
                prompt='End Temperature for simmulated annealing',
                default=allrasd.Tend)
            allrasd.cool = get_flt(
                prompt=
                'cooling factor for simmulated annealing (usually 0.7 - 0.95)',
                default=allrasd.cool,
                min=0.1,
                max=0.99)
            allrasd.maxrun = get_flt(prompt='max. repeats at one Temp.',
                                     default=allrasd.maxrun)
            allrasd.MC = get_flt(
                prompt='max fractional parameter change at T = 100',
                default=allrasd.MC)
            allrasd.RMS_count_max = get_flt(
                prompt='max. annealing (T) steps without improvement',
                default=allrasd.RMS_count_max)
            allrasd.factor = get_flt(
                prompt=
                'some factor (Boltz. = exp(d(RMS)*factor/T)) in decision process (~1e4 - 1e7)',
                default=allrasd.factor)
        elif ret == 'runRefine':
            if allrasd.Rmin == None:
                print 'Please define simmulated annealing parameters first'
            else:
                allrasd.reflist = []
                for rasd in allrasd.list:
                    if rasd.use_in_Refine:
                        allrasd.reflist.append(rasd)
                if allrasd.reflist == []:
                    print 'No scans specified for use in refinement'
                else:
                    rasd_ana.simulated_annealing(allrasd)
        elif ret == 'select':
            scan_pnt = get_int(prompt='Enter scan number',
                               default=scan_pnt,
                               min=0,
                               max=allrasd.dims - 1)
        elif ret == 'next':
            if scan_pnt + 1 < allrasd.dims:
                scan_pnt = scan_pnt + 1
        elif ret == 'previous':
            if scan_pnt - 1 > -1:
                scan_pnt = scan_pnt - 1
        else:
            pass