Example #1
0
def apply(cases: List[Case],
          prtid: int,
          prefix: Optional[str] = 'checkpoint',
          **kwargs) -> List[Case]:
    """Write the Case with all the applied modifications.
    """
    if TBcore.get_option('system', 'verbose'):
        sys.stdout.write('--- TB PLUGIN: WRITE ---\n')

    counter = '' if prtid is -1 else '.{:02d}'.format(prtid)
    paths = [c.main_path for c in cases]
    try:
        path = paths[0].resolve()
        for p in paths:
            path = path.relative_to(p.resolve())
    except ValueError:
        path = Path.cwd()

    YAML_Dumper()
    ofile = str(path.joinpath(prefix)) + counter + '.yml'
    if TBcore.get_option('system', 'verbose'):
        sys.stdout.write('Writing checkpoint file {} for {} case(s).\n'.format(
            ofile, len(cases)))
    with open(ofile, "w") as stream:
        yaml.dump_all([c.data for c in cases],
                      stream,
                      Dumper=Dumper,
                      default_flow_style=False)

    return cases
Example #2
0
def make_structure(sse1: dict, sse2: dict,
                   outfile: Path) -> Tuple[PDBFrame, PDBFrame]:
    """
    """
    sse1 = PDB(
        pd.DataFrame(sse1['metadata']['atoms'],
                     columns=[
                         'auth_comp_id', 'auth_atom_id', 'auth_seq_id',
                         'Cartn_x', 'Cartn_y', 'Cartn_z'
                     ])).renumber(1)

    sse2 = PDB(
        pd.DataFrame(sse2['metadata']['atoms'],
                     columns=[
                         'auth_comp_id', 'auth_atom_id', 'auth_seq_id',
                         'Cartn_x', 'Cartn_y', 'Cartn_z'
                     ])).renumber(sse1.iloc[-1]['auth_seq_id'] + 5)
    structure = pd.concat([sse1, sse2])
    structure['id'] = list(range(1, structure.shape[0] + 1))

    if TBcore.get_option('system', 'verbose'):
        sys.stdout.write('-> generating structure {}\n'.format(
            outfile.resolve()))
    structure.write(output_file=str(outfile),
                    format='pdb',
                    clean=True,
                    force=TBcore.get_option('system', 'overwrite'))

    return sse1, sse2
Example #3
0
def download_pdb(pdbdb: SBIdb.PDBLink, pdb3d: SBIstr.PDBFrame, pdbid: str,
                 pdbchain: str) -> Tuple[str, SBIstr.PDBFrame]:
    filename = pdbdb.store_local_path('{0}_{1}.pdb.gz'.format(pdbid, pdbchain))
    if not os.path.isfile(filename):
        if TBcore.get_option('system', 'verbose'):
            sys.stdout.write('  Downloading PDB {}\n'.format(pdbid))
        pdb3d = SBIstr.PDB('fetch:{0}'.format(pdbid),
                           format='pdb',
                           clean=True,
                           dehydrate=True,
                           hetatms=False)['Chain:{}'.format(pdbchain)]
        pdb3d.write(filename, format='pdb')
        return filename, pdb3d

    if TBcore.get_option('system', 'verbose'):
        sys.stdout.write('  {} already exists\n'.format(filename))
    if pdb3d is None or pdb3d.id != '{0}_{1}'.format(pdbid, pdbchain):
        pdb3d = SBIstr.PDB('fetch:{0}'.format(pdbid),
                           format='pdb',
                           clean=True,
                           dehydrate=True,
                           hetatms=False)['Chain:{}'.format(pdbchain)]
        return filename, pdb3d
    else:
        return filename, pdb3d
