Exemple #1
0
def main():

    args = parse_args()
    try:
        os.makedirs(args.directory)
    except OSError:
        pass

    target = Volume.fromfile(args.target)
    structure = Structure.fromfile(args.template)
    center = structure.coor.mean(axis=1)
    radius = np.linalg.norm((structure.coor - center.reshape(-1, 1)), axis=0).max() + 0.5 * args.resolution

    template = zeros_like(target)
    rottemplate = zeros_like(target)
    mask = zeros_like(target)
    rotmask = zeros_like(target)
    structure_to_shape(structure.coor, args.resolution, out=template, shape='vol', weights=structure.atomnumber)
    structure_to_shape(structure.coor, args.resolution, out=mask, shape='mask')

    if args.laplace:
        target.array = laplace(target.array, mode='constant')
        template.array = laplace(template.array, mode='constant')
    if args.core_weighted:
        mask.array = determine_core_indices(mask.array)

    # Normalize the template density
    ind = mask.array != 0
    N = ind.sum()
    template.array *= mask.array
    template.array[ind] -= template.array[ind].mean()
    template.array[ind] /= template.array[ind].std()

    rotmat = quat_to_rotmat(proportional_orientations(args.angle)[0])

    lcc_list = []
    center -= target.origin
    center /= template.voxelspacing
    radius /= template.voxelspacing
    time0 = time()
    for n, rot in enumerate(rotmat):
        rotate_grid(template.array, rot, center, radius, rottemplate.array)
        rotate_grid(mask.array, rot, center, radius, rotmask.array, nearest=True)
        lcc = calc_lcc(target.array, rottemplate.array, rotmask.array, N)
        lcc_list.append(lcc)
        print '{:d}              \r'.format(n),

    print 'Searching took: {:.0f}m {:.0f}s'.format(*divmod(time() - time0, 60))
    ind = np.argsort(lcc_list)[::-1]
    with open(os.path.join(args.directory, args.outfile), 'w') as f:
        line = ' '.join(['{:.4f}'] + ['{:7.4f}'] * 9) + '\n'
        for n in xrange(min(args.nsolutions, len(lcc_list))):
            f.write(line.format(lcc_list[ind[n]], *rotmat[ind[n]].ravel()))
Exemple #2
0
import sys

import numpy as np
from numpy.fft import fftn

from powerfit import Volume
from powerfit._powerfit import fsc_curve

vol1 = Volume.fromfile(sys.argv[1])
vol2 = Volume.fromfile(sys.argv[2])

ft_vol1 = fftn(vol1.array)
ft_vol2 = fftn(vol2.array)

fsc = fsc_curve(ft_vol1, ft_vol2)
res = [n / vol1.dimensions[0] for n in xrange(fsc.size)]
inv_res = [1 / r for r in res[1:]]

print fsc
print
print res
print
print inv_res

