Ejemplo n.º 1
0
def XTCwrite(coords, box, filename, time=None, step=None):
    numFrames = coords.shape[2]
    if np.size(box,
               1) != numFrames:  # Box should have as many frames as trajectory
        box = np.tile(box, (1, numFrames))

    nframes = np.size(coords, 2)
    if np.size(time) != nframes:
        time = np.zeros(nframes)
    if np.size(step) != nframes:
        step = np.zeros(nframes, dtype=int)

    if os.path.isfile(filename):
        os.unlink(filename)

    lib = xtc_lib()
    bbox = (ct.c_float * 3)()
    natoms = ct.c_int(coords.shape[0])
    cstep = ct.c_int()
    # print(coords.shape)
    for f in range(coords.shape[2]):
        cstep = ct.c_int(step[f])
        ctime = ct.c_float(time[f])  # TODO FIXME
        # print ( step )
        # print ( time )
        bbox[0] = box[0, f] * 0.1
        bbox[1] = box[1, f] * 0.1
        bbox[2] = box[2, f] * 0.1

        data = coords[:, :, f].astype(np.float32) * 0.1  # Convert from A to nm
        pos = data.ctypes.data_as(ct.POINTER(ct.c_float))
        lib['libxtc'].xtc_write(ct.c_char_p(filename.encode("ascii")), natoms,
                                cstep, ctime, pos, bbox)
Ejemplo n.º 2
0
def XTCwrite(mol, filename):
    coords = mol.coords
    box = mol.box
    time = mol.time
    step = mol.step
    numFrames = mol.numFrames

    if np.size(box, 1) != numFrames:  # Box should have as many frames as trajectory
        box = np.tile(box, (1, numFrames))

    nframes = np.size(coords, 2)
    if np.size(time) != nframes:
        time = np.zeros(nframes)
    if np.size(step) != nframes:
        step = np.zeros(nframes, dtype=int)

    if os.path.isfile(filename):
        os.unlink(filename)

    box = box.astype(np.float32) * 0.1
    step = step.astype(np.int32)
    time = time.astype(np.float32)
    coords = coords.astype(np.float32) * 0.1  # Convert from A to nm
    if not box.flags['C_CONTIGUOUS']:
        box = np.ascontiguousarray(box)
    if not step.flags['C_CONTIGUOUS']:
        step = np.ascontiguousarray(step)
    if not time.flags['C_CONTIGUOUS']:
        time = np.ascontiguousarray(time)
    if not coords.flags['C_CONTIGUOUS']:
        coords = np.ascontiguousarray(coords)

    lib = xtc_lib()
    natoms = ct.c_int(coords.shape[0])
    nframes = ct.c_int(coords.shape[2])

    cstep = step.ctypes.data_as(ct.POINTER(ct.c_int))
    ctime = time.ctypes.data_as(ct.POINTER(ct.c_float))
    cbox = box.ctypes.data_as(ct.POINTER(ct.c_float))
    ccoords = coords.ctypes.data_as(ct.POINTER(ct.c_float))
    lib['libxtc'].xtc_write(
        ct.c_char_p(filename.encode("ascii")),
        natoms,
        nframes,
        cstep,
        ctime,
        ccoords,
        cbox)
Ejemplo n.º 3
0
def XTCwrite(mol, filename):
    coords = mol.coords
    box = mol.box
    time = mol.time
    step = mol.step
    numFrames = mol.numFrames

    if np.size(box, 1) != numFrames:  # Box should have as many frames as trajectory
        box = np.tile(box, (1, numFrames))

    nframes = np.size(coords, 2)
    if np.size(time) != nframes:
        time = np.zeros(nframes)
    if np.size(step) != nframes:
        step = np.zeros(nframes, dtype=int)

    if os.path.isfile(filename):
        os.unlink(filename)

    lib = xtc_lib()
    bbox = (ct.c_float * 3)()
    natoms = ct.c_int(coords.shape[0])
    cstep = ct.c_int()
    # print(coords.shape)
    for f in range(coords.shape[2]):
        cstep = ct.c_int(step[f])
        ctime = ct.c_float(time[f])  # TODO FIXME
        # print ( step )
        # print ( time )
        bbox[0] = box[0, f] * 0.1
        bbox[1] = box[1, f] * 0.1
        bbox[2] = box[2, f] * 0.1

        data = coords[:, :, f].astype(np.float32) * 0.1  # Convert from A to nm
        pos = data.ctypes.data_as(ct.POINTER(ct.c_float))
        lib['libxtc'].xtc_write(
            ct.c_char_p(filename.encode("ascii")),
            natoms,
            cstep,
            ctime,
            pos,
            bbox)
