Example #1
0
def load_grid(fname, prefix='aa', ramp='jet'):

    cmd.volume_ramp_new('ramp_jet', [
        0.00,
        0.00,
        0.00,
        1.00,
        0.00,
        25.00,
        0.06,
        0.93,
        1.00,
        0.05,
        50.00,
        0.49,
        0.51,
        1.00,
        0.15,
        75.00,
        1.00,
        1.00,
        0.00,
        0.23,
        90.00,
        0.80,
        0.18,
        1.00,
        0.48,
        100.00,
        0.98,
        0.01,
        1.00,
        1.00,
    ])

    cmd.volume_ramp_new('ramp_delta', [
        -1.0, 1.00, 0.00, 0.00, 0.00, -0.4, 1.00, 1.00, 0.00, 1.0, -0.2, 1.00,
        0.00, 0.00, 0.00, 0.2, 0.00, 0.00, 1.00, 0.00, 0.4, 0.00, 1.00, 1.00,
        1.0, 1.0, 0.00, 0.00, 1.00, 0.00
    ])

    F = h5py.File(fname, 'r')
    grid = F['step'][()]
    origin = F['origin'][()]

    NUCS = set(F.keys())
    protected = set(['origin', 'step', 'atypes'])
    NUCS -= protected

    for i in NUCS:
        data = F[i][()]
        b = Brick.from_numpy(data, grid, origin)
        bname = prefix + '_' + i
        cmd.load_brick(b, bname)
        volname = bname + '_volume'

        cmd.volume(volname, bname)

        cmd.volume_color(volname, 'ramp_jet')
Example #2
0
    def test(self):
        try:
            import numpy
        except ImportError:
            self.skip('requires numpy')

        from chempy.brick import Brick

        spacing = (.5, .5, .5)
        origin = (3., 4., 5.)
        shape = (10, 10, 10)
        range_ =  [a * (b - 1) for (a, b) in zip (spacing, shape)]

        data = numpy.zeros(shape, float)

        brick = Brick.from_numpy(data, spacing, origin)
        self.assertArrayEqual(brick.range, range_)

        cmd.load_brick(brick, 'map')

        extent = cmd.get_extent('map')
        self.assertArrayEqual(extent, [origin, cpv.add(origin, range_)])
Example #3
0


# ===============================
# brick creation

from chempy.brick import Brick

brik = Brick()

brik.setup_from_min_max(
   [0.0,0.0,0.0],
   [2.0,2.0,2.0],
   [0.2,0.2,0.2])

# ===============================
# brick data

import math

for x in range(11):
   for y in range(11):   
      for z in range(11):
          mx=1.5*(x-5)
          my=2*(y-5)
          mz=3*(z-5)
          brik.lvl[x,y,z]=1/math.exp(math.sqrt(mx*mx+my*my+mz*mz)/10.0)

# ===============================
# easy pickling code
def load_nrrd(filename, prefix='channel', channel='', _self=cmd):
    '''
DESCRIPTION

    Load maps in NRRD file format.

    Spec:
    http://teem.sourceforge.net/nrrd/format.html

    Example files:
    http://www.cs.utah.edu/~jmk/simian/download.htm
    '''
    import numpy
    import shlex
    from chempy.brick import Brick

    handle = open(filename, 'rb')

    magic = handle.readline()
    assert magic.startswith('NRRD')

    header = {}

    while True:
        line = handle.readline()
        if not line.strip():
            break
        if line.startswith('#'):
            continue
        key, value = line.split(':')
        header[key] = value.strip()

    assert header['encoding'] == 'raw'

    endian = '>' if header.get('endian') == 'big' else '<'
    dtype = {
        'signed char': 'i1',
        'int8': 'i1',
        'int8_t': 'i1',
        'uchar': 'u1',
        'unsigned char': 'u1',
        'uint8': 'u1',
        'uint8_t': 'u1',
        'float': 'f4',
        'double': 'f8',
    }[header['type']]

    data = numpy.fromfile(handle, endian + dtype)
    handle.close()

    sizes = [int(i) for i in header['sizes'].split()]
    grid = [float(i) for i in header.get('spacings', '0 1 1 1').split()[1:]]
    channels = shlex.split(header.get('labels', 'abcdefg'))[0]

    assert len(sizes) == 4

    sizes = tuple(reversed(sizes))
    grid = tuple(reversed(grid))

    data = data.reshape(sizes)

    for i in range(sizes[-1]):
        ch = channels[i]
        name = prefix

        if not channel:
            name += '_' + ch
        elif channel != ch:
            continue

        stack = data[..., i].astype('f4')

        # normalize
        stack -= stack.mean()
        stack /= stack.std()

        brick = Brick.from_numpy(stack, grid)
        _self.load_brick(brick, name)