Exemple #3
0
def main():

    time0 = time()
    args = parse_args()
    mkdir_p(args.directory)
    # Configure logging file
    logging.basicConfig(filename=join(args.directory, 'powerfit.log'),
                        level=logging.INFO,
                        format='%(asctime)s %(message)s')
    logging.info(' '.join(argv))

    # Get GPU queue if requested
    queues = None
    if args.gpu:
        import pyopencl as cl
        p = cl.get_platforms()[0]
        devs = p.get_devices()
        context = cl.Context(devices=devs)
        # For clFFT each queue should have its own Context
        queues = [cl.CommandQueue(context, device=dev) for dev in devs]

    write('Target file read from: {:s}'.format(abspath(args.target.name)))
    target = Volume.fromfile(args.target)
    write('Target resolution: {:.2f}'.format(args.resolution))
    resolution = args.resolution
    write(('Initial shape of density:' + ' {:d}' * 3).format(*target.shape))
    # Resample target density if requested
    if not args.no_resampling:
        factor = 2 * args.resampling_rate * target.voxelspacing / resolution
        if factor < .9:
            target = resample(target, factor)
            write(('Shape after resampling:' +
                   ' {:d}' * 3).format(*target.shape))
    # Trim target density if requested
    if not args.no_trimming:
        if args.trimming_cutoff is None:
            args.trimming_cutoff = target.array.max() / 10
        target = trim(target, args.trimming_cutoff)
        write(('Shape after trimming:' + ' {:d}' * 3).format(*target.shape))
    # Extend the density to a multiple of 2, 3, 5, and 7 for clFFT
    extended_shape = [nearest_multiple2357(n) for n in target.shape]
    target = extend(target, extended_shape)
    write(('Shape after extending:' + ' {:d}' * 3).format(*target.shape))

    # Read in structure or high-resolution map
    write('Template file read from: {:s}'.format(abspath(args.template.name)))
    structure = Structure.fromfile(args.template)
    if args.chain is not None:
        write('Selecting chains: ' + args.chain)
        structure = structure.select('chain', args.chain.split(','))
    if structure.data.size == 0:
        raise ValueError("No atoms were selected.")

    # Move structure to origin of density
    structure.translate(target.origin - structure.coor.mean(axis=1))
    template = structure_to_shape_like(target,
                                       structure.coor,
                                       resolution=resolution,
                                       weights=structure.atomnumber,
                                       shape='vol')
    mask = structure_to_shape_like(target,
                                   structure.coor,
                                   resolution=resolution,
                                   shape='mask')

    # Read in the rotations to sample
    write('Reading in rotations.')
    q, w, degree = proportional_orientations(args.angle)
    rotmat = quat_to_rotmat(q)
    write('Requested rotational sampling density: {:.2f}'.format(args.angle))
    write('Real rotational sampling density: {:}'.format(degree))

    # Apply core-weighted mask if requested
    if args.core_weighted:
        write('Calculating core-weighted mask.')
        mask.array = determine_core_indices(mask.array)

    pf = PowerFitter(target, laplace=args.laplace)
    pf._rotations = rotmat
    pf._template = template
    pf._mask = mask
    pf._nproc = args.nproc
    pf.directory = args.directory
    pf._queues = queues
    if args.gpu:
        write('Using GPU-accelerated search.')
    else:
        write('Requested number of processors: {:d}'.format(args.nproc))
    write('Starting search')
    time1 = time()
    pf.scan()
    write(
        'Time for search: {:.0f}m {:.0f}s'.format(*divmod(time() - time1, 60)))

    write('Analyzing results')
    # calculate the molecular volume of the structure
    mv = structure_to_shape_like(
        target,
        structure.coor,
        resolution=resolution,
        radii=structure.rvdw,
        shape='mask').array.sum() * target.voxelspacing**3
    z_sigma = fisher_sigma(mv, resolution)
    analyzer = Analyzer(pf._lcc,
                        rotmat,
                        pf._rot,
                        voxelspacing=target.voxelspacing,
                        origin=target.origin,
                        z_sigma=z_sigma)

    write('Writing solutions to file.')
    Volume(pf._lcc, target.voxelspacing,
           target.origin).tofile(join(args.directory, 'lcc.mrc'))
    analyzer.tofile(join(args.directory, 'solutions.out'))

    write('Writing PDBs to file.')
    n = min(args.num, len(analyzer.solutions))
    write_fits_to_pdb(structure,
                      analyzer.solutions[:n],
                      basename=join(args.directory, 'fit'))

    write('Total time: {:.0f}m {:.0f}s'.format(*divmod(time() - time0, 60)))
