Analysis of a single PDB file. Can generate textual reports XML, PyMOL session files and images as output.
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)
1131009
def _generate_tree_log_file(self, tree, alignment, output_tree_file_path,
                               output_log_file_path, residue_type, fasttree):
        '''
        '''
        if residue_type==Create._NUCLEOTIDE_PACKAGE_TYPE:
            cmd = "%s -quiet -gtr -nt -nome -mllen -intree '%s' -log %s -out %s %s" %\
                                       (fasttree, tree, output_log_file_path,
                                        output_tree_file_path, alignment)
        elif residue_type==Create._PROTEIN_PACKAGE_TYPE:
            cmd = "%s -quiet -nome -mllen -intree '%s' -log %s -out %s %s" %\
                                       (fasttree, tree, output_log_file_path,
                                        output_tree_file_path, alignment)
        extern.run(cmd)
977411
def main_init():
    """"""
    parser = ArgumentParser(prog="PLIP", description=descript)
    pdbstructure = parser.add_mutually_exclusive_group(required=True)  # Needs either PDB ID or file
    # '-' as file name reads from stdin
    pdbstructure.add_argument("-f", "--file", dest="input", nargs="+", help="Set input file, '-' reads from stdin")
    pdbstructure.add_argument("-i", "--input", dest="pdbid", nargs="+")
    outputgroup = parser.add_mutually_exclusive_group(required=False)  # Needs either outpath or stdout
    outputgroup.add_argument("-o", "--out", dest="outpath", default="./")
    outputgroup.add_argument("-O", "--stdout", dest="stdout", action="store_true", default=False, help="Write to stdout instead of file")
    parser.add_argument("--rawstring", dest="use_raw_string", default=False, action="store_true", help="Use Python raw strings for stdout and stdin")
    parser.add_argument("-v", "--verbose", dest="verbose", default=False, help="Set verbose mode", action="store_true")
    parser.add_argument("-p", "--pics", dest="pics", default=False, help="Additional pictures", action="store_true")
    parser.add_argument("-x", "--xml", dest="xml", default=False, help="Generate report file in XML format",
                        action="store_true")
    parser.add_argument("-t", "--txt", dest="txt", default=False, help="Generate report file in TXT (RST) format",
                        action="store_true")
    parser.add_argument("-y", "--pymol", dest="pymol", default=False, help="Additional PyMOL session files",
                        action="store_true")
    parser.add_argument("--maxthreads", dest="maxthreads", default=multiprocessing.cpu_count(),
                        help="Set maximum number of main threads (number of binding sites processed simultaneously)."
                             "If not set, PLIP uses all available CPUs if possible.",
                        type=int)
    parser.add_argument("--breakcomposite", dest="breakcomposite", default=False,
                        help="Don't combine ligand fragments with covalent bonds but treat them as single ligands for the analysis.",
                        action="store_true")
    parser.add_argument("--altlocation", dest="altlocation", default=False,
                        help="Also consider alternate locations for atoms (e.g. alternate conformations).",
                        action="store_true")
    parser.add_argument("--debug", dest="debug", default=False,
                        help="Turn on DEBUG mode with extended log.",
                        action="store_true")
    parser.add_argument("--nofix", dest="nofix", default=False,
                        help="Turns off fixing of PDB files.",
                        action="store_true")
    parser.add_argument("--nofixfile", dest="nofixfile", default=False,
                        help="Turns off writing files for fixed PDB files.",
                        action="store_true")
    parser.add_argument("--nopdbcanmap", dest="nopdbcanmap", default=False,
                        help="Turns off calculation of mapping between canonical and PDB atom order for ligands.",
                        action="store_true")
    parser.add_argument("--dnareceptor", dest="dnareceptor", default=False,
                        help="Uses the DNA instead of the protein as a receptor for interactions.",
                        action="store_true")
    parser.add_argument("--name", dest="outputfilename", default="report",
                        help="Set a filename for the report TXT and XML files. Will only work when processing single structures.")
    ligandtype = parser.add_mutually_exclusive_group()  # Either peptide/inter or intra mode
    ligandtype.add_argument("--peptides", "--inter", dest="peptides", default=[],
                        help="Allows to define one or multiple chains as peptide ligands or to detect inter-chain contacts",
                        nargs="+")
    ligandtype.add_argument("--intra", dest="intra", help="Allows to define one chain to analyze intra-chain contacts.")
    parser.add_argument("--keepmod", dest="keepmod", default=False,
                        help="Keep modified residues as ligands",
                        action="store_true")
    # Optional threshold arguments, not shown in help
    thr = namedtuple('threshold', 'name type')
    thresholds = [thr(name='aromatic_planarity', type='angle'),
                  thr(name='hydroph_dist_max', type='distance'), thr(name='hbond_dist_max', type='distance'),
                  thr(name='hbond_don_angle_min', type='angle'), thr(name='pistack_dist_max', type='distance'),
                  thr(name='pistack_ang_dev', type='other'), thr(name='pistack_offset_max', type='distance'),
                  thr(name='pication_dist_max', type='distance'), thr(name='saltbridge_dist_max', type='distance'),
                  thr(name='halogen_dist_max', type='distance'), thr(name='halogen_acc_angle', type='angle'),
                  thr(name='halogen_don_angle', type='angle'), thr(name='halogen_angle_dev', type='other'),
                  thr(name='water_bridge_mindist', type='distance'), thr(name='water_bridge_maxdist', type='distance'),
                  thr(name='water_bridge_omega_min', type='angle'), thr(name='water_bridge_omega_max', type='angle'),
                  thr(name='water_bridge_theta_min', type='angle')]
    for t in thresholds:
        parser.add_argument('--%s' % t.name, dest=t.name, type=lambda val: threshold_limiter(parser, val),
                            help=argparse.SUPPRESS)

    arguments = parser.parse_args()
    config.VERBOSE = True if (arguments.verbose or arguments.debug) else False
    config.DEBUG = True if arguments.debug else False
    config.MAXTHREADS = arguments.maxthreads
    config.XML = arguments.xml
    config.TXT = arguments.txt
    config.PICS = arguments.pics
    config.PYMOL = arguments.pymol
    config.STDOUT = arguments.stdout
    config.RAWSTRING = arguments.use_raw_string
    config.OUTPATH = arguments.outpath
    config.OUTPATH = tilde_expansion("".join([config.OUTPATH, '/'])
                                     if not config.OUTPATH.endswith('/') else config.OUTPATH)
    config.BASEPATH = config.OUTPATH  # Used for batch processing
    config.BREAKCOMPOSITE = arguments.breakcomposite
    config.ALTLOC = arguments.altlocation
    config.PEPTIDES = arguments.peptides
    config.INTRA = arguments.intra
    config.NOFIX = arguments.nofix
    config.NOFIXFILE = arguments.nofixfile
    config.NOPDBCANMAP = arguments.nopdbcanmap
    config.KEEPMOD = arguments.keepmod
    config.DNARECEPTOR = arguments.dnareceptor
    config.OUTPUTFILENAME = arguments.outputfilename
    # Make sure we have pymol with --pics and --pymol
    if config.PICS or config.PYMOL:
        try:
            import pymol
        except ImportError:
            write_message("PyMOL is required for --pics and --pymol.\n", mtype='error')
            raise
    # Assign values to global thresholds
    for t in thresholds:
        tvalue = getattr(arguments, t.name)
        if tvalue is not None:
            if t.type == 'angle' and not 0 < tvalue < 180:  # Check value for angle thresholds
                parser.error("Threshold for angles need to have values within 0 and 180.")
            if t.type == 'distance':
                if tvalue > 10:  # Check value for angle thresholds
                    parser.error("Threshold for distances must not be larger than 10 Angstrom.")
                elif tvalue > config.BS_DIST + 1:  # Dynamically adapt the search space for binding site residues
                    config.BS_DIST = tvalue + 1
            setattr(config, t.name.upper(), tvalue)
    # Check additional conditions for interdependent thresholds
    if not config.HALOGEN_ACC_ANGLE > config.HALOGEN_ANGLE_DEV:
        parser.error("The halogen acceptor angle has to be larger than the halogen angle deviation.")
    if not config.HALOGEN_DON_ANGLE > config.HALOGEN_ANGLE_DEV:
        parser.error("The halogen donor angle has to be larger than the halogen angle deviation.")
    if not config.WATER_BRIDGE_MINDIST < config.WATER_BRIDGE_MAXDIST:
        parser.error("The water bridge minimum distance has to be smaller than the water bridge maximum distance.")
    if not config.WATER_BRIDGE_OMEGA_MIN < config.WATER_BRIDGE_OMEGA_MAX:
        parser.error("The water bridge omega minimum angle has to be smaller than the water bridge omega maximum angle")
    expanded_path = tilde_expansion(arguments.input) if arguments.input is not None else None
    main(expanded_path, arguments.pdbid)