Example #4
0
def execute(log: Logger, data: Dict, wpaths: Dict) -> Dict:
    """Run Rosetta.
    """
    if TBcore.get_option('slurm', 'use'):
        slurm_file = wpaths['main'].joinpath('submit_hybridize.sh')
        TButil.plugin_filemaker('Submission file at {}'.format(slurm_file))
        with slurm_file.open('w') as fd:
            fd.write(TButil.slurm_header() + '\n')
            for k in ['assembly', 'design']:
                cmd = [
                    'srun',
                ]
                cmd.extend(data['cmd'][k])
                fd.write(' '.join([str(x) for x in cmd]) + '\n')

        if TBcore.get_option('system', 'verbose'):
            sys.stdout.write(
                'Submiting jobs to SLURM... this might take a while\n')
        TButil.submit_slurm(slurm_file)
    else:
        for k in ['assembly', 'design']:
            log.notice(
                f'EXECTUE: {" ".join([str(x) for x in data["cmd"][k]])}')
            run([str(x) for x in data['cmd'][k]], stdout=DEVNULL)
    return data
Example #5
0
def apply(cases: List[Case],
          prtid: int,
          loop_range: int = 3,
          top_loops: int = 20,
          harpins_2: bool = True,
          rmsd_cut: float = 5.0,
          **kwargs) -> List[Case]:
    """Use MASTER to cover the transitions between secondary structures.

    And something else.
    """
    if TBcore.get_option('system', 'verbose'):
        sys.stdout.write('--- TB PLUGIN: LOOP_MASTER ---\n')

    # Get list of PDS structures
    tempdb = False
    database = core.get_option('master', 'pds')
    database = Path(database)
    if database.is_file():
        pass
    elif database.is_dir():
        f = NamedTemporaryFile(mode='w', delete=False)
        if TBcore.get_option('system', 'debug'):
            sys.stdout.write('Temporary file for PDS database: {}\n'.format(
                f.name))
        [f.write(str(x.resolve()) + '\n') for x in database.glob('*/*.pds')]
        f.close()
        database = Path(f.name)
        tempdb = True
    else:
        raise ValueError(
            'The provided MASTER database directory/list file cannot be found.'
        )

    # Get ABEGOS
    abegodata = get_abegos()

    # Get FragFiles
    fragfiles = get_fragfiles()

    # Execute for each case
    for i, case in enumerate(cases):
        cases[i].data.setdefault('metadata',
                                 {}).setdefault('loop_fragments', [])
        cases[i].data.setdefault('metadata', {}).setdefault('loop_lengths', [])
        cases[i] = case_apply(case, database, loop_range, top_loops, rmsd_cut,
                              abegodata, harpins_2, fragfiles)
        cases[i] = cases[i].set_protocol_done(prtid)

    if tempdb:
        os.unlink(f.name)

    return cases
Example #6
0
def apply(cases: List[Case],
          prtid: int,
          outfile: Optional[Union[str, Path]] = None,
          prefix: Optional[str] = None,
          plot_types: Optional[List[str]] = None,
          **kwargs) -> List[Case]:
    """Generate visual representations of the Case.
    """
    TButil.plugin_title(__file__, len(cases))

    # File management
    if outfile is None:
        outfile = cases[0].main_path.joinpath('images').resolve()
        outfile.mkdir(parents=True, exist_ok=True)
    if isinstance(outfile, str):
        outfile = Path(outfile).resolve()

    outformat = TBcore.get_option('system', 'image')

    # Checking available plot_types
    plot_types = [
        _PLT_TYPES_[0],
    ] if plot_types is None else plot_types
    if len(set(plot_types).difference(_PLT_TYPES_)) > 0:
        raise ValueError('Requested unknown plot format. '
                         'Available are: {}'.format(','.join(_PLT_TYPES_)))

    for ptype in plot_types:
        if outfile.is_dir():
            prefix = prefix if prefix is not None else ".".join(
                [str(os.getppid()), '{:02d}'.format(prtid)])
            thisoutfile = outfile.joinpath(".".join(
                [prefix, ptype + outformat]))
        else:
            thisoutfile = Path(str(outfile) + '.' + ptype + outformat)
        thisoutfile.parent.mkdir(parents=True, exist_ok=True)
        if not TBcore.get_option('system',
                                 'overwrite') and thisoutfile.is_file():
            sys.stderr.write(
                'Unable to overwrite file {}: Already exists\n'.format(
                    thisoutfile))
            continue

        fig, ax = getattr(pts, ptype)(cases, **kwargs.pop(ptype, {}))
        plt.tight_layout()
        plt.savefig(str(thisoutfile), dpi=300)

        TButil.plugin_imagemaker('Creating new image at: {}'.format(
            str(thisoutfile)))

    for i, case in enumerate(cases):
        cases[i] = case.set_protocol_done(prtid)
    return cases
