Exemple #1
0
    def detect_scenes(self):
        if (self.hash_diffs):
            # Initalize Scenes List
            self.scenes = []

            # Initialize Scene
            scene = [self.image_list[0]]

            # Determine Scenes
            for curr, diff in enumerate(self.hash_diffs, 1):
                # End Scene And Append To List
                if ((diff >= self.scene_threshold) and
                    (time_diff(self.image_list[curr - 1],
                               self.image_list[curr]) > self.del_threshold)):
                    self.scenes.append(scene)
                    scene = [self.image_list[curr]]
                else:
                    # Append Image To Scene
                    if (not (self.image_list[curr] in scene)):
                        scene.append(self.image_list[curr])

            # Append Final Scene
            if (scene):
                self.scenes.append(scene)
        else:
            util.perror("spectra: No image differences found to process")
Exemple #2
0
    def detect_duplicates(self):
        if (self.hash_diffs):
            # Initialize Duplicates List
            self.duplicates = []

            # Initialize Group List
            duplicate_group = []

            # Determine Duplicates
            for curr, diff in enumerate(self.hash_diffs, 0):
                # Add Image Pair To Duplicate Group
                if (diff <= self.dupli_threshold):
                    if (not (self.image_list[curr] in duplicate_group)):
                        duplicate_group.append(self.image_list[curr])
                    if (not (self.image_list[curr + 1] in duplicate_group)):
                        duplicate_group.append(self.image_list[curr + 1])
                # Append Duplicate Group To List
                elif (len(duplicate_group) > 1):
                    self.duplicates.append(duplicate_group)
                    duplicate_group = []

            # Append Final Duplicate Group
            if (len(duplicate_group) > 1):
                self.duplicates.append(duplicate_group)
        else:
            util.perror("spectra: No image differences found to process")
Exemple #3
0
    def collect_directory(self):
        # Initialize Process Counter
        curr = 0

        # Initialize Image Paths List
        self.image_list = []

        # Congregate Image Files
        for path, subdirs, files in os.walk(str(self.image_path)):
            for file in files:
                # Select Files With Supported File Types
                if (file.endswith((".jpg", ".jpeg", ".png", ".tiff", ".JPG",
                                   ".JPEG", ".PNG", ".TIFF"))):
                    # Create Local Image Data Map
                    image_data = {
                        'dir': util.absolute(path),
                        'name': file,
                        'path': util.form_path([path, file])
                    }

                    # Move File To Opened Path
                    if (self.image_path != image_data['dir']):
                        util.move(
                            image_data['path'],
                            util.absolute(
                                util.form_path(
                                    [self.image_path, image_data['name']])))

                    # Add File To Image List
                    self.image_list.append(
                        util.form_path([self.image_path, image_data['name']]))

                    # Update Prompt
                    print("\rLoaded {} Images - {}".format(
                        curr, self.image_path),
                          end="")
                    curr += 1

        # Delete Empty Directories
        for file in os.listdir(str(self.image_path)):
            # Create Normalized Path
            dir_path = util.form_path([self.image_path, file])

            # Check Directory Existence
            if (util.exists(dir_path)):
                try:
                    # Remove Empty Directory
                    os.rmdir(dir_path)
                except OSError:
                    pass

        # Update Prompt
        print("\rLoaded All Images - {}".format(self.image_path))

        # Verify Image List Length
        if (not (self.image_list)):
            util.perror("spectra: No images found")

        # Sort Image Paths in Lexicographical Order
        self.image_list.sort()
Exemple #4
0
    def organize_directory(self):
        if (self.scenes):
            # Iterate Over Scenes List
            for curr, scene in enumerate(self.scenes, 1):
                # Create Scene Folder
                util.mkdir(
                    util.form_path([self.image_path,
                                    SCENE.format(curr)]))

                # Move Images To Scene Folder
                for image in scene:
                    try:
                        # Generate Source and Destination Paths
                        src = util.absolute(image)
                        dst = util.normalize(
                            util.form_path([
                                util.dirname(image),
                                SCENE.format(curr),
                                util.basename(image)
                            ]))

                        # Move Images To Scene Folder
                        util.move(src, dst)
                    except FileNotFoundError:
                        pass

            # Update Prompt
            print("Organized All Images             ")
        else:
            util.perror("spectra: No scenes found to analyze")
