Prepare a PDB file for docking by first converting it to mol2 format.

        Args:
            force_rerun (bool): If method should be rerun even if output file exists
14113
def dockprep(self, force_rerun=False):
        
        log.debug('{}: running dock preparation...'.format(self.id))

        prep_mol2 = op.join(self.dock_dir, '{}_prep.mol2'.format(self.id))
        prep_py = op.join(self.dock_dir, "prep.py")

        if ssbio.utils.force_rerun(flag=force_rerun, outfile=prep_mol2):
            with open(prep_py, "w") as f:
                f.write('import chimera\n')
                f.write('from DockPrep import prep\n')
                f.write('models = chimera.openModels.list(modelTypes=[chimera.Molecule])\n')
                f.write('prep(models)\n')
                f.write('from WriteMol2 import writeMol2\n')
                f.write('writeMol2(models, "{}")\n'.format(prep_mol2))

            cmd = 'chimera --nogui {} {}'.format(self.structure_path, prep_py)
            os.system(cmd)
            os.remove(prep_py)
            os.remove('{}c'.format(prep_py))

        if ssbio.utils.is_non_zero_file(prep_mol2):
            self.dockprep_path = prep_mol2
            log.debug('{}: successful dockprep execution'.format(self.dockprep_path))
        else:
            log.critical('{}: dockprep failed to run on PDB file'.format(self.structure_path))
402397
def run_with_reloader(main_func, extra_files=None, interval=1, reloader_type="auto"):
    """"""
    import signal

    reloader = reloader_loops[reloader_type](extra_files, interval)
    signal.signal(signal.SIGTERM, lambda *args: sys.exit(0))
    try:
        if os.environ.get("WERKZEUG_RUN_MAIN") == "true":
            ensure_echo_on()
            t = threading.Thread(target=main_func, args=())
            t.setDaemon(True)
            t.start()
            reloader.run()
        else:
            sys.exit(reloader.restart_with_reloader())
    except KeyboardInterrupt:
        pass
234834
def sphere_selector_using_residues(self, radius, force_rerun=False):
        
        log.debug('{}: running sphere selector...'.format(self.id))

        if not self.sphgen_path or not self.bindingsite_path:
            return ValueError('Please run sphgen and binding_site_mol2')

        selsph = op.join(self.dock_dir, '{}_selsph_binding.sph'.format(self.id))

        if ssbio.utils.force_rerun(flag=force_rerun, outfile=selsph):
            cmd = "sphere_selector {} {} {}".format(self.sphgen_path, self.bindingsite_path, radius)
            rename = "mv selected_spheres.sph {}".format(selsph)

            os.system(cmd)
            os.system(rename)

        if ssbio.utils.is_non_zero_file(selsph):
            self.sphsel_path = selsph
            log.debug('{}: successful sphere selection'.format(self.sphsel_path))
        else:
            log.critical('{}: sphere_selector_using_residues failed to run on sph file'.format(self.sphgen_path))
1263514
public static br_broker force_reboot(nitro_service client, br_broker resource) throws Exception
	{
		return ((br_broker[]) resource.perform_operation(client, "force_reboot"))[0];
	}
838715
def run(self):
        
        if not self.should_run():
            return

        manifests_archive_dir = tempfile.mkdtemp()
        image = self.workflow.image
        # As in flatpak_create_oci, we specify command to prevent possible docker daemon errors.
        container_dict = self.tasker.d.create_container(image, command=['/bin/bash'])
        container_id = container_dict['Id']
        try:
            bits, stat = self.tasker.d.get_archive(container_id,
                                                   IMG_MANIFESTS_PATH)
        except APIError as ex:
            msg = ('Could not extract operator manifest files. '
                   'Is there a %s path in the image?' % (IMG_MANIFESTS_PATH))
            self.log.debug('Error while trying to extract %s from image: %s',
                           IMG_MANIFESTS_PATH, ex)
            self.log.error(msg)
            raise RuntimeError('%s %s' % (msg, ex))
        finally:
            self.tasker.d.remove_container(container_id)

        with tempfile.NamedTemporaryFile() as extracted_file:
            for chunk in bits:
                extracted_file.write(chunk)
            extracted_file.flush()
            tar_archive = tarfile.TarFile(extracted_file.name)

        tar_archive.extractall(manifests_archive_dir)
        manifests_path = os.path.join(manifests_archive_dir, MANIFESTS_DIR_NAME)

        manifests_zipfile_path = os.path.join(manifests_archive_dir, OPERATOR_MANIFESTS_ARCHIVE)
        with zipfile.ZipFile(manifests_zipfile_path, 'w') as archive:
            for root, _, files in os.walk(manifests_path):
                for f in files:
                    filedir = os.path.relpath(root, manifests_path)
                    filepath = os.path.join(filedir, f)
                    archive.write(os.path.join(root, f), filepath)
            manifest_files = archive.namelist()
            if not manifest_files:
                self.log.error('Empty operator manifests directory')
                raise RuntimeError('Empty operator manifests directory')
            self.log.debug("Archiving operator manifests: %s", manifest_files)

        shutil.rmtree(manifests_path)

        return manifests_zipfile_path