Example #7
0
 def execute(row, structures, flip):
     # 1. Download file
     nonlocal pdbdb
     nonlocal pdb3d
     filename, pdb3d = download_pdb(pdbdb, pdb3d, row['pdb'], row['chain'])
     pdb3d = pdb3d['AtomType:CA']
     df = TButil.pdb_geometry_from_rules(
         pdb3d, list(zip(structures, row['match'], flip)))
     df = df.assign(pdb=[
         row['pdb'],
     ] * df.shape[0])
     df = df.assign(chain=[
         row['chain'],
     ] * df.shape[0])
     df = df.assign(rmsd=[
         row['rmsd'],
     ] * df.shape[0])
     df = df.assign(match=[
         row['match'],
     ] * df.shape[0])
     df['pdb_path'] = [
         filename,
     ] * df.shape[0]
     if TBcore.get_option('system', 'verbose'):
         sys.stdout.flush()
     return df
Example #8
0
def pds_database( force: Optional[bool] = False ) -> Tuple[Path, List]:
    """Provide the list of available PDS as a file and a list.

    :param bool force: When :data:`.True`, recheck the PDS database even if one is
        already assigned.

    .. note::
        Depends onf the ``master.pds`` configuration option
    """
    global pds_file
    global pds_list

    if not force:
        if pds_file is not None and pds_list is not None:
            return pds_file, pds_list

    pds_file = TBcore.get_option('master', 'pds')
    pds_list = []
    pds_file = Path(pds_file)
    if pds_file.is_file():
        pds_list = [line.strip() for line in open(pds_file).readlines() if len(line.strip()) > 0]
        return pds_file, pds_list
    elif pds_file.is_dir():
        pds_list = [str(x.resolve()) for x in pds_file.glob('*/*.pds')]
        f = NamedTemporaryFile(mode='w', delete=False)
        plugin_filemaker('Temporary file for PDS database: {}'.format(f.name))
        [f.write(x + '\n') for x in pds_list]
        f.close()
        pds_file = Path(f.name)
        return pds_file, pds_list
    else:
        raise ValueError('The provided MASTER database directory/list file cannot be found.')
Example #9
0
def pds_database( log: Logger,
                  filter: Optional[Union[str, Path]] = None,
                  ) -> Tuple[Path, List]:
    """Provide the list of target PDS as a file and a list.

    .. note::
        Depends on the ``master.pds`` configuration option.

    :param log: Job logger.
    :param filter: File containting the target subset, otherwise all PDS database is considered.
    """
    # @TODO: PDS-FILTER
    pds_file = Path(TBcore.get_option('master', 'pds'))
    if pds_file.is_file():
        pds_list = [line.strip() for line in open(pds_file).readlines() if len(line.strip()) > 0]
    elif pds_file.is_dir():
        pds_list = [str(x.resolve()) for x in pds_file.glob('*/*.pds')]
    else:
        raise NodeDataError('The provided MASTER database directory/list file cannot be found.')

    # Even if a PDS file already exists, we always create a temporary file so that we can
    # manage different versions of the PDS database in different Nodes.
    f = NamedTemporaryFile(mode='w', delete=False)
    log.info(f'Temporary file for PDS database: {f.name}')
    [f.write(x + '\n') for x in pds_list]
    f.close()
    pds_file = Path(f.name)
    return pds_file, pds_list