Ejemplo n.º 4
0
def XTCread(filename, frame=None, topoloc=None):
    """ Reads XTC file

    Parameters
    ----------
    filename : str
        Path of xtc file.
    frame : list
        A list of integer frames which we want to read from the file. If None will read all.

    Returns
    -------
    coords : nd.array
    box : nd.array
    boxangles : nd.array
    step : nd.array
    time : nd.array
    """
    givenframes = frame
    class __xtc(ct.Structure):
        _fields_ = [("box", (ct.c_float * 3)),
                    ("natoms", ct.c_int),
                    ("step", ct.c_ulong),
                    ("time", ct.c_double),
                    ("pos", ct.POINTER(ct.c_float))]

    lib = xtc_lib()
    nframes = pack_ulong_buffer([0])
    natoms = pack_int_buffer([0])
    deltastep = pack_int_buffer([0])
    deltat = pack_double_buffer([0])

    lib['libxtc'].xtc_read.restype = ct.POINTER(__xtc)
    lib['libxtc'].xtc_read_frame.restype = ct.POINTER(__xtc)

    coords = None
    if givenframes is None:  # Read the whole XTC file at once
        retval = lib['libxtc'].xtc_read(
            ct.c_char_p(filename.encode("ascii")),
            natoms,
            nframes, deltat, deltastep)
        if not retval:
            raise IOError('XTC file {} possibly corrupt.'.format(filename))
        nframes = nframes[0]
        frames = range(nframes)
        coords = np.zeros((natoms[0], 3, nframes), dtype=np.float32)
    else:
        if not isinstance(givenframes, list) and not isinstance(givenframes, np.ndarray):
            givenframes = [givenframes]
        nframes = len(givenframes)
        frames = givenframes

    step = np.zeros(nframes, dtype=np.uint64)
    time = np.zeros(nframes, dtype=np.float32)
    box = np.zeros((3, nframes), dtype=np.float32)
    boxangles = np.zeros((3, nframes), dtype=np.float32)

    for i, f in enumerate(frames):
        if givenframes is not None:  # If frames were given, read specific frame
            retval = lib['libxtc'].xtc_read_frame(
                ct.c_char_p(filename.encode("ascii")),
                natoms,
                ct.c_int(f))
            if not retval:
                raise IOError('XTC file {} possibly corrupt.'.format(filename))
            if coords is None:
                coords = np.zeros((natoms[0], 3, nframes), dtype=np.float32)
            fidx = 0
        else:
            fidx = f

        step[i] = retval[fidx].step
        time[i] = retval[fidx].time
        box[:, i] = retval[fidx].box
        coords[:, :, i] = np.ctypeslib.as_array(retval[fidx].pos, shape=(natoms[0], 3))

        if givenframes is not None:
            lib['libc'].free(retval[0].pos)
            lib['libc'].free(retval)

    if givenframes is None:
        for f in range(len(frames)):
            lib['libc'].free(retval[f].pos)
        lib['libc'].free(retval)

    if np.size(coords, 2) == 0:
        raise NameError('Malformed XTC file. No frames read from: {}'.format(filename))
    if np.size(coords, 0) == 0:
        raise NameError('Malformed XTC file. No atoms read from: {}'.format(filename))

    coords *= 10.  # Convert from nm to Angstrom
    box *= 10.  # Convert from nm to Angstrom
    nframes = coords.shape[2]
    if len(step) != nframes or np.sum(step) == 0:
        step = np.arange(nframes)
    if len(time) != nframes or np.sum(time) == 0:
        logger.warning('No time information read from {}. Defaulting to 0.1ns framestep.'.format(filename))
        time = np.arange(nframes) * 1E5  # Default is 0.1ns in femtoseconds = 100.000 fs
    return None, Trajectory(coords=coords, box=box, boxangles=boxangles, step=step, time=time)