770994
def run_forge(args):
    
    version = args.version
    commit_id = args.commit_id
    branch = args.branch

    try:
        print(Version(version, commit_id, branch))
    except DockerTagNamingException, de:
        print(de)
        sys.exit(1)
754892
def rerun(client, revision, roots, siblings, inputs, paths):
    """"""
    graph = Graph(client)
    outputs = graph.build(paths=paths, revision=revision)

    # Check or extend siblings of outputs.
    outputs = siblings(graph, outputs)
    output_paths = {node.path for node in outputs}

    # Normalize and check all starting paths.
    roots = {graph.normalize_path(root) for root in roots}
    assert not roots & output_paths, '--from colides with output paths'

    # Generate workflow and check inputs.
    # NOTE The workflow creation is done before opening a new file.
    workflow = inputs(
        client,
        graph.ascwl(
            input_paths=roots,
            output_paths=output_paths,
            outputs=outputs,
        )
    )

    # Make sure all inputs are pulled from a storage.
    client.pull_paths_from_storage(
        *(path for _, path in workflow.iter_input_files(client.workflow_path))
    )

    # Store the generated workflow used for updating paths.
    import yaml

    output_file = client.workflow_path / '{0}.cwl'.format(uuid.uuid4().hex)
    with output_file.open('w') as f:
        f.write(
            yaml.dump(
                ascwl(
                    workflow,
                    filter=lambda _, x: x is not None,
                    basedir=client.workflow_path,
                ),
                default_flow_style=False
            )
        )

    # Execute the workflow and relocate all output files.
    from ._cwl import execute
    # FIXME get new output paths for edited tools
    # output_paths = {path for _, path in workflow.iter_output_files()}
    execute(
        client,
        output_file,
        output_paths=output_paths,
    )
356687
def process_forcefield(*forcefields):
    
    for forcefield in forcefields:
        if forcefield.endswith('.frcmod'):
            gaffmol2 = os.path.splitext(forcefield)[0] + '.gaff.mol2'
            yield create_ffxml_file([gaffmol2], [forcefield])
        else:
            yield forcefield
784880
def is_forced_retry(self, method, status_code):
        
        if self.method_whitelist and method.upper() not in self.method_whitelist:
            return False

        return self.status_forcelist and status_code in self.status_forcelist