686834
def analyze(files)
      report    = Report.new(configuration.report_levels)
      presenter = configuration.presenter.new
      parser    = Parser.new

      parser.consumer = proc do |diag|
        report_diagnostic(diag, report)
      end

      files.each do |file|
        analyze_file(file, parser, report)
      end

      return presenter.present(report)
    end
1033471
def cli(yamlfile, format, output, collections):
    
    print(ShExGenerator(yamlfile, format).serialize(output=output, collections=collections))
365840
def process_output(meta_file, outfile_name, code_links):
    '''
    '''

    # Markdown title line
    doc_str = '# ' + meta_file['header'] + '\n'
    doc_str += 'Generated by [py2md](https://github.com/gbowerman/py2md) on '
    doc_str += strftime("%Y-%m-%d %H:%M:%S ") + '\n\n'

    # Create a table of contents if more than one module (i.e. more than one
    # source file)
    if len(meta_file['modules']) > 1:
        doc_str += "## Contents\n"
        chapter_num = 1
        for meta_doc in meta_file['modules']:
            chapter_name = meta_doc['summary_comment']
            chapter_link = chapter_name.lstrip().replace('.', '').replace(' ', '-').lower()
            doc_str += str(chapter_num) + \
                '. [' + chapter_name + '](#' + chapter_link + ')\n'
            chapter_num += 1


    # Document each meta-file
    for meta_doc in meta_file['modules']:
        doc_str += '## ' + meta_doc['summary_comment'] + '\n'
        doc_str += '[source file](' + meta_doc['source_file'] + ')' + '\n'
        for function_info in meta_doc['functions']:
            doc_str += '### ' + function_info['name'] + '\n'
            doc_str += function_info['definition'] + '\n\n'
            if 'comments' in function_info:
                doc_str += '```\n' + function_info['comments'] + '\n```\n\n'

    # write the markdown to file
    print('Writing file: ' + outfile_name)
    out_file = open(outfile_name, 'w')
    out_file.write(doc_str)
    out_file.close()