Example #10
0
def plot_match_bin(master_match: pd.DataFrame,
                   prefix: Union[Path, str],
                   expected: Union[int, float],
                   groupby: Optional[List] = None,
                   write: bool = True) -> Tuple[plt.Figure, Path]:
    """
    """
    fig = plt.figure(figsize=[15, 5])
    ax = plt.subplot2grid((1, 1), (0, 0), fig=fig)

    master_match = master_match.sort_values('rmsd')
    df = master_match.groupby(groupby).head(
        1) if groupby is not None else master_match

    bins = ['close', 'mid', 'far', 'extreme']
    sns.countplot(x="bin", data=df, ax=ax, order=bins, palette="Set3")
    ax.set_xticklabels(
        ['close\n[0, 2)', 'mid\n[2, 2.5)', 'far\n[2.5, 3)', 'extreme\n[3, 5)'])
    ax.set_ylim(top=expected)
    match_count = []
    for p in ax.patches:
        pp = int(0 if math.isnan(p.get_height()) else p.get_height())
        ypos = pp + 1000 if pp + 1000 < expected - 500 else pp - 1000
        ax.annotate('{:d}'.format(pp), (p.get_x() + 0.37, ypos))
        match_count.append(bool(pp))
    plt.tight_layout()

    imagename = Path(str(prefix) + TBcore.get_option('system', 'image'))
    if write:
        plugin_imagemaker('MASTER match image summary at {}'.format(imagename))
        plt.savefig(imagename, dpi=300)
    return fig, imagename, dict(zip(bins, match_count))
Example #11
0
def build_pdb_object(
        sses: List[Dict], loops: Union[List[int],
                                       int]) -> Tuple[Frame3D, List[int]]:
    """
    """
    if isinstance(loops, int):
        loops = [
            loops,
        ] * (len(sses) - 1)
    if len(sses) != len(loops) + 1:
        raise ValueError(
            'Number of loops should equal number of SSE minus one.')

    pieces = []
    columns = [
        'auth_comp_id', 'auth_atom_id', 'auth_seq_id', 'Cartn_x', 'Cartn_y',
        'Cartn_z'
    ]
    start = 1
    for i, sse in enumerate(sses):
        start = 1 if i == 0 else int(sses[i - 1]['length']) + loops[i -
                                                                    1] + start
        if TBcore.get_option('system', 'verbose'):
            sys.stdout.write(
                'PDB: Building SSE {:02d}:{} starting at {}\n'.format(
                    i + 1, sse['id'], start))
        pieces.append(
            PDB(pd.DataFrame(sse['metadata']['atoms'],
                             columns=columns)).renumber(start))

    structure = pd.concat(pieces, sort=False).reset_index()
    structure['id'] = list(range(1, structure.shape[0] + 1))
    return structure, [int(p.iloc[-1]['auth_seq_id']) for p in pieces]
Example #12
0
def plot_angle_network(log: Logger,
                       network: nx.DiGraph,
                       node_positions: Dict,
                       sse_list: List[str],
                       prefix: Union[Path, str],
                       write: bool = True) -> Tuple[plt.Figure, Path]:
    """Plots the per SSE geometrical distributions from the :ref:`MASTER` search.

    :param log: Job Logger.
    :param network: Network Graph to use for angle network.
    :param node_positions: Positions of the nodes (SSEs).
    :param sse_list: The SSEs to be considered.
    :param prefix: Prefix for plot name.
    :param write: Shall the plot by saved (default: True).
    """
    fig = plt.figure(figsize=[25, 25])
    ax = plt.subplot2grid((1, 1), (0, 0), fig=fig)

    nx.draw(network, pos=node_positions, ax=ax)
    ax.set_axis_on()
    ax.set_xticks(range(len(sse_list)))
    ax.set_xticklabels(sse_list)
    ax.set_xlabel('SSE')
    ax.set_ylabel('zeta angle')
    plt.tight_layout()

    imagename = Path(str(prefix) + TBcore.get_option('system', 'image'))
    if write:
        log.notice(f'Layer angle network image summary at {imagename}')
        plt.savefig(imagename, dpi=300)
    return fig, imagename