Exemple #5
0
def check_lim(lim_ens, chain, lim_basy, lim_easy, lim_bseq, lim_eseq):
    '''check struct_ncs_dom_lim
    '''

    tab = 'struct_ncs_dom_lim'
    for i, x in enumerate(lim_ens):  #
        ch1, ch2, ns1, ns2 = lim_basy[i], lim_easy[i], lim_bseq[i], lim_eseq[i]
        if ch1 != ch2:
            util.perror(
                'Warning: two chainID (%s & %s) are not the same. look at row %2d in %s.'
                % (ch1, ch2, i + 1, tab))

        if ch1 not in list(chain.keys()):
            util.perror(
                'Warning: chainID (%s) not in coordinate. look at row %2d in %s.'
                % (ch1, i + 1, tab))

        if ((ch1 in list(chain.keys()) and int(ns1) not in chain[ch1])):
            util.perror(
                'Warning: residue number (%s_%s) not in coordinate. look at row %2d in %s.'
                % (ch1, ns1, i + 1, tab))

        if ((ch2 in list(chain.keys()) and int(ns2) not in chain[ch2])):
            util.perror(
                'Warning: residue number (%s_%s) not in coordinate. look at row %2d in %s.'
                % (ch2, ns2, i + 1, tab))
Exemple #6
0
def parse(args):
    # Verify Argument List Length
    if (util.empty(args)):
        util.perror("spectra: No arguments found")
    # Verify Directory Existence
    elif (not (util.exists(args[0]))):
        util.perror("spectra: Invalid image path")
    # Verify Argument Count
    elif ((len(args) - 1) % 2):
        util.perror("spectra: Invalid argument format")

    # Initialize Formatted Arguments List
    form_args = []

    # Set Directory Argument
    form_args.append(args[0])

    # Check Arguments For Supported Flags
    for FLAG in SPECTRA_FLAGS:
        # Set Blur Sensitivity Argument
        if (FLAG in args):
            try:
                # Get Threshold Value
                threshold = int(args[args.index(FLAG) + 1])

                # Range Fix Threshold
                if (not (threshold is None)):
                    if (threshold < 0):
                        threshold = 0
                    elif (threshold > 100):
                        threshold = 100
            except ValueError:
                util.perror("spectra: Unexpected argument data type")
            except:
                util.perror(
                    "spectra: Fatal error while parsing input arguments")

            # Modify Threshold
            if (FLAG == SCENE_SENSITIVITY):
                threshold = 100 - threshold

            # Add As Formatted Argument
            form_args.append(threshold)
        else:
            # Append Empty Argument
            form_args.append(None)

    # Return Formatted Arguments List
    return (form_args)
Exemple #7
0
def log_from_shelx(shelx_log, dic):
    '''parse stat from the log of shelx
    '''

    if util.check_file(100, shelx_log)==0 :
        util.perror('Error: SHELX failed!')
        return

    dic['prog']='SHELX'
    
    fp = open(shelx_log, 'r')
    for x in fp:
        if ' R1 = ' in x and 'unique reflections' in x:
            t=x.split('=',1)[1].split()
            dic['rfact'], dic['nref'] = t[0], t[2]
            
    fp.close()