936130
def _build_pcollection(self, pipeline, filepaths, language):
    """"""

    beam = tfds.core.lazy_imports.apache_beam

    def _extract_content(filepath):
      """Extracts article content from a single WikiMedia XML file."""
      logging.info("generating examples from = %s", filepath)
      with tf.io.gfile.GFile(filepath) as f:
        for _, elem in etree.iterparse(f, events=("end",)):
          if not elem.tag.endswith("page"):
            continue
          namespace = elem.tag[:-4]
          title = elem.find("./{0}title".format(namespace)).text
          ns = elem.find("./{0}ns".format(namespace)).text

          # Filter pages that are not in the "main" namespace.
          if ns != "0":
            continue

          raw_content = elem.find(
              "./{0}revision/{0}text".format(namespace)).text
          elem.clear()

          # Filter redirects.
          if raw_content is None or raw_content.lower().startswith("#redirect"):
            beam.metrics.Metrics.counter(language, "filtered-redirects").inc()
            continue

          beam.metrics.Metrics.counter(language, "extracted-examples").inc()
          yield (title, raw_content)

    def _clean_content(inputs):
      """Cleans raw wikicode to extract text."""
      title, raw_content = inputs
      try:
        text = _parse_and_clean_wikicode(raw_content)
      except (
          tfds.core.lazy_imports.mwparserfromhell.parser.ParserError) as e:
        beam.metrics.Metrics.counter(language, "parser-error").inc()
        logging.error("mwparserfromhell ParseError: %s", e)
        return

      beam.metrics.Metrics.counter(language, "cleaned-examples").inc()

      yield {
          "title": title,
          "text": text
      }

    return (
        pipeline
        | beam.Create(filepaths)
        | beam.FlatMap(_extract_content)
        | beam.FlatMap(_clean_content)
    )
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")
1166954
def outputPDF(self,**kwargs):
        
        import pylatex as pl
        geometry_options = {"tmargin": "2cm", "lmargin": "2cm"}
        doc = pl.Document(geometry_options=geometry_options)
        #Following option avoids float error when to many unplaced figs or tabs
        # (to force placing floats also \clearpage can be used after a section for example)
        doc.append(pl.utils.NoEscape(r'\extrafloats{100}'))
        doc.append(pl.utils.NoEscape(r'\title{'+self.title+'}'))
        if self.addTime:
            from time import localtime, strftime
            doc.append(pl.utils.NoEscape(r'\date{'+strftime("%Y-%m-%d %H:%M:%S", localtime())+r'}'))
        else: doc.append(pl.utils.NoEscape(r'\date{\today}'))
        if self.author: doc.append(pl.utils.NoEscape(r'\author{'+self.author+'}'))
        doc.append(pl.utils.NoEscape(r'\maketitle'))

        # Append introduction
        if self.p:
            with doc.create(pl.Section('Introduction')):
                doc.append(renewliner(self.p))

        # Sections
        c = count(1)
        for section in self.sections:
            section.sectionsPDF(walkTrace=(next(c),),doc=doc)

        # Append conclusion
        if self.conclusion:
            with doc.create(pl.Section('Conclusion')):
                doc.append(renewliner(self.conclusion))

        # Generate pdf
        doc.generate_pdf(self.outfile,**kwargs)