Example #13
0
def plot_loop_length_distribution(
        log: Logger,
        dfloop: pd.DataFrame,
        pick: int,
        prefix: Union[Path, str],
        title: str,
        write: bool = True) -> Tuple[plt.Figure, Path]:
    """Plots the loop length count distribution for a jump.

    :param log: Job Logger.
    :param dfloop: Loop set for a particular jump.
    :param pick: The selected length that was picked (for annotation on the plot).
    :param prefix: Prefix for plot name.
    :param title: Plot title.
    :param write: Shall the plot by saved (default: True).
    """
    fig = plt.figure()
    ax = plt.subplot2grid((1, 1), (0, 0), fig=fig)
    sns.countplot(x='loop_length', data=dfloop, ax=ax, palette="PRGn")
    cnt = dfloop[dfloop['loop_length'] == pick]['length_count'].values[0]
    pick = [int(x.get_text()) for x in ax.get_xticklabels()].index(pick)
    ax.plot(pick, cnt, marker=11, color='black')
    ax.set_title(title)
    plt.tight_layout()

    imagename = Path(str(prefix) + TBcore.get_option('system', 'image'))
    if write:
        log.notice(f'loop image summary at {imagename}')
        plt.savefig(imagename, dpi=300)
    return fig, imagename
Example #14
0
def plugin_warning(text: str):
    """Format a warning and manage follow up behaviour.

    :param str text: Warning text.
    """
    sys.stdout.write(cl.Fore.GREEN + str(text) + '\n')
    if TBcore.get_option('system', 'strict'):
        sys.exit(-1)
Example #15
0
def sketchXZ(cases: List[Case], **kwargs) -> Tuple[plt.Figure, List[plt.Axes]]:
    """
    """
    grid = _calculate_grid(cases, **kwargs)

    if TBcore.get_option('system', 'verbose'):
        sys.stdout.write('Generating an image grid of: {0}x{1}\n'.format(
            grid[0], grid[1]))

    fsize = (kwargs.pop('width',
                        7.5 * grid[1]), kwargs.pop('hight', 7.5 * grid[0]))
    fig = plt.figure(figsize=fsize)
    axs = []
    ylim, xlim = [0, 0], [0, 0]
    for i, case in enumerate(cases):
        position = (int(i / grid[1]), i % grid[1])
        title = '{0}_{1:03d}'.format(case['configuration.name'], i + 1)
        if TBcore.get_option('system', 'verbose'):
            sys.stdout.write('Showing {0}-{3} in position: {1}x{2}\n'.format(
                title, position[0], position[1], case.architecture_str))

        ax = plt.subplot2grid(grid, position, fig=fig)
        axs.append(ax)
        plot_case_sketch(case, ax, kwargs.pop('connections', False),
                         kwargs.pop('beta_fill', 'red'),
                         kwargs.pop('beta_edge', 'black'),
                         kwargs.pop('alpha_fill', 'blue'),
                         kwargs.pop('alpha_edge', 'black'),
                         kwargs.pop('connection_edge', None))
        ax.set_title(title)
        cy = ax.get_ylim()
        cx = ax.get_xlim()
        ylim = [
            ylim[0] if cy[0] < ylim[0] else cy[0],
            ylim[1] if cy[1] > ylim[1] else cy[1]
        ]
        xlim = [
            xlim[0] if cx[0] > xlim[0] else cx[0],
            xlim[1] if cx[1] < xlim[1] else cx[1]
        ]

    for ax in axs:
        ax.set_ylim(ylim[0], ylim[1])
        ax.set_xlim(xlim[0], xlim[1])

    return fig, axs
Example #16
0
def checkpoint_out(filename: Union[Path, str], data: Dict):
    """
    """
    filename = Path(filename)

    if TBcore.get_option('system', 'verbose'):
        sys.stdout.write('CHECKPOINT: Creating at {}\n'.format(filename))
    with filename.open('w') as fd:
        json.dump(data, fd, cls=GeneralEncoder)
Example #17
0
def plugin_filereader(text: str):
    """Highlight the loading of files.

    :param str text: File reading text.
    """
    if TBcore.get_option('system', 'verbose'):
        sys.stdout.write(cl.Fore.BLUE + cl.Back.WHITE + 'READ FILE: ' +
                         str(text))
        sys.stdout.write(cl.Style.RESET_ALL + '\n')