Ejemplo n.º 5
0
def XTCread(filename, frames=None):
    class __xtc(ct.Structure):
        _fields_ = [("box", (ct.c_float * 3)), ("natoms", ct.c_int),
                    ("step", ct.c_ulong), ("time", ct.c_double),
                    ("pos", ct.POINTER(ct.c_float))]

    lib = xtc_lib()
    nframes = pack_ulong_buffer([0])
    natoms = pack_int_buffer([0])
    deltastep = pack_int_buffer([0])
    deltat = pack_double_buffer([0])

    lib['libxtc'].xtc_read.restype = ct.POINTER(__xtc)
    lib['libxtc'].xtc_read_frame.restype = ct.POINTER(__xtc)

    if frames is None:
        retval = lib['libxtc'].xtc_read(ct.c_char_p(filename.encode("ascii")),
                                        natoms, nframes, deltat, deltastep)

        if not retval:
            raise IOError('XTC file {} possibly corrupt.'.format(filename))

        frames = range(nframes[0])
        t = Trajectory()
        t.natoms = natoms[0]
        t.nframes = len(frames)
        t.coords = np.zeros((natoms[0], 3, t.nframes), dtype=np.float32)
        t.step = np.zeros(t.nframes, dtype=np.uint64)
        t.time = np.zeros(t.nframes, dtype=np.float32)
        t.box = np.zeros((3, t.nframes), dtype=np.float32)

        for i, f in enumerate(frames):
            if f >= nframes[0] or f < 0:
                raise RuntimeError(
                    'Frame index out of range in XTCread with given frames')
            t.step[i] = retval[f].step
            t.time[i] = retval[f].time
            t.box[0, i] = retval[f].box[0]
            t.box[1, i] = retval[f].box[1]
            t.box[2, i] = retval[f].box[2]
            #		print( t.coords[:,:,f].shape)
            #		print ( t.box[:,f] )
            #   t.step[i] = deltastep[0] * i
            t.coords[:, :, i] = np.ctypeslib.as_array(retval[f].pos,
                                                      shape=(natoms[0], 3))

        for f in range(len(frames)):
            lib['libc'].free(retval[f].pos)
        lib['libc'].free(retval)

    else:
        if not isinstance(frames, list) and not isinstance(frames, np.ndarray):
            frames = [frames]
        t = Trajectory()
        t.natoms = 0
        t.nframes = len(frames)
        t.coords = None
        t.step = None
        t.time = None
        t.box = None

        nframes = len(frames)
        i = 0
        for f in frames:
            retval = lib['libxtc'].xtc_read_frame(
                ct.c_char_p(filename.encode("ascii")), natoms, ct.c_int(f))
            if t.coords is None:
                t.natoms = natoms[0]
                t.coords = np.zeros((natoms[0], 3, nframes), dtype=np.float32)
                t.step = np.zeros(nframes, dtype=np.uint64)
                t.time = np.zeros(nframes, dtype=np.float32)
                t.box = np.zeros((3, nframes), dtype=np.float32)

            t.step[i] = retval[0].step
            t.time[i] = retval[0].time
            t.box[0, i] = retval[0].box[0]
            t.box[1, i] = retval[0].box[1]
            t.box[2, i] = retval[0].box[2]
            t.coords[:, :, i] = np.ctypeslib.as_array(retval[0].pos,
                                                      shape=(natoms[0], 3))
            i += 1

            lib['libc'].free(retval[0].pos)
            lib['libc'].free(retval)

    if np.size(t.coords, 2) == 0:
        raise NameError(
            'Malformed XTC file. No frames read from: {}'.format(filename))
    if np.size(t.coords, 0) == 0:
        raise NameError(
            'Malformed XTC file. No atoms read from: {}'.format(filename))

    # print( t.step )
    # print( t.time )
    #	print( t.coords[:,:,0] )
    # print(t.coords.shape)
    t.coords *= 10.  # Convert from nm to Angstrom
    t.box *= 10.  # Convert from nm to Angstrom
    return t