1008657
def _parse_kraken_output(out_dir, db, data):
    
    in_file = os.path.join(out_dir, "kraken_out")
    stat_file = os.path.join(out_dir, "kraken_stats")
    out_file = os.path.join(out_dir, "kraken_summary")
    kraken_cmd = config_utils.get_program("kraken-report", data["config"])
    classify = unclassify = None
    with open(stat_file, 'r') as handle:
        for line in handle:
            if line.find(" classified") > -1:
                classify = line[line.find("(") + 1:line.find(")")]
            if line.find(" unclassified") > -1:
                unclassify = line[line.find("(") + 1:line.find(")")]
    if os.path.getsize(in_file) > 0 and not os.path.exists(out_file):
        with file_transaction(data, out_file) as tx_out_file:
            cl = ("{kraken_cmd} --db {db} {in_file} > {tx_out_file}").format(**locals())
            do.run(cl, "kraken report: %s" % dd.get_sample_name(data))
    kraken = {"kraken_clas": classify, "kraken_unclas": unclassify}
    kraken_sum = _summarize_kraken(out_file)
    kraken.update(kraken_sum)
    return kraken
145897
def pprint(data, tag_lookup, indent=0):
    """"""
    output = ''
    if isinstance(data, dict):
        for key, value in data.items():
            tag = tag_lookup(key)
            if isinstance(value, (dict, list)) and tag.type is not read_bplist:
                output += '{0}{1}: {2}\n'.format(indent*' ', key, tag)
                output += pprint(value, tag_lookup, indent+2)
            else:
                output += '{0}{1}: {2} {3}\n'.format(
                    indent*' ', key, str(value), tag)
    elif isinstance(data, list):
        for elem in data:
            output += pprint(elem, tag_lookup, indent)
    else:
        raise exceptions.InvalidDmapDataError(
            'invalid dmap data: ' + str(data))
    return output