Example #5
0
def load_grid(fname, prefix='aa', ramp='jet'):

    cmd.volume_ramp_new('ramp_DA', [
        0.00,
        1.00,
        1.00,
        1.00,
        0.00,
        25.00,
        1.00,
        0.77,
        0.77,
        0.02,
        50.00,
        1.00,
        0.54,
        0.54,
        0.06,
        75.00,
        1.00,
        0.38,
        0.38,
        0.18,
        90.00,
        0.93,
        0.00,
        0.00,
        0.60,
        100.00,
        0.70,
        0.00,
        0.00,
        1.00,
    ])

    cmd.volume_ramp_new('ramp_DG', [
        0.00,
        1.00,
        1.00,
        1.00,
        0.00,
        25.00,
        0.77,
        0.77,
        1.00,
        0.02,
        50.00,
        0.54,
        0.54,
        1.00,
        0.06,
        75.00,
        0.38,
        0.38,
        1.00,
        0.18,
        90.00,
        0.00,
        0.00,
        0.93,
        0.60,
        100.00,
        0.00,
        0.00,
        0.70,
        1.00,
    ])

    cmd.volume_ramp_new('ramp_DC', [
        0.00,
        1.00,
        1.00,
        1.00,
        0.00,
        25.00,
        0.64,
        1.00,
        0.61,
        0.02,
        50.00,
        0.48,
        1.00,
        0.47,
        0.06,
        75.00,
        0.26,
        1.00,
        0.28,
        0.18,
        90.00,
        0.04,
        0.85,
        0.00,
        0.44,
        100.00,
        0.00,
        0.52,
        0.06,
        1.00,
    ])

    cmd.volume_ramp_new('ramp_DT', [
        0.00,
        1.00,
        1.00,
        1.00,
        0.00,
        25.00,
        1.00,
        0.99,
        0.55,
        0.02,
        50.00,
        1.00,
        0.98,
        0.46,
        0.06,
        75.00,
        1.00,
        0.99,
        0.37,
        0.19,
        90.00,
        0.92,
        0.92,
        0.00,
        0.39,
        100.00,
        0.76,
        0.73,
        0.00,
        1.00,
    ])

    cmd.volume_ramp_new('ramp_P', [
        0.00,
        1.00,
        1.00,
        1.00,
        0.00,
        25.00,
        1.00,
        0.95,
        0.93,
        0.02,
        50.00,
        1.00,
        0.85,
        0.69,
        0.06,
        75.00,
        1.00,
        0.78,
        0.55,
        0.19,
        90.00,
        1.00,
        0.66,
        0.30,
        0.39,
        100.00,
        0.97,
        0.50,
        0.00,
        1.00,
    ])

    cmd.volume_ramp_new('ramp_jet', [
        0.00,
        0.00,
        0.00,
        1.00,
        0.00,
        25.00,
        0.06,
        0.93,
        1.00,
        0.05,
        50.00,
        0.49,
        0.51,
        1.00,
        0.15,
        75.00,
        1.00,
        1.00,
        0.00,
        0.23,
        90.00,
        0.80,
        0.18,
        1.00,
        0.48,
        100.00,
        0.98,
        0.01,
        1.00,
        1.00,
    ])

    cmd.volume_ramp_new('ramp_delta', [
        -1.0, 1.00, 0.00, 0.00, 0.00, -0.4, 1.00, 1.00, 0.00, 1.0, -0.2, 1.00,
        0.00, 0.00, 0.00, 0.2, 0.00, 0.00, 1.00, 0.00, 0.4, 0.00, 1.00, 1.00,
        1.0, 1.0, 0.00, 0.00, 1.00, 0.00
    ])

    F = h5py.File(fname, 'r')

    # load step along every axis
    # step = np.array([1.0, 1.0, 1.0])
    step = F['step'][()]

    # load origin of grid
    # origin = np.array([0.0, 0.0, 0.0])
    origin = F['origin'][()]

    NUCS = set(F.keys())
    protected = set(['origin', 'step', 'atypes'])
    NUCS -= protected

    for i in NUCS:
        # load data: 3D array
        data = F[i][()]
        # Create brick
        b = Brick.from_numpy(data, step, origin)
        bname = prefix + '_' + i
        # load brick into pymol
        cmd.load_brick(b, bname)
        volname = bname + '_volume'

        # assign ramp to the brick
        cmd.volume(volname, bname)

        if ramp == 'nuc':
            cmd.volume_color(volname, 'ramp_' + i)
        elif ramp == 'delta':
            cmd.volume_color(volname, 'ramp_delta')
        else:
            cmd.volume_color(volname, 'ramp_jet')