154064
def update(self, force=[]):
        

        # These lists may help us become very fast in the future
        newkeys = []
        oldvals = []
        newvals = []

        cfg_cur = self.rtdc_ds.config["filtering"]
        cfg_old = self._old_config

        # Determine which data was updated
        for skey in list(cfg_cur.keys()):
            if skey not in cfg_old:
                cfg_old[skey] = None
            if cfg_cur[skey] != cfg_old[skey]:
                newkeys.append(skey)
                oldvals.append(cfg_old[skey])
                newvals.append(cfg_cur[skey])

        # 1. Filter all feature min/max values.
        # This line gets the feature names that must be filtered.
        col2filter = []
        for k in newkeys:
            # k[:-4] because we want to crop " min" and " max"
            if k[:-4] in dfn.scalar_feature_names:
                col2filter.append(k[:-4])

        for f in force:
            # Manually add forced features
            if f in dfn.scalar_feature_names:
                col2filter.append(f)
            else:
                # Make sure the feature name is valid.
                raise ValueError("Unknown feature name {}".format(f))

        col2filter = np.unique(col2filter)

        for col in col2filter:
            if col in self.rtdc_ds:
                fstart = col + " min"
                fend = col + " max"
                # Get the current feature filter
                col_filt = self[col]
                # If min and max exist and if they are not identical:
                if (fstart in cfg_cur and
                    fend in cfg_cur and
                        cfg_cur[fstart] != cfg_cur[fend]):
                    # TODO: speedup
                    # Here one could check for smaller values in the
                    # lists oldvals/newvals that we defined above.
                    # Be sure to check against force in that case!
                    ivalstart = cfg_cur[fstart]
                    ivalend = cfg_cur[fend]
                    if ivalstart > ivalend:
                        msg = "inverting filter: {} > {}".format(fstart, fend)
                        warnings.warn(msg)
                        ivalstart, ivalend = ivalend, ivalstart
                    data = self.rtdc_ds[col]
                    col_filt[:] = (ivalstart <= data)*(data <= ivalend)
                else:
                    col_filt[:] = True

        # 2. Filter with polygon filters
        # check if something has changed
        pf_id = "polygon filters"
        if (
            (pf_id in cfg_cur and pf_id not in cfg_old) or
            (pf_id in cfg_cur and pf_id in cfg_old and
             cfg_cur[pf_id] != cfg_old[pf_id])):
            self.polygon[:] = True
            # perform polygon filtering
            for p in PolygonFilter.instances:
                if p.unique_id in cfg_cur[pf_id]:
                    # update self.polygon
                    # iterate through axes
                    datax = self.rtdc_ds[p.axes[0]]
                    datay = self.rtdc_ds[p.axes[1]]
                    self.polygon *= p.filter(datax, datay)

        # 3. Invalid filters
        self.invalid[:] = True
        if cfg_cur["remove invalid events"]:
            for col in dfn.scalar_feature_names:
                if col in self.rtdc_ds:
                    data = self.rtdc_ds[col]
                    invalid = np.isinf(data) | np.isnan(data)
                    self.invalid *= ~invalid

        # 4. Finally combine all filters
        # get a list of all filters
        self.all[:] = True

        if cfg_cur["enable filters"]:
            for col in self._filters:
                self.all[:] *= self._filters[col]

            self.all[:] *= self.invalid
            self.all[:] *= self.manual
            self.all[:] *= self.polygon

            # Filter with configuration keyword argument "limit events".
            # This additional step limits the total number of events in
            # self.all.
            if cfg_cur["limit events"] > 0:
                limit = cfg_cur["limit events"]
                sub = self.all[self.all]
                _f, idx = downsampling.downsample_rand(sub,
                                                       samples=limit,
                                                       ret_idx=True)
                sub[~idx] = False
                self.all[self.all] = sub

        # Actual filtering is then done during plotting
        self._old_config = self.rtdc_ds.config.copy()["filtering"]
492294
def process_pdb(pdbfile, outpath, as_string=False, outputprefix='report'):
    """"""
    if not as_string:
        startmessage = '\nStarting analysis of %s\n' % pdbfile.split('/')[-1]
    else:
        startmessage = "Starting analysis from stdin.\n"
    write_message(startmessage)
    write_message('='*len(startmessage)+'\n')
    mol = PDBComplex()
    mol.output_path = outpath
    mol.load_pdb(pdbfile, as_string=as_string)
    # #@todo Offers possibility for filter function from command line (by ligand chain, position, hetid)
    for ligand in mol.ligands:
        mol.characterize_complex(ligand)

    create_folder_if_not_exists(outpath)

    # Generate the report files
    streport = StructureReport(mol, outputprefix=outputprefix)

    config.MAXTHREADS = min(config.MAXTHREADS, len(mol.interaction_sets))

    ######################################
    # PyMOL Visualization (parallelized) #
    ######################################

    if config.PYMOL or config.PICS:
        try:
            from plip.modules.visualize import visualize_in_pymol
        except ImportError:
            from modules.visualize import visualize_in_pymol
        complexes = [VisualizerData(mol, site) for site in sorted(mol.interaction_sets)
                     if not len(mol.interaction_sets[site].interacting_res) == 0]
        if config.MAXTHREADS > 1:
            write_message('\nGenerating visualizations in parallel on %i cores ...' % config.MAXTHREADS)
            parfn = parallel_fn(visualize_in_pymol)
            parfn(complexes, processes=config.MAXTHREADS)
        else:
            [visualize_in_pymol(plcomplex) for plcomplex in complexes]

    if config.XML:  # Generate report in xml format
        streport.write_xml(as_string=config.STDOUT)

    if config.TXT:  # Generate report in txt (rst) format
        streport.write_txt(as_string=config.STDOUT)