455870
def generate(self):
    
    self._setup()

    header_html = self._generate_header()
    footer_html = self._generate_footer()
    results_topbar_html = self._generate_topbar("results")
    summary_topbar_html = self._generate_topbar("summary")
    logs_topbar_html = self._generate_topbar("logs")
    diff_topbar_html = self._generate_topbar("diff")

    summary_body_html = self._generate_summary_body()
    diff_body_html = self._generate_diff_body()
    summary_html = header_html + summary_topbar_html + summary_body_html + footer_html
    diff_html = header_html + diff_topbar_html + diff_body_html+ footer_html
    Reporter._make_file(summary_html, self.report_info.home_page)
    Reporter._make_file(diff_html,self.report_info.diff_page)

    log_body_html = self._generate_log_body()
    log_html = header_html + logs_topbar_html + log_body_html+footer_html
    Reporter._make_file(log_html, self.report_info.log_page)

    for config_name in self.report_info.config_to_test_names_map.keys():
      config_dir = os.path.join(self.report_info.resource_dir, config_name)
      utils.makedirs(config_dir)

      config_body_html = self._generate_config_body(config_name)
      config_html = header_html + results_topbar_html + config_body_html + footer_html
      config_file = os.path.join(config_dir, config_name + self.report_info.report_file_sfx)
      Reporter._make_file(config_html, config_file)

      for test_name in self.data_source.get_test_names(config_name):
        test_body_html = self._generate_test_body(config_name, test_name)
        test_html = header_html + results_topbar_html + test_body_html + footer_html
        test_file = os.path.join(config_dir, test_name + self.report_info.report_file_sfx)
        Reporter._make_file(test_html, test_file)
1260522
def xml_report(self, file_path):
        """"""
        self.logger.debug('Generating XML report')
        report = self.zap.core.xmlreport()
        self._write_report(report, file_path)