Example #6
0
def load_meta_grid(fname, prefix='meta'):

    F = h5py.File(fname, 'r')

    step = F['step'][()]

    origin = F['origin'][()]

    NUCS = set(F.keys())
    protected = set(['origin', 'step', 'atypes'])
    NUCS -= protected

    for i in NUCS:
        data = F[i][()]
        b = Brick.from_numpy(data, step, origin)
        bname = prefix + '_' + i
        cmd.load_brick(b, bname)
        volname = bname + '_volume'

        d_min = np.min(data)
        d_max = np.max(data)

        v = np.linspace(d_min, d_max, 6)

        cmd.volume(volname, bname)

        print('ramp_%s' % i)

        cmd.volume_ramp_new('ramp_grid', [
            v[0],
            0.00,
            0.00,
            1.00,
            0.70,
            v[1],
            0.06,
            0.93,
            1.00,
            0.50,
            v[2],
            0.49,
            0.51,
            1.00,
            0.30,
            v[3],
            1.00,
            1.00,
            0.00,
            0.10,
            v[4],
            0.80,
            0.18,
            1.00,
            0.05,
            v[5],
            0.98,
            0.01,
            1.00,
            0.00,
        ])

        cmd.volume_color(volname, 'ramp_grid')
Example #7
0
# ===============================
# brick creation

from chempy.brick import Brick

brik = Brick()

brik.setup_from_min_max([0.0, 0.0, 0.0], [2.0, 2.0, 2.0], [0.2, 0.2, 0.2])

# ===============================
# brick data

import math

for x in range(11):
    for y in range(11):
        for z in range(11):
            mx = 1.5 * (x - 5)
            my = 2 * (y - 5)
            mz = 3 * (z - 5)
            brik.lvl[x, y, z] = 1 / math.exp(
                math.sqrt(mx * mx + my * my + mz * mz) / 10.0)

# ===============================
# easy pickling code

#from chempy import io

#io.pkl.toFile(brik,"brick.pkb")

#brik = io.pkl.fromFile("brick.pkb")
def load_img_stack(pattern,
                   name='',
                   grid=1.0,
                   channel=0,
                   normalize=1,
                   extent=None,
                   quiet=1,
                   _self=cmd):
    '''
DESCRIPTION

    Load a stack of images as a map

ARGUMENTS

    pattern = str: image filename or pattern

    name = str: map object name to create

    grid = float: grid spacing in Angstrom {default: 1.0}

    channel = int: color channel for RGB images {default: 0}

    normalize = 0 or 1: normalize data {default: 1}

    extent = 3-float: (a,b,c) edge lengths in Angstrom, overwrites "grid"
    arguments if given {default: }

EXAMPLES

    load_img_stack img*.tif, extent=(21.0, 14.5, 18.2)
    '''
    import glob
    import numpy
    from chempy.brick import Brick

    try:
        from PIL import Image
    except ImportError:
        import Image

    channel, normalize, quiet = int(channel), int(normalize), int(quiet)

    if not name:
        name = _self.get_unused_name('map')

    if isinstance(grid, str):
        grid = _self.safe_eval(grid)
    if not isinstance(grid, (tuple, list)):
        grid = (grid, ) * 3

    stack = []
    size = None

    filenames = glob.glob(_self.exp_path(pattern))

    if not filenames:
        raise CmdException('no such files')

    for filename in sorted(filenames):
        img = Image.open(filename)
        if size is None:
            size = img.size
        for img in imgframeiter(img):
            if img.size != size:
                if not quiet:
                    print('Image size mismatch: %s != %s' % (img.size, size))
                continue
            a = numpy.reshape(img, (size[0], size[1], -1))
            stack.append(a[..., channel])

    stack = numpy.asfarray(stack)
    stack = stack.swapaxes(0, 2)[:, ::-1, ::-1]

    if min(stack.shape) < 2:
        raise CmdException('insufficient grid dimensions: ' + str(stack.shape))

    if normalize:
        stack -= stack.mean()
        stack /= stack.std()

    if extent:
        if isinstance(extent, str):
            extent = _self.safe_eval(extent)
        grid = [(float(e) / (s - 1)) for (e, s) in zip(extent, stack.shape)]
        if not quiet:
            print(' Setting grid = ' + str(grid))

    brick = Brick.from_numpy(stack, grid)
    _self.load_brick(brick, name)