Exemple #8
0
def html_table_content(fw, idd, y, url, maphtml):
    '''Write a row in the table of HTML.
    idd: number, y: resid, id, rho, dcc, biso, occ
    '''
    warn = ' . '

    if float(y[2]) < -9.0:
        t = 'Warning: resid=%s_%s: No real_spaceR calculated (maybe 0 occupancy)\n' % (
            y[0], y[1])
        util.perror(t)
    elif ((float(y[2]) < 0.7 and float(y[3]) > 0.4) or float(y[2]) < 0.5
          or float(y[3]) > 0.5):
        t = 'Warning: resid=%s_%s: bad real_spaceR (%s) or density correlation (%s)\n' % (
            y[0], y[1], y[3], y[2])
        config.ERRLOG.append(t)
        warn = ' ! '

    ss = ' '
    if len(y) < 4: return
    for z in y:
        if ((float(y[2]) < 0.7 and float(y[3]) > 0.4) or float(y[2]) < 0.5
                or float(y[3]) > 0.5):
            ss = ss + '<td><font color="red">%s</font></td> ' % z
        else:
            ss = ss + '<td>%s</td>' % z

    if idd == 0:
        map1 = '<A TARGET="_self" HREF="%s%s">view map</A>' % (url, maphtml)
        ss = ss + '<td>%s</td>' % map1
    else:
        ss = ss + '<td> </td> '

    all = '<tr>' + ss + '</tr>\n'
    fw.write(all)

    return warn
Exemple #9
0
def model_stat(file,logfile, dic):
    ''' parse data from the output of cns (model_stats)'''

    dic['prog']='CNS'
    if util.check_file(100, file) :
        fp = open(file, 'r')
    elif util.check_file(100, logfile) :
        fp = open(logfile, 'r')
    else:    
        util.perror('Error: CNS failed!')
        return


    for x in fp:
        if 'resolution range:' in x[:18] :
            t=x.split(':')[1].split()
            dic['resl'], dic['resh'] = t[0], t[2]
            
        elif ' after B-factor and/or bulk solvent correction  r=' in x :
            t=x.split('r=',1)[1].split()
            dic['rfact'], dic['rfree'] = t[0], t[2]
            
        elif '>>> bulk solvent: density level=' in x :
            t=x.split('level=',1)[1].split()
            dic['k_sol'], dic['b_sol'] = t[0], t[3]
            
        elif 'total number of reflections used: ' in x :
            t=x.split('used:',1)[1].split()
            dic['nref'], dic['comp'] = t[0], t[2]
            
        elif 'number of reflections in test set:' in x :
            t=x.split('set:',1)[1].split()
            dic['nfree'], dic['pfree'] = t[0], t[2]


#below from stat.log

        elif ' low_res= ' in x :
            dic['resl']=x.split('low_res=')[1].strip().split(';')[0]

        elif ' high_res= ' in x :
            dic['resh']=x.split('high_res=')[1].strip().split(';')[0]

        elif ' REFLection> NREFlection= ' in x :
            dic['nref']=x.split('NREFlection=')[1].strip()

        elif 'best sol_k = ' in x and '.' in x[12:20]:
            t=x.split('=',1)[1].strip()
            dic['k_sol'] = t

        elif 'best sol_b = ' in x and '.' in x[12:20]:  
            t=x.split('=',1)[1].strip()
            dic['b_sol'] = t

        elif 'Overall R-value for test set:' in x :
            t=x.split(':',1)[1]
            dic['rfree'] = t.strip()
            
        elif 'Overall R-value for working set:' in x :
            t=x.split(':',1)[1]
            dic['rfact'] = t.strip()
            
    if '?' in dic['rfact'] : util.perror('Error: CNS failed!')        
    fp.close()