458334
def reporter(self, analysistype='genesippr'):
        
        logging.info('Creating {} report'.format(analysistype))
        # Create a dictionary to link all the genera with their genes
        genusgenes = dict()
        # The organism-specific targets are in .tfa files in the target path
        targetpath = str()
        for sample in self.runmetadata.samples:
            if sample.general.bestassemblyfile != 'NA':
                targetpath = sample[analysistype].targetpath
        for organismfile in glob(os.path.join(targetpath, '*.tfa')):
            organism = os.path.splitext(os.path.basename(organismfile))[0]
            # Use BioPython to extract all the gene names from the file
            for record in SeqIO.parse(open(organismfile), 'fasta'):
                # Append the gene names to the genus-specific list
                try:
                    genusgenes[organism].add(record.id.split('_')[0])
                except (KeyError, IndexError):
                    genusgenes[organism] = set()
                    genusgenes[organism].add(record.id.split('_')[0])
        # Determine from which genera the gene hits were sourced
        for sample in self.runmetadata.samples:
            # Initialise the list to store the genera
            sample[analysistype].targetgenera = list()
            if sample.general.bestassemblyfile != 'NA':
                for organism in genusgenes:
                    # Iterate through all the genesippr hits and attribute each gene to the appropriate genus
                    for gene in sample[analysistype].results:
                        # If the gene name is in the genes from that organism, add the genus name to the list of
                        # genera found in the sample
                        if gene.split('_')[0] in genusgenes[organism]:
                            if organism not in sample[analysistype].targetgenera:
                                sample[analysistype].targetgenera.append(organism)
        # Create the path in which the reports are stored
        make_path(self.reportpath)
        # The report will have every gene for all genera in the header
        header = 'Strain,Genus,{},\n'.format(','.join(self.genelist))
        data = str()
        with open(os.path.join(self.reportpath, analysistype + '.csv'), 'w') as report:
            for sample in self.runmetadata.samples:
                sample[analysistype].report_output = list()
                if sample.general.bestassemblyfile != 'NA':
                    # Add the genus/genera found in the sample
                    data += '{},{},'.format(sample.name, ';'.join(sample[analysistype].targetgenera))
                    best_dict = dict()
                    if sample[analysistype].results:
                        gene_check = list()
                        # Find the best match for all the hits
                        for target, pid in sample[analysistype].results.items():
                            gene_name = target.split('_')[0]
                            for gene in self.genelist:
                                # If the key matches a gene in the list of genes
                                if gene == gene_name:
                                    # If the percent identity is better, update the dictionary
                                    try:
                                        if float(pid) > best_dict[gene]:
                                            best_dict[gene] = float(pid)
                                    except KeyError:
                                        best_dict[gene] = float(pid)
                        for gene in self.genelist:
                            # If the gene was not found in the sample, print an empty cell in the report
                            try:
                                best_dict[gene]
                            except KeyError:
                                data += ','
                            # Print the required information for the gene
                            for name, identity in sample[analysistype].results.items():
                                if name.split('_')[0] == gene and gene not in gene_check:
                                    data += '{pid}%'.format(pid=best_dict[gene])
                                    try:
                                        if not sample.general.trimmedcorrectedfastqfiles[0].endswith('.fasta'):
                                            data += ' ({avgd} +/- {std}),'\
                                                .format(avgd=sample[analysistype].avgdepth[name],
                                                        std=sample[analysistype].standarddev[name])
                                        else:
                                            data += ','
                                    except IndexError:
                                        data += ','
                                    gene_check.append(gene)
                                    # Add the simplified results to the object - used in the assembly pipeline report
                                    sample[analysistype].report_output.append(gene)
                        # Add a newline after each sample
                        data += '\n'
                    # Add a newline if the sample did not have any gene hits
                    else:
                        data += '\n'
            # Write the header and data to file
            report.write(header)
            report.write(data)
352499
def get_pdb_sets(self):
        ''''''

        assert(self.id != None)

        data = []
        for pdb_set in self.pdb_sets:

            pdb_set_record = dict(
                PPComplexID = self.id,
                SetNumber = pdb_set['set_number'],
                IsComplex = pdb_set['is_complex'],
                Notes = pdb_set['notes'],
            )

            chain_records = []
            for side, chain_details in sorted(pdb_set['chains'].iteritems()):
                chain_records.append(dict(
                    PPComplexID = self.id,
                    SetNumber = pdb_set['set_number'],
                    Side = side,
                    ChainIndex = chain_details['chain_index'],
                    PDBFileID = chain_details['pdb_file_id'],
                    Chain = chain_details['chain_id'],
                    NMRModel = chain_details['nmr_model'],
                ))

            data.append(dict(pdb_set = pdb_set_record, chain_records = chain_records))

        return data
585323
def generate_pymol_session(self, pymol_executable = 'pymol', settings = {}):
        ''' '''
        b = BatchBuilder(pymol_executable = pymol_executable)

        structures_list = [
            (self.structure_1_name, self.scaffold_pdb.pdb_content, self.get_differing_scaffold_residue_ids()),
            (self.structure_2_name, self.model_pdb.pdb_content, self.get_differing_model_residue_ids()),
        ]

        PSE_files = b.run(ScaffoldModelDesignBuilder, [PDBContainer.from_content_triple(structures_list)], settings = settings)

        return PSE_files[0], b.PSE_scripts[0]
414157
def report_xml():
    
    arguments = docopt.docopt(report_xml.__doc__, version='cr-rate 1.0')
    with use_db(arguments['<session-file>'], WorkDB.Mode.open) as db:
        xml_elem = _create_xml_report(db)
        xml_elem.write(
            sys.stdout.buffer, encoding='utf-8', xml_declaration=True)