Example #18
0
def plugin_imagemaker(text: str):
    """Highlight the creation of new plot files.

    :param str text: File creation text.
    """
    if TBcore.get_option('system', 'verbose'):
        sys.stdout.write(cl.Fore.GREEN + cl.Back.BLUE + 'NEW PLOT: ' +
                         str(text))
        sys.stdout.write(cl.Style.RESET_ALL + '\n')
Example #19
0
def make_pieces(pdb3d: Frame3D, rules: List[Tuple]) -> Dict:
    """
    """
    pieces = {}
    for piece in rules:
        sse_id, ranges, _ = piece
        if TBcore.get_option('system', 'debug'):
            sys.stdout.write('PDB:Individualize SSE:{} of {}\n'.format(
                sse_id, pdb3d.id))
        with SBIcr.on_option_value('structure', 'source', 'label'):
            segment = pdb3d['Residue:{0}-{1}'.format(ranges[0], ranges[1])]
            pieces.setdefault(sse_id, {}).setdefault('atoms', segment)
        with SBIcr.on_option_value('structure', 'source', 'auth'):
            if TBcore.get_option('system', 'verbose'):
                first, last = segment.first_compound.number, segment.last_compound.number
                sys.stdout.write('PDB:{2} - Range: {0}-{1}\n'.format(
                    first, last, pdb3d.id))
    return pieces
Example #20
0
def checkpoint_in(filename: Union[Path, str]) -> Optional[Dict]:
    """
    """
    if TBcore.get_option('system', 'forced'):
        return None

    filename = Path(filename)
    if filename.is_file():
        if TBcore.get_option('system', 'verbose'):
            sys.stdout.write(
                'CHECKPOINT: Reloading from {}\n'.format(filename))
        with Path(filename).open() as fd:
            try:
                data = json.load(fd)
            except json.JSONDecodeError:
                return None
        return data

    return None
Example #21
0
def plugin_case_count(cases: int, io='o'):
    """Print on-screen the current number of cases.

    :param int cases: Current number of cases.
    :param str io: If ``i``: input. If ``o``: output
    """
    if TBcore.get_option('system', 'verbose'):
        io = 'batch applied to' if io == 'i' else 'generated a total of'
        sys.stdout.write(cl.Style.DIM +
                         '* {} {:03d} cases\n\n'.format(io, cases))
Example #22
0
def get_master_exes() -> Tuple[str, str]:
    """Provide the path to the MASTER executables.

    .. note::
        Depends onf the ``master.master`` configuration option
        Depends onf the ``master.create`` configuration option
    """
    global create_exe
    global master_exe

    if create_exe is not None and master_exe is not None:
        return master_exe, create_exe

    master_exe = TBcore.get_option('master', 'master')
    if not os.access(master_exe, os.X_OK):
        raise IOError('Unable to find a proper executable for master at {}'.format(master_exe))
    create_exe = TBcore.get_option('master', 'create')
    if not os.access(create_exe, os.X_OK):
        raise IOError('Unable to find a proper executable for createPDS at {}'.format(create_exe))
    return master_exe, create_exe
Example #23
0
    def execute(self, data: List[Dict]) -> List[Dict]:
        kase = Case(data[0])

        # File management
        if self.outfile is None:
            self.outfile = kase.main_path.joinpath('images').resolve()
            self.outfile.mkdir(parents=True, exist_ok=True)
        if isinstance(self.outfile, str):
            self.outfile = Path(self.outfile).resolve()

        # Get output format
        outformat = TBcore.get_option('system', 'image')

        for ptype in self.plot_types:
            if self.outfile.is_dir():
                self.prefix = self.prefix if self.prefix is not None else ".".join(
                    [str(os.getppid()), f'{ptype}'])
                thisoutfile = self.outfile.joinpath(".".join(
                    [self.prefix, ptype + outformat]))
            else:
                thisoutfile = Path(str(self.outfile) + '.' + ptype + outformat)
            thisoutfile.parent.mkdir(parents=True, exist_ok=True)
            if not TBcore.get_option('system',
                                     'overwrite') and thisoutfile.is_file():
                self.log.warning(
                    f'Unable to overwrite file {thisoutfile}: Already exists')
                continue

            if not self.plot_params[ptype]:
                fig, ax = getattr(pts, ptype)(self.log,
                                              [Case(i) for i in data])
            else:
                fig, ax = getattr(pts,
                                  ptype)(self.log, [Case(i) for i in data],
                                         self.plot_params[ptype])
            plt.tight_layout()
            plt.savefig(str(thisoutfile), dpi=300)

            self.log.info(f'Creating new image at: {str(thisoutfile)}')
            return data