def load_img_stack(pattern, name='', grid=1.0, channel=0, normalize=1,
        extent=None, quiet=1, _self=cmd):
    '''
DESCRIPTION

    Load a stack of images as a map

ARGUMENTS

    pattern = str: image filename or pattern

    name = str: map object name to create

    grid = float: grid spacing in Angstrom {default: 1.0}

    channel = int: color channel for RGB images {default: 0}

    normalize = 0 or 1: normalize data {default: 1}

    extent = 3-float: (a,b,c) edge lengths in Angstrom, overwrites "grid"
    arguments if given {default: }

EXAMPLES

    load_img_stack img*.tif, extent=(21.0, 14.5, 18.2)
    '''
    import glob
    import numpy
    from chempy.brick import Brick

    try:
        from PIL import Image
    except ImportError:
        import Image

    channel, normalize, quiet = int(channel), int(normalize), int(quiet)

    if not name:
        name = _self.get_unused_name('map')

    if isinstance(grid, str):
        grid = _self.safe_eval(grid)
    if not isinstance(grid, (tuple, list)):
        grid = (grid,) * 3

    stack = []
    size = None

    filenames = glob.glob(_self.exp_path(pattern))

    if not filenames:
        raise CmdException('no such files')

    for filename in sorted(filenames):
        img = Image.open(filename)
        if size is None:
            size = img.size
        for img in imgframeiter(img):
            if img.size != size:
                if not quiet:
                    print('Image size mismatch: %s != %s' % (img.size, size))
                continue
            a = numpy.reshape(img, (size[0], size[1], -1))
            stack.append(a[..., channel])

    stack = numpy.asfarray(stack)
    stack = stack.swapaxes(0, 2)[:, ::-1, ::-1]

    if min(stack.shape) < 2:
        raise CmdException('insufficient grid dimensions: ' + str(stack.shape))

    if normalize:
        stack -= stack.mean()
        stack /= stack.std()

    if extent:
        if isinstance(extent, str):
            extent = _self.safe_eval(extent)
        grid = [(float(e) / (s - 1)) for (e, s) in zip(extent, stack.shape)]
        if not quiet:
            print(' Setting grid = ' + str(grid))

    brick = Brick.from_numpy(stack, grid)
    _self.load_brick(brick, name)