Exemple #4
0
def main():

    time0 = clock()
    args = parse_args()
    mkdir_p(args.directory)
    # Configure logging file
    logging.basicConfig(filename=join(args.directory, 'powerfit.log'), 
            level=logging.INFO, format='%(asctime)s %(message)s')
    logging.info(' '.join(argv))

    # Get GPU queue if requested
    queues = None
    if args.gpu:
        import pyopencl as cl
        p = cl.get_platforms()[0]
        devs = p.get_devices()
        ctx = cl.Context(devices=devs)
        # For clFFT each queue should have its own Context
        contexts = [cl.Context(devices=[dev]) for dev in devs]
        queues = [cl.CommandQueue(ctx, device=dev) for ctx, dev in zip(contexts, devs)]

    write('Target file read from: {:s}'.format(abspath(args.target.name)))
    target = Volume.fromfile(args.target)
    write('Target resolution: {:.2f}'.format(args.resolution))
    resolution = args.resolution
    write(('Initial shape of density:' + ' {:d}'*3).format(*target.shape))
    # Resample target density if requested
    if not args.no_resampling:
        factor = 2 * args.resampling_rate * target.voxelspacing / resolution
        if factor < .9:
            target = resample(target, factor)
            write(('Shape after resampling:' + ' {:d}'*3).format(*target.shape))
    # Trim target density if requested
    if not args.no_trimming:
        if args.trimming_cutoff is None:
            args.trimming_cutoff = target.array.max() / 10
        target = trim(target, args.trimming_cutoff)
        write(('Shape after trimming:' + ' {:d}'*3).format(*target.shape))
    # Extend the density to a multiple of 2, 3, 5, and 7 for clFFT
    extended_shape = [nearest_multiple2357(n) for n in target.shape]
    target = extend(target, extended_shape)
    write(('Shape after extending:' + ' {:d}'*3).format(*target.shape))

    # Read in structure or high-resolution map
    if args.ft_template == 'pdb':
        write('Template file read from: {:s}'.format(abspath(args.template.name)))
        structure = Structure.fromfile(args.template)
        if args.chain is not None:
            write('Selecting chains: ' + args.chain)
            structure = structure.select('chain', args.chain.split(','))
        if structure.data.size == 0:
            raise ValueError("No atoms were selected.")

        template = structure_to_shape_like(
              target, structure.coor, resolution=resolution,
              weights=structure.atomnumber, shape='vol'
              )
        mask = structure_to_shape_like(
              target, structure.coor, resolution=resolution, shape='mask'
              )
    elif args.ft_template == 'map':
        template_high_res = Volume.fromfile(args.template)
        #TODO handle correctly

    # Read in the rotations to sample
    write('Reading in rotations.')
    q, w, degree = proportional_orientations(args.angle)
    rotmat = quat_to_rotmat(q)
    write('Requested rotational sampling density: {:.2f}'.format(args.angle))
    write('Real rotational sampling density: {:}'.format(degree))

    # Apply core-weighted mask if requested
    if args.core_weighted:
        write('Calculating core-weighted mask.')
        mask.array = determine_core_indices(mask.array)

    pf = PowerFitter(target, laplace=args.laplace)
    pf._rotations = rotmat
    pf._template = template
    pf._mask = mask
    pf._nproc = args.nproc
    pf.directory = args.directory
    pf._queues = queues
    if args.gpu:
        write('Using GPU-accelerated search.')
    else:
        write('Requested number of processors: {:d}'.format(args.nproc))
    write('Starting search')
    time1 = clock()
    pf.scan()
    write('Time for search: {:.0f}m {:.0f}s'.format(*divmod(clock() - time1, 60)))

    write('Analyzing results')
    # calculate the molecular volume of the structure
    mv = structure_to_shape_like(
          target, structure.coor, resolution=resolution, radii=structure.rvdw, shape='mask'
          ).array.sum() * target.voxelspacing ** 3
    z_sigma = fisher_sigma(mv, resolution)
    analyzer = Analyzer(
            pf._lcc, rotmat, pf._rot, voxelspacing=target.voxelspacing,
            origin=target.origin, z_sigma=z_sigma
            )

    write('Writing solutions to file.')
    Volume(pf._lcc, target.voxelspacing, target.origin).tofile(join(args.directory, 'lcc.mrc'))
    analyzer.tofile(join(args.directory, 'solutions.out'))

    if args.ft_template == 'pdb':
        write('Writing PDBs to file.')
        n = min(args.num, len(analyzer.solutions))
        write_fits_to_pdb(structure, analyzer.solutions[:n],
                basename=join(args.directory, 'fit'))

    write('Total time: {:.0f}m {:.0f}s'.format(*divmod(clock() - time0, 60)))