Example #24
0
def execute(cmd: List, wfolder: Path):
    """
    """
    if not TBcore.get_option('slurm', 'use'):
        run(cmd)
    else:
        slurm_file = wfolder.joinpath('submit_analytics.sh')
        with slurm_file.open('w') as fd:
            fd.write(TButil.slurm_header() + '\n')
            fd.write(TButil.slurm_pyenv() + '\n')
            for c in cmd:
                fd.write(' '.join([str(x) for x in c]) + '\n')
        TButil.submit_slurm(slurm_file)
Example #25
0
def sketchXY(cases: List[Case], **kwargs) -> Tuple[plt.Figure, List[plt.Axes]]:
    """
    """
    grid = list(_calculate_grid(cases, **kwargs))
    lcount = max([len(c.shape) for c in cases])
    grid[0] = grid[0] * lcount

    if TBcore.get_option('system', 'verbose'):
        sys.stdout.write('Generating an image grid of: {0}x{1}\n'.format(
            grid[0], grid[1]))

    fsize = (kwargs.pop('width', 7.5 * grid[1]),
             kwargs.pop('hight', 7.5 * grid[0] / lcount))
    fig = plt.figure(figsize=fsize)
    axs = []
    # ylim, xlim = [0, 0], [0, 0]
    for i, case in enumerate(cases):
        position = (int(i / grid[1]), i % grid[1])
        title = '{0}_{1:03d}'.format(case['configuration.name'], i + 1)
        if TBcore.get_option('system', 'verbose'):
            sys.stdout.write('Showing {0}-{3} in position: {1}x{2}\n'.format(
                title, position[0], position[1], case.architecture_str))

        lcaxs = []
        for xx in range(lcount):
            p = list(copy.deepcopy(position))
            p[0] += xx
            lcaxs.append(plt.subplot2grid(grid, p, fig=fig))
        axs.extend(lcaxs)
        plot_case_sketch_vertical(case, lcaxs,
                                  kwargs.pop('connections', False),
                                  kwargs.pop('beta_fill', 'red'),
                                  kwargs.pop('beta_edge', 'black'),
                                  kwargs.pop('alpha_fill', 'blue'),
                                  kwargs.pop('alpha_edge', 'black'))
        for xx in lcaxs:
            xx.set_title(title + ' - ' + xx.get_title())

    return fig, axs
Example #26
0
def plot_geometric_distributions(
        log: Logger,
        df: pd.DataFrame,
        prefix: Union[Path, str],
        write: bool = True) -> Tuple[plt.Figure, Path]:
    """Plots the per SSE geometrical distributions from the :ref:`MASTER` search.

    :param log: Job Logger.
    :param df: Calculated geometric statistics from the :ref:`MASTER` search.
    :param prefix: Prefix for plot name.
    :param write: Shall the plot by saved (default: True).
    """
    ordering = sorted(df.sse.unique())
    fig = plt.figure(figsize=[15, 15])
    grid = (3, 2)

    for i, l in enumerate(['layer', 'floor', 'side']):
        ax = plt.subplot2grid(grid, (i, 0), fig=fig)
        sns.violinplot(x='sse',
                       y=f'angles_{l}',
                       hue='bin',
                       data=df,
                       palette="Set3",
                       order=ordering,
                       ax=ax,
                       cut=1)
        ax.legend().remove()
        ax.set_ylabel('angle')
        ax.set_title(f'angles_{l}')
        ax = plt.subplot2grid(grid, (i, 1), fig=fig)
        sns.violinplot(x='sse',
                       y='points_{}'.format(l),
                       hue='bin',
                       data=df,
                       palette="Set3",
                       order=ordering,
                       ax=ax,
                       cut=0)
        ax.set_ylabel('distance')
        ax.set_title(f'points_{l}')
        if i != 0:
            ax.legend().remove()
        else:
            ax.legend(ncol=len(df.bin.unique()))
    plt.tight_layout()

    imagename = Path(str(prefix) + TBcore.get_option('system', 'image'))
    if write:
        log.notice(f'Geometric distributions image summary at {imagename}')
        plt.savefig(imagename, dpi=300)
    return fig, imagename