Ejemplo n.º 6
0
def XTCread(filename, frame=None, topoloc=None):
    """ Reads XTC file

    Parameters
    ----------
    filename : str
        Path of xtc file.
    frame : list
        A list of integer frames which we want to read from the file. If None will read all.

    Returns
    -------
    coords : nd.array
    box : nd.array
    boxangles : nd.array
    step : nd.array
    time : nd.array
    """
    givenframes = frame
    class __xtc(ct.Structure):
        _fields_ = [("box", (ct.c_float * 3)),
                    ("natoms", ct.c_int),
                    ("step", ct.c_ulong),
                    ("time", ct.c_double),
                    ("pos", ct.POINTER(ct.c_float))]

    lib = xtc_lib()
    nframes = pack_ulong_buffer([0])
    natoms = pack_int_buffer([0])
    deltastep = pack_int_buffer([0])
    deltat = pack_double_buffer([0])

    lib['libxtc'].xtc_read.restype = ct.POINTER(__xtc)
    lib['libxtc'].xtc_read_frame.restype = ct.POINTER(__xtc)

    coords = None
    if givenframes is None:  # Read the whole XTC file at once
        retval = lib['libxtc'].xtc_read(
            ct.c_char_p(filename.encode("ascii")),
            natoms,
            nframes, deltat, deltastep)
        if not retval:
            raise IOError('XTC file {} possibly corrupt.'.format(filename))
        nframes = nframes[0]
        frames = range(nframes)
        coords = np.zeros((natoms[0], 3, nframes), dtype=np.float32)
    else:
        if not isinstance(givenframes, list) and not isinstance(givenframes, np.ndarray):
            givenframes = [givenframes]
        nframes = len(givenframes)
        frames = givenframes

    step = np.zeros(nframes, dtype=np.uint64)
    time = np.zeros(nframes, dtype=np.float32)
    box = np.zeros((3, nframes), dtype=np.float32)
    boxangles = np.zeros((3, nframes), dtype=np.float32)

    for i, f in enumerate(frames):
        if givenframes is not None:  # If frames were given, read specific frame
            retval = lib['libxtc'].xtc_read_frame(
                ct.c_char_p(filename.encode("ascii")),
                natoms,
                ct.c_int(f))
            if not retval:
                raise IOError('XTC file {} possibly corrupt.'.format(filename))
            if coords is None:
                coords = np.zeros((natoms[0], 3, nframes), dtype=np.float32)
            fidx = 0
        else:
            fidx = f

        step[i] = retval[fidx].step
        time[i] = retval[fidx].time
        box[:, i] = retval[fidx].box
        coords[:, :, i] = np.ctypeslib.as_array(retval[fidx].pos, shape=(natoms[0], 3))

        if givenframes is not None:
            lib['libc'].free(retval[0].pos)
            lib['libc'].free(retval)

    if givenframes is None:
        for f in range(len(frames)):
            lib['libc'].free(retval[f].pos)
        lib['libc'].free(retval)

    if np.size(coords, 2) == 0:
        raise NameError('Malformed XTC file. No frames read from: {}'.format(filename))
    if np.size(coords, 0) == 0:
        raise NameError('Malformed XTC file. No atoms read from: {}'.format(filename))

    coords *= 10.  # Convert from nm to Angstrom
    box *= 10.  # Convert from nm to Angstrom
    nframes = coords.shape[2]
    if len(step) != nframes or np.sum(step) == 0:
        step = np.arange(nframes)
    if len(time) != nframes or np.sum(time) == 0:
        logger.warning('No time information read from {}. Defaulting to 0.1ns framestep.'.format(filename))
        time = np.arange(nframes) * 1E5  # Default is 0.1ns in femtoseconds = 100.000 fs
    return None, Trajectory(coords=coords, box=box, boxangles=boxangles, step=step, time=time)