Example #10
0
def load_sites(fname, prefix='sites', ramp='jet', top=42):

    cmd.volume_ramp_new('ramp_DA', [
        0.00,
        1.00,
        1.00,
        1.00,
        0.00,
        25.00,
        1.00,
        0.77,
        0.77,
        0.02,
        50.00,
        1.00,
        0.54,
        0.54,
        0.06,
        75.00,
        1.00,
        0.38,
        0.38,
        0.18,
        90.00,
        0.93,
        0.00,
        0.00,
        0.60,
        100.00,
        0.70,
        0.00,
        0.00,
        1.00,
    ])

    cmd.volume_ramp_new('ramp_DG', [
        0.00,
        1.00,
        1.00,
        1.00,
        0.00,
        25.00,
        0.77,
        0.77,
        1.00,
        0.02,
        50.00,
        0.54,
        0.54,
        1.00,
        0.06,
        75.00,
        0.38,
        0.38,
        1.00,
        0.18,
        90.00,
        0.00,
        0.00,
        0.93,
        0.60,
        100.00,
        0.00,
        0.00,
        0.70,
        1.00,
    ])

    cmd.volume_ramp_new('ramp_DC', [
        0.00,
        1.00,
        1.00,
        1.00,
        0.00,
        25.00,
        0.64,
        1.00,
        0.61,
        0.02,
        50.00,
        0.48,
        1.00,
        0.47,
        0.06,
        75.00,
        0.26,
        1.00,
        0.28,
        0.18,
        90.00,
        0.04,
        0.85,
        0.00,
        0.44,
        100.00,
        0.00,
        0.52,
        0.06,
        1.00,
    ])

    cmd.volume_ramp_new('ramp_DT', [
        0.00,
        1.00,
        1.00,
        1.00,
        0.00,
        25.00,
        1.00,
        0.99,
        0.55,
        0.02,
        50.00,
        1.00,
        0.98,
        0.46,
        0.06,
        75.00,
        1.00,
        0.99,
        0.37,
        0.19,
        90.00,
        0.92,
        0.92,
        0.00,
        0.39,
        100.00,
        0.76,
        0.73,
        0.00,
        1.00,
    ])

    cmd.volume_ramp_new('ramp_P', [
        0.00,
        1.00,
        1.00,
        1.00,
        0.00,
        25.00,
        1.00,
        0.95,
        0.93,
        0.02,
        50.00,
        1.00,
        0.85,
        0.69,
        0.06,
        75.00,
        1.00,
        0.78,
        0.55,
        0.19,
        90.00,
        1.00,
        0.66,
        0.30,
        0.39,
        100.00,
        0.97,
        0.50,
        0.00,
        1.00,
    ])

    cmd.volume_ramp_new('ramp_jet', [
        0.00,
        0.00,
        0.00,
        1.00,
        0.00,
        25.00,
        0.06,
        0.93,
        1.00,
        0.05,
        50.00,
        0.49,
        0.51,
        1.00,
        0.15,
        75.00,
        1.00,
        1.00,
        0.00,
        0.23,
        90.00,
        0.80,
        0.18,
        1.00,
        0.48,
        100.00,
        0.98,
        0.01,
        1.00,
        1.00,
    ])

    cmd.volume_ramp_new('ramp_delta', [
        -1.0, 1.00, 0.00, 0.00, 0.00, -0.4, 1.00, 1.00, 0.00, 1.0, -0.2, 1.00,
        0.00, 0.00, 0.00, 0.2, 0.00, 0.00, 1.00, 0.00, 0.4, 0.00, 1.00, 1.00,
        1.0, 1.0, 0.00, 0.00, 1.00, 0.00
    ])

    F = h5py.File(fname, 'r')

    NUCS = natsort.natsorted(F.keys())

    if int(top) < 1:
        print('top should be greater than 1')
        return

    top_ = min(int(top), len(NUCS))

    NUCS_ = NUCS[:top_]

    for i in NUCS_:
        data = F[i]['data'][()]
        origin = F[i]['origin'][()]
        step = F[i]['step'][()]
        b = Brick.from_numpy(data, step, origin)
        bname = prefix + '_' + i
        cmd.load_brick(b, bname)
        volname = bname + '_volume'

        cmd.volume(volname, bname)

        cmd.volume_color(volname, 'ramp_' + ramp)
Example #11
0
def load_vis_map(filename, name=None, mimic=1, quiet=1, _self=cmd):
    '''
DESCRIPTION

    Load a map (a.k.a. volume or brick) from a vis file.

ARGUMENTS

    filename = string: filename

    name = string: name of map or group prefix, if ending with
    a period. {default: "Dataset Name" property from file}

    mimic = 0/1: load isosurfaces {default: 1}
    '''
    from chempy.brick import Brick

    mimic, quiet = int(mimic), int(quiet)

    data = get_data(filename)

    try:
        if data.attrs['Rank'] != 3:
            raise ValueError('Rank %s' % data.attrs['Rank'])
        if tuple(data.attrs['Dimensions']) != data.value.shape:
            raise ValueError('Dimensions %s' % data.attrs['Dimensions'])
        if data.attrs['Grid Type'] != 1:
            raise ValueError('Unknown Grid Type: %s' % data.attrs['Grid Type'])

        ds_name = data.attrs.get("Dataset Name") or "unnamed"

        obj = Brick.from_numpy(data.value,
                data.attrs["Space Ratio"],
                data.attrs["Origin"])

    except Exception as e:
        raise CmdException('could not find map in vis file')

    if not name:
        name = _self.get_unused_name(ds_name, 0)
    elif name.endswith("."):
        name = _self.get_unused_name(name + ds_name, 0)

    _self.load_brick(obj, name)

    try:
        cell = data.attrs['Unit Cell ABC'].tolist() + \
               data.attrs['Unit Cell Angle'].tolist()
    except KeyError:
        cell = [False]

    if all(cell):
        cell.append('P 1')
        _self.set_symmetry(name, *cell)

    if not mimic:
        return name

    isofunc = {1: _self.isomesh, 2: _self.isodot}.get(
            0, _self.isosurface)

    for color, isolevel in zip(data.attrs.get('Contour Colors', []),
                               data.attrs.get('Contour Isovalues', [])):
        mesh_name = _self.get_unused_name(name + '_contour', 0)
        isofunc(mesh_name, name, isolevel)
        apply_color(color, mesh_name, quiet, _self)

    return name