Example #27
0
def apply(cases: List[Case], prtid: int, protocol: str,
          **kwargs) -> List[Case]:
    """Generates final fragment files for the full structure.
    """
    if TBcore.get_option('system', 'verbose'):
        sys.stdout.write('--- TB PLUGIN: FRAGMENT_MAKER ---\n')

    # Execute for each case
    for i, case in enumerate(cases):
        cases[i].data.setdefault('metadata', {}).setdefault('fragments', {})
        cases[i] = case_apply(case, protocol)
        cases[i] = cases[i].set_protocol_done(prtid)

    return cases
Example #28
0
def execute_master_fixedgap(outfile: Path, pds_list: Path, mdis: int,
                            Mdis: int, rmsd_cut: float):
    """
    """
    createPDS = core.get_option('master', 'create')
    createbash = '{0} --type query --pdb {1} --pds {2}'
    master = core.get_option('master', 'master')
    masterbash = '{0} --query {1} --targetList {2} --rmsdCut {6} --matchOut {3} --gapLen {4}-{5}'

    createcmd = shlex.split(
        createbash.format(createPDS, outfile, outfile.with_suffix('.pds')))
    mastercmd = shlex.split(
        masterbash.format(master, outfile.with_suffix('.pds'), pds_list,
                          outfile.with_suffix('.master'), mdis, Mdis,
                          rmsd_cut))
    if TBcore.get_option('system', 'verbose'):
        sys.stdout.write('-> Execute: {}\n'.format(' '.join(createcmd)))
    with open(os.devnull, 'w') as devnull:
        run(createcmd, stdout=devnull)
    if TBcore.get_option('system', 'verbose'):
        sys.stdout.write('-> Execute: {}\n'.format(' '.join(mastercmd)))
    with open(os.devnull, 'w') as devnull:
        run(mastercmd, stdout=devnull)
Example #29
0
def get_fragfiles():
    """
    """
    fragpath = Path(core.get_option('master', 'fragments'))
    if TBcore.get_option('system', 'debug'):
        sys.stdout.write('Listing available fragment files at: {}\n'.format(
            fragpath.name))
    if not fragpath.is_dir():
        raise IOError('MASTER fragments folder cannot be found.')
    return pd.DataFrame(
        [(x.name[:4], x.name[5:6], x, y)
         for x, y in zip(sorted(fragpath.glob('*/*3mers.gz')),
                         sorted(fragpath.glob('*/*9mers.gz')))],
        columns=['pdb', 'chain', '3mers', '9mers'])
Example #30
0
def plugin_bash(text: Union[List[List], List[str]]):
    """Show prepared bash statements to execute.

    :param text: List of statements to show.
    """
    if TBcore.get_option('system', 'verbose'):
        if isinstance(text[0], str):
            sys.stdout.write(cl.Fore.RED + cl.Back.CYAN + 'BASH: ' +
                             ' '.join([str(x) for x in text]))
        else:
            for cmd in text:
                sys.stdout.write(cl.Fore.RED + cl.Back.CYAN + 'BASH: ' +
                                 ' '.join([str(x) for x in cmd]) + '\n')
        sys.stdout.write(cl.Style.RESET_ALL + '\n')