5742
def get_msms_annotations(self, outdir, force_rerun=False):
        
        # Now can run on Biopython Model objects exclusively thanks to Biopython updates
        # if self.file_type != 'pdb':
        #     raise ValueError('{}: unable to run MSMS with "{}" file type. Please change file type to "pdb"'.format(self.id,
        #                                                                                                     self.file_type))

        if self.structure:
            parsed = self.structure
        else:
            parsed = self.parse_structure()

        if not parsed:
            log.error('{}: unable to open structure to run MSMS'.format(self.id))
            return

        log.debug('{}: running MSMS'.format(self.id))
        # PDB ID is currently set to the structure file so the output name is the same with _msms.df appended to it
        msms_results = ssbio.protein.structure.properties.msms.get_msms_df(model=parsed.first_model, pdb_id=self.structure_path,
                                                                           outdir=outdir, force_rerun=force_rerun)
        if msms_results.empty:
            log.error('{}: unable to run MSMS'.format(self.id))
            return

        chains = msms_results.chain.unique()

        for chain in chains:
            res_depths = msms_results[msms_results.chain == chain].res_depth.tolist()
            ca_depths = msms_results[msms_results.chain == chain].ca_depth.tolist()

            chain_prop = self.chains.get_by_id(chain)
            chain_seq = chain_prop.seq_record

            # Making sure the X's are filled in
            res_depths = ssbio.protein.structure.properties.residues.match_structure_sequence(orig_seq=chain_seq,
                                                                                              new_seq=res_depths,
                                                                                              fill_with=float('Inf'))

            ca_depths = ssbio.protein.structure.properties.residues.match_structure_sequence(orig_seq=chain_seq,
                                                                                             new_seq=ca_depths,
                                                                                             fill_with=float('Inf'))

            chain_prop.seq_record.letter_annotations['RES_DEPTH-msms'] = res_depths
            chain_prop.seq_record.letter_annotations['CA_DEPTH-msms'] = ca_depths
            log.debug('{}: stored residue depths in chain seq_record letter_annotations'.format(chain))