Exemple #10
0
def map_around_ligand(fw_itool, dic, mapfile, pdb, dcc, ch_lig, url):
    '''mapfile: the map in cell; pdb: a list (non-poly); dcc: a list of list;
    ch_lig: a dict for ligand {'ch': [n1,n2 ..]}; url: the url for html
    '''

    if (not ch_lig) or (not dcc): return

    cif1 = '''
loop_
_dcc_ligand.id
_dcc_ligand.residue_name
_dcc_ligand.chain_id
_dcc_ligand.dcc_correlation 
_dcc_ligand.real_space_R
_dcc_ligand.Biso_mean 
_dcc_ligand.occupancy_mean
_dcc_ligand.warning
_dcc_ligand.file_name_map_html
_dcc_ligand.file_name_pdb
_dcc_ligand.file_name_map
_dcc_ligand.file_name_jmol
_dcc_ligand.full_map_sigma
_dcc_ligand.sub_map_sigma
'''

    if not dic['sdsc_map']:
        fw_itool.write(cif1)
        html_table = mapfile + '_lig.html'
        fw = open(html_table, 'w')
        html_table_head(fw, 'Ligands', 1)

    min, max, mean, sigma = map_info(mapfile)
    cont = {
        '0.5': 0.5,
        '0.7': 0.7,
        '1.0': 1.0,
        '1.5': 1.5,
        '2.0': 2.0
    }  #contour 4 map in asu.
    cont1 = {
        '0.5': 0.5,
        '0.7': 0.7,
        '1.0': 1.0,
        '1.5': 1.5,
        '2.0': 2.0
    }  #contour 4 sub map.
    contlist = ['0.5', '0.7', '1.0', '1.5', '2.0']
    lig_sdsc, level_sdsc, jmol_sdsc = [], [], []

    nlig, ncov = 0, 0
    for k, v in ch_lig.items():  #k: chainID; v: a list of residue number

        nres_list = isolate_connect_ligand(pdb, k, v)
        ligid = 0
        for ii, x in enumerate(nres_list):

            pep = get_table_value(pdb, k, x,
                                  dcc)  #look through dcc table natom>=2

            if not pep: continue

            if dic['cif']:
                idd, natom, ligpdb = get_subcif(dic, k, x)
            else:
                idd = pep[0][1]  #ligid_alt_chid_resn
                natom, ligpdb = get_subpdb(pdb, k, x, idd)

            if natom < 2: continue

            mapout = cut_map_around_xyz(mapfile, ligpdb, idd)
            min1, max1, mean1, sigma1 = map_info(mapout)  #for
            print('%s: natom=%d: FullMap-sigma=%s: LigMap-sigma=%s' %
                  (idd, natom, sigma, sigma1))
            if len(x) > 1:  # exist of covelently bonded ligands
                ncov = ncov + 1
                s1 = []
                for z in pep:
                    s1.append(z[1])
                ss = '","'.join(s1)

                sss = ' {"id":"composite_%d","ligands":["' % ncov + ss + '"]},'
            else:
                sss = ' {"id":"' + pep[0][1] + '","ligands":["' + pep[0][
                    1] + '"]},'

            lig_sdsc.append([sss])
            scale = 1.0
            if (float(sigma1) > 0):
                scale = float(sigma) / float(sigma1)
                for z in list(cont.keys()):
                    cont1[z] = cont[z] * scale
            else:
                util.perror(
                    'Warning: Negative sigma scale, possible no map cut. Check needed.'
                )

            if dic['sdsc_map']:
                level, jmol = gen_ligmap_sdsc(idd, contlist, cont1, cont)
                level_sdsc.append(level)
                jmol_sdsc.append(jmol)
                continue

            maphtml = get_html4jmol(idd, ligpdb, mapout, cont1)

            ligid = ligid + 1
            filename = ' %s.html  %s.pdb  %s_cut.map %s_com %s %s' % (
                idd, idd, idd, idd, sigma, sigma1)
            if dic['cif']:
                filename = ' %s.html  %s.cif  %s_cut.map %s_com %s %s' % (
                    idd, idd, idd, idd, sigma, sigma1)

            for i, y in enumerate(pep):
                warn = html_table_content(fw, i, y, url, maphtml)
                ss = '%d ' % ligid + ' '.join(y) + warn + filename + '\n'
                fw_itool.write('%s' % ss)
                nlig = nlig + 1

    if not dic['sdsc_map'] and nlig == 0:
        fw_itool.write('? ? ? ? ? ? ? ? ? ? ? ? ? ? \n')

    if dic['sdsc_map'] > 0:
        fw = open('ERF_table.json', 'w')
        if len(level_sdsc) <= 0:
            fw.close()
            return
        fw.write('{\n  "components":[\n')
        write_sdsc_map(fw, lig_sdsc)
        fw.write('  ],\n')

        fw.write('\n  "ligmap":[\n')
        write_sdsc_map(fw, level_sdsc)
        fw.write('  ],\n')

        fw.write('\n  "contour_level":[\n')
        write_sdsc_map(fw, jmol_sdsc)
        fw.write('  ]\n}\n')

        fw.close()

    else:
        fw.write('</TABLE>\n')
        fw.close()
Exemple #11
0
def cut_map_around_ligand_peptide(dccfile, dic, mapfile_in, xyzfile_in):
    '''It generate a complete set for ligand (map, html, jmol).
    dccfile: the density file by dcc.
    dic: a directory to hold all the file for webpage (url below).
    mapfile_in: a input map file.
    xyzfile_in: a input coordinate file.
    '''

    print('Cutting the density maps for ligands/peptide')

    tmpxyz = xyzfile_in
    if util.is_cif(xyzfile_in): tmpxyz = cif.cif2pdb(xyzfile_in)
    pdbfile = os.path.basename(dic['pdbfile']) + '_new'
    if pdbfile != tmpxyz: shutil.copy(tmpxyz, pdbfile)

    mapfile = os.path.basename(dic['pdbfile']) + '_2fofc.map'
    if dic['ligmapcif']: mapfile = dic['xyzfile_orig'] + '_2fofc.map'
    shutil.move(mapfile_in, mapfile)

    if dic['ligmapcif']:  #pre-parse the cif file.
        dic['cif'] = 1

        ciffile = dic['xyzfile_orig']

        flist = open(ciffile, 'r').readlines()
        cell_items, values = cif.cifparse(flist, '_cell.')
        cell = cif.get_rows(cell_items, values)
        dic['cell_items'], dic['lig_cell'] = cell_items, cell

        sym_items, values = cif.cifparse(flist, '_symmetry.')
        sym = cif.get_rows(sym_items, values)
        dic['sym_items'], dic['lig_sym'] = sym_items, sym

        items, values = cif.cifparse(flist, '_atom_site.')
        comp = cif.parse_values(items, values, "_atom_site.auth_comp_id")
        asym = cif.parse_values(items, values, "_atom_site.auth_asym_id")
        seq = cif.parse_values(items, values, "_atom_site.auth_seq_id")
        alt = cif.parse_values(items, values, "_atom_site.label_alt_id")
        ins = cif.parse_values(items, values, "_atom_site.pdbx_PDB_ins_code")
        mod = cif.parse_values(items, values, "_atom_site.pdbx_PDB_model_num")
        row = cif.get_rows(items, values)

        dic['items'], dic['comp1'], dic['asym'], dic[
            'seq'] = items, comp, asym, seq
        dic['alt'], dic['ins'], dic['mod'], dic['row'] = alt, ins, mod, row

    fw_itool = open('LIG_PEPTIDE.cif',
                    'w')  #a cif file contains table, filenames
    fw_itool.write('data_lig_peptide\n')
    fw_itool.write(
        '\n# A "!" will be given if the residue is bad with real_space_R.\n')
    fw_itool.write('\n# Criteria: (CC<0.7 and R>0.4) or CC<0.5 or R>0.5\n')

    url = 'http://sf-tool.wwpdb.org/users_data/dir_%s/' % dic['dir']
    #url=os.environ['THIS_SERVICE_URL__FIX_ME'] + '/users_data/dir_%s/' %dic['dir']

    ch_pep, chr_pep, ch_lig, chr_lig, ch_wat, chr_wat = tls.chain_res_range(
        pdbfile)

    ligpdb = non_poly_pdb(ch_pep, ch_lig, pdbfile)  #get non-poly xyz file
    dcc = get_dcc(dccfile)  #get a list for dcc of each residue

    if not dcc:
        util.perror(
            'Warning: Failed to parse EDS values! No ligand/peptide maps will be generated. '
        )

    for k, v in ch_pep.items():
        if len(v) < 15:  #length of peptide
            if not dic['sdsc_map']:
                map_around_peptide(fw_itool, dic, mapfile, ligpdb, dcc, ch_pep,
                                   url)
            break

    if ch_lig:
        map_around_ligand(fw_itool, dic, mapfile, ligpdb, dcc, ch_lig, url)

    get_html_table_baddcc_general(mapfile, dcc)  #for polymer/lig/peptide

    fw_itool.close()

    if dic['sdsc_map']:
        arg = 'rm -f %s %s  %s  LIG_PEPTIDE.cif ' % (mapfile, mapfile_in,
                                                     xyzfile_in)
        arg = arg + ' %s_rcc_sum.cif.mtz  %s_2fofc.map_all.html ' % (
            dic['pdbfile'], dic['pdbfile'])
        os.system(arg)