680234
def load_pdb(self, pdbpath, as_string=False):
        """"""
        if as_string:
            self.sourcefiles['pdbcomplex.original'] = None
            self.sourcefiles['pdbcomplex'] = None
            self.sourcefiles['pdbstring'] = pdbpath
        else:
            self.sourcefiles['pdbcomplex.original'] = pdbpath
            self.sourcefiles['pdbcomplex'] = pdbpath
        self.information['pdbfixes'] = False
        pdbparser = PDBParser(pdbpath, as_string=as_string)  # Parse PDB file to find errors and get additonal data
        # #@todo Refactor and rename here
        self.Mapper.proteinmap = pdbparser.proteinmap
        self.Mapper.reversed_proteinmap = {v: k for k, v in self.Mapper.proteinmap.items()}
        self.modres = pdbparser.modres
        self.covalent = pdbparser.covalent
        self.altconf = pdbparser.altconformations
        self.corrected_pdb = pdbparser.corrected_pdb

        if not config.PLUGIN_MODE:
            if pdbparser.num_fixed_lines > 0:
                write_message('%i lines automatically fixed in PDB input file.\n' % pdbparser.num_fixed_lines)
                # Save modified PDB file
                if not as_string:
                    basename = os.path.basename(pdbpath).split('.')[0]
                else:
                    basename = "from_stdin"
                pdbpath_fixed = tmpfile(prefix='plipfixed.' + basename + '_', direc=self.output_path)
                create_folder_if_not_exists(self.output_path)
                self.sourcefiles['pdbcomplex'] = pdbpath_fixed
                self.corrected_pdb = re.sub(r'[^\x00-\x7F]+', ' ', self.corrected_pdb)  # Strip non-unicode chars
                if not config.NOFIXFILE:  # Only write to file if this option is not activated
                    with open(pdbpath_fixed, 'w') as f:
                        f.write(self.corrected_pdb)
                self.information['pdbfixes'] = True

        if not as_string:
            self.sourcefiles['filename'] = os.path.basename(self.sourcefiles['pdbcomplex'])
        self.protcomplex, self.filetype = read_pdb(self.corrected_pdb, as_string=True)

        # Update the model in the Mapper class instance
        self.Mapper.original_structure = self.protcomplex.OBMol
        write_message('PDB structure successfully read.\n')

        # Determine (temporary) PyMOL Name from Filename
        self.pymol_name = pdbpath.split('/')[-1].split('.')[0] + '-Protein'
        # Replace characters causing problems in PyMOL
        self.pymol_name = self.pymol_name.replace(' ', '').replace('(', '').replace(')', '').replace('-', '_')
        # But if possible, name it after PDBID in Header
        if 'HEADER' in self.protcomplex.data:  # If the PDB file has a proper header
            potential_name = self.protcomplex.data['HEADER'][56:60].lower()
            if extract_pdbid(potential_name) != 'UnknownProtein':
                self.pymol_name = potential_name
        write_message("Pymol Name set as: '%s'\n" % self.pymol_name, mtype='debug')

        # Extract and prepare ligands
        ligandfinder = LigandFinder(self.protcomplex, self.altconf, self.modres, self.covalent, self.Mapper)
        self.ligands = ligandfinder.ligands
        self.excluded = ligandfinder.excluded

        # Add polar hydrogens
        self.protcomplex.OBMol.AddPolarHydrogens()
        for atm in self.protcomplex:
            self.atoms[atm.idx] = atm
        write_message("Assigned polar hydrogens\n", mtype='debug')

        if len(self.excluded) != 0:
            write_message("Excluded molecules as ligands: %s\n" % ','.join([lig for lig in self.excluded]))

        if config.DNARECEPTOR:
            self.resis = [obres for obres in pybel.ob.OBResidueIter(
                self.protcomplex.OBMol) if obres.GetName() in config.DNA+config.RNA]
        else:
            self.resis = [obres for obres in pybel.ob.OBResidueIter(
                self.protcomplex.OBMol) if obres.GetResidueProperty(0)]

        num_ligs = len(self.ligands)
        if num_ligs == 1:
            write_message("Analyzing one ligand...\n")
        elif num_ligs > 1:
            write_message("Analyzing %i ligands...\n" % num_ligs)
        else:
            write_message("Structure contains no ligands.\n\n")
731906
def setup_output_dir(op_dir, force)
      flag_file = output_flag_file(op_dir)
      if File.exist?(op_dir)
        unless File.directory?(op_dir)
          error "'#{op_dir}' exists, and is not a directory" 
        end
        begin
          created = File.read(flag_file)
        rescue SystemCallError
          error "\nDirectory #{op_dir} already exists, but it looks like it\n" +
            "isn't an RDoc directory. Because RDoc doesn't want to risk\n" +
            "destroying any of your existing files, you'll need to\n" +
            "specify a different output directory name (using the\n" +
            "--op <dir> option).\n\n"
        else
          last = (Time.parse(created) unless force rescue nil)
        end
      else
        File.makedirs(op_dir)
      end
      last
    end
1359874
def do_dock6_flexible(self, ligand_path, force_rerun=False):
        
        log.debug('{}: running DOCK6...'.format(self.id))

        ligand_name = os.path.basename(ligand_path).split('.')[0]
        in_name = op.join(self.dock_dir, "{}_{}_flexdock.in".format(self.id, ligand_name))
        out_name = op.join(self.dock_dir, "{}_{}_flexdock.out".format(self.id, ligand_name))

        conformers_out = op.join(self.dock_dir, '{}_{}_flexdock_conformers.mol2'.format(self.id, ligand_name))
        scored_out = op.join(self.dock_dir, '{}_{}_flexdock_scored.mol2'.format(self.id, ligand_name))
        ranked_out = op.join(self.dock_dir, '{}_{}_flexdock_ranked.mol2'.format(self.id, ligand_name))

        if ssbio.utils.force_rerun(flag=force_rerun, outfile=ranked_out):
            with open(in_name, "w") as f:
                dock_text = """ligand_atom_file                                             {}
limit_max_ligands                                            no
skip_molecule                                                no
read_mol_solvation                                           no
calculate_rmsd                                               no
use_database_filter                                          no
orient_ligand                                                yes
automated_matching                                           yes
receptor_site_file                                           {}
max_orientations                                             500
critical_points                                              no
chemical_matching                                            no
use_ligand_spheres                                           no
use_internal_energy                                          yes
internal_energy_rep_exp                                      12
flexible_ligand                                              yes
user_specified_anchor                                        no
limit_max_anchors                                            no
min_anchor_size                                              5
pruning_use_clustering                                       yes
pruning_max_orients                                          100
pruning_clustering_cutoff                                    100
pruning_conformer_score_cutoff                               100
use_clash_overlap                                            no
write_growth_tree                                            no
bump_filter                                                  yes
bump_grid_prefix                                             {}
score_molecules                                              yes
contact_score_primary                                        no
contact_score_secondary                                      no
grid_score_primary                                           yes
grid_score_secondary                                         no
grid_score_rep_rad_scale                                     1
grid_score_vdw_scale                                         1
grid_score_es_scale                                          1
grid_score_grid_prefix                                       {}
multigrid_score_secondary                                    no
dock3.5_score_secondary                                      no
continuous_score_secondary                                   no
descriptor_score_secondary                                   no
gbsa_zou_score_secondary                                     no
gbsa_hawkins_score_secondary                                 no
SASA_descriptor_score_secondary                              no
amber_score_secondary                                        no
minimize_ligand                                              yes
minimize_anchor                                              yes
minimize_flexible_growth                                     yes
use_advanced_simplex_parameters                              no
simplex_max_cycles                                           1
simplex_score_converge                                       0.1
simplex_cycle_converge                                       1.0
simplex_trans_step                                           1.0
simplex_rot_step                                             0.1
simplex_tors_step                                            10.0
simplex_anchor_max_iterations                                500
simplex_grow_max_iterations                                  500
simplex_grow_tors_premin_iterations                          0
simplex_random_seed                                          0
simplex_restraint_min                                        yes
simplex_coefficient_restraint                                10.0
atom_model                                                   all
vdw_defn_file                                                {}
flex_defn_file                                               {}
flex_drive_file                                              {}
ligand_outfile_prefix                                        {}_{}_flexdock
write_orientations                                           no
num_scored_conformers                                        20
write_conformations                                          yes
cluster_conformations                                        yes
rank_ligands                                                 yes
        """.format(ligand_path, op.basename(self.sphsel_path), op.splitext(op.basename(self.grid_path))[0],
                   op.splitext(op.basename(self.grid_path))[0], self.amb_file, self.flex1_file, self.flex2_file,
                   self.id, ligand_name)

                f.write(dock_text)

            os.chdir(self.dock_dir)
            cmd = "dock6 -i {} -o {} -v".format(in_name, out_name)
            os.system(cmd)

        if ssbio.utils.is_non_zero_file(ranked_out):
            self.dock_flexible_outfile = out_name
            self.dock_flexible_conformers_result = conformers_out
            self.dock_flexible_scored_result = scored_out
            log.debug('{}: successful docking!'.format(self.dock_flexible_outfile))
        else:
            log.error('{}+{}: empty DOCK6 ranked file, execution error (or ligand failed to dock)'.format(self.id,
                                                                                                          op.basename(ligand_path)))
338038
def rebind(self, column=None, brew='GnBu'):
        
        self.data['table'] = Data.keypairs(
            self.raw_data, columns=[self.data_key, column])
        domain = [Data.serialize(self.raw_data[column].min()),
                  Data.serialize(self.raw_data[column].quantile(0.95))]
        scale = Scale(name='color', type='quantize', domain=domain,
                      range=brews[brew])
        self.scales['color'] = scale
233045
def setup_detect_python2():
        
        if None in [RTs._rt_py2_detect, RTs._rtp_py2_detect]:
            RTs._rt_py2_detect = RefactoringTool(py2_detect_fixers)
            RTs._rtp_py2_detect = RefactoringTool(py2_detect_fixers,
                                                  {'print_function': True})