#    util.delete_file(pdbfile)
    return
Exemple #12
0
    def process_images(self):
        if (self.image_list):
            # Initialize Process Counter
            curr = 0

            # Initialize Hash List
            self.hashes = []

            # Initalize Blurred Array
            self.blurred = []

            # Load Image Data Map
            image_data = load_image_data(self.image_path)

            # Error Check Image Data Map
            if (image_data is None):
                image_data = {}

            # Calculate Hash Values
            for image in self.image_list:
                # Create Data Object
                if (not (image in image_data)):
                    image_data[image] = data(lmod=util.get_lmod(image))

                # Calculate Imagehash
                self.hashes.append(imagehash.average_hash(Image.open(image)))

                # End Imagehash Calculation----------------------------------------------------------------------------------------------------------------------------

                # Store Image Name
                input_image = image

                # Store Recent Modification Time
                curr_lmod = util.get_lmod(image)

                # Calculate Blur Coefficient
                if ((image_data[image].vari is None)
                        or (image_data[image].nmax is None)
                        or (image_data[image].rmsv is None)
                        or (image_data[image].lmod < curr_lmod)):
                    # Compute RMS Value
                    loaded_image = Image.open(image).convert('L')
                    image_stats = ImageStat.Stat(loaded_image)
                    image_rms = image_stats.rms[0]

                    # Determine RMS Deficiency
                    if (image_rms < self.rms_threshold):
                        # Create Cache Folder
                        try:
                            util.mkdir(
                                util.form_path([self.image_path, TEMP_FOLD]))
                        except FileExistsError:
                            pass

                        # Create Cache File
                        input_image = util.form_path([
                            util.dirname(util.absolute(image)), TEMP_FOLD,
                            EQ_IMAGE.format(util.basename(image))
                        ])

                        # Equalize Image Histogram
                        image_file = cv2.imread(image, cv2.IMREAD_GRAYSCALE)
                        clahe = cv2.createCLAHE(clipLimit=1.125,
                                                tileGridSize=(4, 4))
                        eq_image = clahe.apply(image_file)
                        cv2.imwrite(input_image, eq_image)

                    # Ignore Future Warnings
                    with warnings.catch_warnings():
                        warnings.filterwarnings("ignore")

                        # Compute Laplace Matrix
                        loaded_image = rgb2gray(io.imread(input_image))
                        laplace_data = laplace(loaded_image, ksize=10)

                    # Store Image Data
                    image_data[image].vari = variance(laplace_data)
                    image_data[image].nmax = np.amax(laplace_data)
                    image_data[image].rmsv = image_rms
                    image_data[image].lmod = curr_lmod

                # Group Blurry Images
                if ((image_data[image].vari < self.var_threshold)
                        and (image_data[image].nmax < self.max_threshold)):
                    self.blurred.append(image)

                # Update Prompt
                print("\rProcessing Images - {}% ".format(
                    int(curr * 100 / len(self.image_list))),
                      end="")
                curr += 1

            # End Variance Computation---------------------------------------------------------------------------------------------------------------------------------

            # Write Computed Data To Data File
            with open(util.form_path([self.image_path, DATA_FILE]),
                      'w') as data_file:
                for image in image_data:
                    if (image in self.image_list):
                        data_file.write("{},{},{},{},{}\n".format(
                            image, image_data[image].vari,
                            image_data[image].nmax, image_data[image].rmsv,
                            image_data[image].lmod))
            # Close File
            data_file.close()

            # End Write Operation--------------------------------------------------------------------------------------------------------------------------------------

            # Initialize Diff List
            self.hash_diffs = []

            # Calculate Hash Differences
            for i in range(len(self.hashes) - 1):
                self.hash_diffs.append(
                    (self.hashes[i + 1] - self.hashes[i]) * self.precision)

            # End Hash Difference Computation--------------------------------------------------------------------------------------------------------------------------

            # Update Prompt
            print("\rProcessed All Images   ")
        else:
            util.perror("spectra: Found no images to process")
Exemple #13
0
def check_ncs_cif(file):
    '''check all errors in the cif file:
    check the four cif tables agaist the scheme
    '''

    flist = open(file, 'r').readlines()

    ncs = ncs_from_head(flist)

    items, values = cif.cifparse(flist, '_struct_ncs_ens.')
    ens_id = cif.parse_values(items, values, '_struct_ncs_ens.id')

    items, values = cif.cifparse(flist, '_refine_ls_restr_ncs.')
    res_ord = cif.parse_values(items, values,
                               '_refine_ls_restr_ncs.pdbx_ordinal')
    res_ref = cif.parse_values(items, values,
                               '_refine_ls_restr_ncs.pdbx_refine_id')
    res_ens = cif.parse_values(items, values,
                               '_refine_ls_restr_ncs.pdbx_ens_id')
    res_dom = cif.parse_values(items, values, '_refine_ls_restr_ncs.dom_id')
    res_typ = cif.parse_values(items, values, '_refine_ls_restr_ncs.pdbx_type')
    res_asy = cif.parse_values(items, values,
                               '_refine_ls_restr_ncs.pdbx_auth_asym_id')
    res_num = cif.parse_values(items, values,
                               '_refine_ls_restr_ncs.pdbx_number')
    res_rms = cif.parse_values(items, values,
                               '_refine_ls_restr_ncs.rms_dev_position')

    if '?' in res_rms:
        res_rms = cif.parse_values(items, values,
                                   '_refine_ls_restr_ncs.pdbx_rms')
    res_wgh = cif.parse_values(items, values,
                               '_refine_ls_restr_ncs.weight_position')

    items, values = cif.cifparse(flist, '_struct_ncs_dom.')
    dom_ens = cif.parse_values(items, values, '_struct_ncs_dom.pdbx_ens_id')
    dom_id = cif.parse_values(items, values, '_struct_ncs_dom.id')
    dom_all = cif.parse_values(items, values, '_struct_ncs_dom.details')

    items, values = cif.cifparse(flist, '_struct_ncs_dom_lim.')
    lim_ens = cif.parse_values(items, values,
                               '_struct_ncs_dom_lim.pdbx_ens_id')
    lim_dom = cif.parse_values(items, values, '_struct_ncs_dom_lim.dom_id')
    lim_com = cif.parse_values(items, values,
                               '_struct_ncs_dom_lim.pdbx_component_id')
    lim_basy = cif.parse_values(items, values,
                                '_struct_ncs_dom_lim.beg_auth_asym_id')
    lim_bseq = cif.parse_values(items, values,
                                '_struct_ncs_dom_lim.beg_auth_seq_id')
    lim_easy = cif.parse_values(items, values,
                                '_struct_ncs_dom_lim.end_auth_asym_id')
    lim_eseq = cif.parse_values(items, values,
                                '_struct_ncs_dom_lim.end_auth_seq_id')
    lim_all = cif.parse_values(items, values,
                               '_struct_ncs_dom_lim.selection_details')

    if len(ncs):
        if not (res_ens or dom_ens or lim_ens or ens_id):
            util.perror(
                'Warning: NCS records exist, but no cif tables for it.')
            return
    else:
        if not len(ens_id): return

    if not (res_ens or res_dom or res_ord or res_ref or res_asy or res_typ):
        util.perror(
            'Warning: No cif table (refine_ls_restr_ncs) or missing key items for NCS.'
        )
    if not (dom_ens or dom_id):
        util.perror(
            'Warning: No cif table (struct_ncs_dom) or missing key items for NCS.'
        )
    if not (lim_ens or lim_dom or lim_com):
        util.perror(
            'Warning: No cif table (struct_ncs_dom_lim) or missing key items for NCS.'
        )
    if not (ens_id):
        util.perror('Warning: No cif table (struct_ncs_ens) for NCS.')

    chain = get_chain_seq(flist)  #chain is dic for int

    def tmp(list1, list2):  #put ensemble=key and doms=[] to a dic
        tmpd = {}
        for j, y in enumerate(list1):
            if y not in list(tmpd.keys()): tmpd[y] = []
            tmpd[y].append(list2[j])
        return tmpd

    dom = tmp(dom_ens, dom_id)
    lim = tmp(lim_ens, lim_dom)
    res = tmp(res_ens, res_dom)

    def tmp1(list1, list2, s2):
        for n in list1:
            if n not in list2:
                util.perror('Error: NCS ID (%s) not in table (%s).' % (n, s2))

    if dom: tmp1(ens_id, list(dom.keys()), 'struct_ncs_dom')
    if lim: tmp1(ens_id, list(lim.keys()), 'struct_ncs_dom_lim')
    if res: tmp1(ens_id, list(res.keys()), 'refine_ls_restr_ncs')

    #    print chain.keys(), chain, dom, lim, res

    if (lim_basy and lim_easy and lim_bseq and lim_eseq):
        check_lim(lim_ens, chain, lim_basy, lim_easy, lim_bseq, lim_eseq)

    check_res(res_ens, chain, res_ref, res_asy, res_typ, res_num, res_rms)
Exemple #14
0
def check_res(res_ens, chain, res_ref, res_asy, res_type, res_num, res_rms):
    '''refine_ls_restr_ncs
    '''

    tab = 'refine_ls_restr_ncs'
    for i, x in enumerate(res_ens):
        if res_ref and 'X-RAY DIFFRACTION' not in res_ref[i]:
            util.perror(
                'Warning: refine_id must be "X-RAY DIFFRACTION". look at row %2d in %s.'
                % (i + 1, tab))

        if res_asy and res_asy[i] not in list(chain.keys()):
            util.perror(
                'Warning: chainID (%s) not in coordinate. look at row %2d in %s.'
                % (res_asy[i], i + 1, tab))

        if res_num and util.is_number(res_num[i]) and int(res_num[i]) == 0:
            util.perror(
                'Warning: Restrain number (or atom pairs)=0. look at row %2d in %s.'
                % (i + 1, tab))

        if (res_type
                and ('POSITIONAL' not in res_type[i].upper()
                     and 'TORSIONAL' not in res_type[i].upper()
                     and 'LOCAL' not in res_type[i].upper()
                     and 'INTERATOMIC DISTANCE' not in res_type[i].upper()
                     and 'THERMAL' not in res_type[i].upper())):
            util.perror(
                'Warning: wrong restrain type (%s). look at row %2d in %s.' %
                (res_type[i], i + 1, tab))

        if res_rms:
            rms = res_rms[i]
            if util.is_number(rms):
                if ((res_type and 'POSITIONAL' in res_type[i]
                     and float(rms) > 2)
                        or (res_type and 'TORTIONAL' in res_type[i]
                            and float(rms) > 15)):
                    util.perror(
                        'Warning: RMSD (%s) is large. look at row %2d in %s.' %
                        (rms, i + 1, tab))
            else:
                util.perror(
                    'Warning: RMSD (%s) is not a number. look at row %2d in %s. '
                    % (rms, i + 1, tab))
Exemple #15
0
 def tmp1(list1, list2, s2):
     for n in list1:
         if n not in list2:
             util.perror('Error: NCS ID (%s) not in table (%s).' % (n, s2))