Beispiel #1
0
def initialize_snap(syst, params={}):

    syst["np"] = sum(
        syst["len_polymers"]) * (1 + syst["excess_DNA"]) + syst["ndiff"]

    syst["nbond"] = sum(syst["len_polymers"]) - len(syst["len_polymers"])

    if syst["cohesin_real"]:
        syst["np"] += syst["n_cohesin"] * syst["particule_per_cohesin"]
        syst["nbond"] += syst["n_cohesin"] * syst["particule_per_cohesin"]

    syst["Rf"] = (sum(syst["len_polymers"]) * 0.5**3 / syst['density'])**0.33
    print("Radius of the cell", syst["Rf"])
    R = syst["Rf"] + 1
    snapshot = data.make_snapshot(N=syst["np"],
                                  box=data.boxdim(L=2 * R),
                                  bond_types=['polymer'])

    syst["bond_list"] = ['DNA', 'cohesin', "fFactor", "weak"]

    syst["plist"] = [
        "DNA", "uDNA", "pDNA", "fFactor", 'cohesine', "rDNA", "fDNA", "tDNA"
    ]
    # uDNA unreplicated DNA
    # rDNA replicated DNA
    # fDNA freshly replicated DNA
    # tDNA template replicated DNA

    return snapshot, syst
 def setUp(self):
     self.lamb = 1  # Dipolar coupling constant: mu0*m^2/ (2 * pi * d^3 * K * T)
     self.r_cut = 15
     # interaction cut-off
     self.diameter = 1
     # particles diameter
     # interaction between point dipoles
     self.dipole_dipole = """ float rsq = dot(r_ij, r_ij);
                             float r_cut = {0};
                             if (rsq < r_cut*r_cut)
                                 {{
                                 float lambda = {1};
                                 float r = fast::sqrt(rsq);
                                 float r3inv = 1.0 / rsq / r;
                                 vec3<float> t = r_ij / r;
                                 vec3<float> pi_o(1,0,0);
                                 vec3<float> pj_o(1,0,0);
                                 rotmat3<float> Ai(q_i);
                                 rotmat3<float> Aj(q_j);
                                 vec3<float> pi = Ai * pi_o;
                                 vec3<float> pj = Aj * pj_o;
                                 float Udd = (lambda*r3inv/2)*( dot(pi,pj)
                                              - 3 * dot(pi,t) * dot(pj,t));
                                 return Udd;
                                }}
                             else
                                 return 0.0f;
                         """.format(self.r_cut, self.lamb)
     self.snapshot = data.make_snapshot(N=2,
                                        box=data.boxdim(L=2 * self.r_cut,
                                                        dimensions=3),
                                        particle_types=['A'])
 def setUp(self):
     lennard_jones = """
                          float rsq = dot(r_ij, r_ij);
                          float rcut  = alpha_iso[0];
                          if (rsq <= rcut*rcut)
                             {{
                             float sigma = alpha_iso[1];
                             float eps   = alpha_iso[2];
                             float sigmasq = sigma*sigma;
                             float rsqinv = sigmasq / rsq;
                             float r6inv = rsqinv*rsqinv*rsqinv;
                             return 4.0f*eps*r6inv*(r6inv-1.0f);
                             }}
                          else
                             {{
                             return 0.0f;
                             }}
                          """
     self.dist = 2.0
     # distance between test particles
     snapshot = data.make_snapshot(N=2,
                                   box=data.boxdim(L=10, dimensions=3),
                                   particle_types=['A'])
     snapshot.particles.position[0, :] = (0, 0, 0)
     snapshot.particles.position[1, :] = (self.dist, 0, 0)
     system = init.read_snapshot(snapshot)
     mc = hpmc.integrate.sphere(seed=1, d=0)
     mc.shape_param.set('A', diameter=0)
     self.patch = jit.patch.user(mc=mc,
                                 r_cut=2.5,
                                 array_size=3,
                                 code=lennard_jones)
     self.logger = analyze.log(filename=None,
                               quantities=["hpmc_patch_energy"],
                               period=1)
Beispiel #4
0
    def setUp(self):
        snap = data.make_snapshot(3, data.boxdim(Lx = 3.5, Ly = 1.5, Lz = 1.5))

        #Setup a set of positions which we can easily see the overlaps for
        snap.particles.position[0] = [-.9, 0.0, 0.0]
        snap.particles.position[1] = [0.0, 0.0, 0.0]
        snap.particles.position[2] = [1.0, 0.25, 0.0]

        self.system = init.read_snapshot(snap)
        self.mc = hpmc.integrate.sphere(seed=123)
    def setUp(self):
        snap = data.make_snapshot(3, data.boxdim(Lx=3.5, Ly=1.5, Lz=1.5))

        #Setup a set of positions which we can easily see the overlaps for
        snap.particles.position[0] = [-.9, 0.0, 0.0]
        snap.particles.position[1] = [0.0, 0.0, 0.0]
        snap.particles.position[2] = [1.0, 0.25, 0.0]

        self.system = init.read_snapshot(snap)
        self.mc = hpmc.integrate.sphere(seed=123)
Beispiel #6
0
def psi6_order_from_gsd(fpath, frame=0):
    with gsd.fl.GSDFile(fpath, 'rb') as f_gsd:
        n_frames_total = f_gsd.nframes
        if frame > n_frames_total:
            raise ValueError('frames beyond n_frames_total')
        #translate negative indices into positive domain:
        abs_frame = frame -(frame//n_frames_total)*n_frames_total
        pos = f_gsd.read_chunk(frame=abs_frame, name='particles/position')
        box_array = f_gsd.read_chunk(frame=0, name='configuration/box')
        box = boxdim(*box_array[0:3])
    psi = psi_order_delone(pos, box, nx=100, ny=100, rcut=1.3)
    return psi
Beispiel #7
0
def latticeToHoomd(a1, a2, a3=[0.,0.,1.], ndim=3):
    from hoomd.data import boxdim

    a1 = np.array(a1)
    a2 = np.array(a2)
    a3 = np.array(a3)
    a1.resize((3,))
    a2.resize((3,))
    a3.resize((3,))
    xhat = np.array([1.,0.,0.])
    yhat = np.array([0.,1.,0.])
    zhat = np.array([0.,0.,1.])

    # Find quaternion to rotate first lattice vector to x axis
    a1mag = np.sqrt(np.dot(a1,a1))
    v1 = a1/a1mag + xhat
    v1mag = np.sqrt(np.dot(v1,v1))
    if v1mag > 1e-6:
        u1 = v1/v1mag
    else:
        # a1 is antialigned with xhat, so rotate around any unit vector perpendicular to xhat
        u1 = yhat
    q1 = np.concatenate(([np.cos(np.pi/2)], np.sin(np.pi/2)*u1))

    # Find quaternion to rotate second lattice vector to xy plane after applying above rotation
    a2prime = quatRot(q1, a2)
    angle = -1*np.arctan2(a2prime[2], a2prime[1])
    q2 = np.concatenate(([np.cos(angle/2)], np.sin(angle/2)*xhat))

    q = quatMult(q2,q1)

    Lx = np.sqrt(np.dot(a1, a1))
    a2x = np.dot(a1, a2) / Lx
    Ly = np.sqrt(np.dot(a2,a2) - a2x*a2x)
    xy = a2x / Ly
    v0xv1 = np.cross(a1, a2)
    v0xv1mag = np.sqrt(np.dot(v0xv1, v0xv1))
    Lz = np.dot(a3, v0xv1) / v0xv1mag
    a3x = np.dot(a1, a3) / Lx
    xz = a3x / Lz
    yz = (np.dot(a2, a3) - a2x*a3x) / (Ly*Lz)

    box = boxdim(Lx=Lx, Ly=Ly, Lz=Lz, xy=xy, xz=xz, yz=yz, dimensions=ndim)

    return box, q
Beispiel #8
0
def latticeToHoomd(a1, a2, a3=[0., 0., 1.], ndim=3):
    from hoomd.data import boxdim

    a1 = np.array(a1)
    a2 = np.array(a2)
    a3 = np.array(a3)
    a1.resize((3, ))
    a2.resize((3, ))
    a3.resize((3, ))
    xhat = np.array([1., 0., 0.])
    yhat = np.array([0., 1., 0.])
    zhat = np.array([0., 0., 1.])

    # Find quaternion to rotate first lattice vector to x axis
    a1mag = np.sqrt(np.dot(a1, a1))
    v1 = a1 / a1mag + xhat
    v1mag = np.sqrt(np.dot(v1, v1))
    if v1mag > 1e-6:
        u1 = v1 / v1mag
    else:
        # a1 is antialigned with xhat, so rotate around any unit vector perpendicular to xhat
        u1 = yhat
    q1 = np.concatenate(([np.cos(np.pi / 2)], np.sin(np.pi / 2) * u1))

    # Find quaternion to rotate second lattice vector to xy plane after applying above rotation
    a2prime = quatRot(q1, a2)
    angle = -1 * np.arctan2(a2prime[2], a2prime[1])
    q2 = np.concatenate(([np.cos(angle / 2)], np.sin(angle / 2) * xhat))

    q = quatMult(q2, q1)

    Lx = np.sqrt(np.dot(a1, a1))
    a2x = np.dot(a1, a2) / Lx
    Ly = np.sqrt(np.dot(a2, a2) - a2x * a2x)
    xy = a2x / Ly
    v0xv1 = np.cross(a1, a2)
    v0xv1mag = np.sqrt(np.dot(v0xv1, v0xv1))
    Lz = np.dot(a3, v0xv1) / v0xv1mag
    a3x = np.dot(a1, a3) / Lx
    xz = a3x / Lz
    yz = (np.dot(a2, a3) - a2x * a3x) / (Ly * Lz)

    box = boxdim(Lx=Lx, Ly=Ly, Lz=Lz, xy=xy, xz=xz, yz=yz, dimensions=ndim)

    return box, q
Beispiel #9
0
def compute_psi6_correlation_from_gsd(fpath, Nframes=1, frame_step=1, nxny=(100,100), init_frame=0):
    nx, ny = nxny
    cf_psi = np.zeros((ny, nx), dtype=complex)
    for frame in range(init_frame, init_frame + Nframes, frame_step):    
        with gsd.fl.GSDFile(fpath, 'rb') as f_gsd:
            n_frames_total = f_gsd.nframes
            if frame > n_frames_total:
                print('frame {} beyond n_frames_total = {}'.format(frame, n_frames_total))
            else:
                #translate negative indices into positive domain:
                abs_frame = frame -(frame//n_frames_total)*n_frames_total
                pos = f_gsd.read_chunk(frame=abs_frame, name='particles/position')
                box_array = f_gsd.read_chunk(frame=0, name='configuration/box')
                box = boxdim(*box_array[0:3])
                psi = psi_order(pos, box, nx=nx, ny=ny, rcut=1.3)
                cf_psi += correlation_function(psi)
    cf_psi /= min(Nframes, n_frames_total)
    return cf_psi
    def setUp(self):
        # square well attraction on constituent spheres
        square_well = """float rsq = dot(r_ij, r_ij);
                              float r_cut = alpha_union[0];
                              if (rsq < r_cut*r_cut)
                                  return alpha_union[1];
                              else
                                  return 0.0f;
                           """

        # soft repulsion between centers of unions
        soft_repulsion = """float rsq = dot(r_ij, r_ij);
                                  float r_cut = alpha_iso[0];
                                  if (rsq < r_cut*r_cut)
                                    return alpha_iso[1];
                                  else
                                    return 0.0f;
                         """
        diameter = 1.0
        snapshot = data.make_snapshot(N=2,
                                      box=data.boxdim(L=10, dimensions=3),
                                      particle_types=['A'])
        snapshot.particles.position[0, :] = (0, 0, 0)
        snapshot.particles.position[1, :] = (diameter, 0, 0)
        system = init.read_snapshot(snapshot)
        mc = hpmc.integrate.sphere_union(d=0, a=0, seed=1)
        mc.shape_param.set('A',
                           diameters=[diameter] * 2,
                           centers=[(0, 0, -diameter / 2),
                                    (0, 0, diameter / 2)],
                           overlap=[0] * 2)
        self.patch = jit.patch.user_union(mc=mc, r_cut=2.5, array_size=2, r_cut_iso=2.5, array_size_iso=2, \
                                          code=square_well, code_iso=soft_repulsion)
        self.patch.set_params('A',
                              positions=[(0, 0, -diameter / 2),
                                         (0, 0, diameter / 2)],
                              typeids=[0, 0])
        self.logger = analyze.log(filename=None,
                                  quantities=["hpmc_patch_energy"],
                                  period=1)
Beispiel #11
0
def pair_correlation_from_gsd(filename, n_bins = (100, 100), frames =(0, -1)):
    """ Calculate pair correlation function.
        Averaged over frames in the range from frames[0] to frames[1]. Negative frames are counted from the end of time.
        \param filename: name of the gsd file
        \param n_bins: tuple of size 2, numbers of bins in x and y direction for correlation function, both even
        Return: array of shape n_bins, pair correlation function normalized to (N - 1). Zero of coordinate is in the middle
        of the pixel grid (between pixels indexed (n_bins[i]/2 - 1) and (n_bins[i]/2)).
    """
    try:
        if is_odd(n_bins[0]) or is_odd(n_bins[1]):
            raise ValueError("n_bins must be 2 x 1 tuple of even numbers")
    except:
        raise ValueError("n_bins must be 2 x 1 tuple of even numbers")
        
    g = np.zeros(n_bins)
    with gsd.fl.GSDFile(filename, 'rb') as f_gsd:
        n_frames_total = f_gsd.nframes
        if frames[0] > n_frames_total or frames[1] > n_frames_total:
            raise ValueError('frames beyond n_frames_total')
        #translate negative indices into positive domain:
        abs_frames = (frames[0] -(frames[0]//n_frames_total)*n_frames_total, \
                     frames[1] -(frames[1]//n_frames_total)*n_frames_total)
        if abs_frames[0] > abs_frames[1]:
            raise ValueError('frames[0] must be to the left from frames[1]')
        all_frames = np.arange(0, n_frames_total, 1)
        selected_frames = all_frames[abs_frames[0]:abs_frames[1] + 1]
        n_frames = abs_frames[1] - abs_frames[0] + 1
        
        n_p = f_gsd.read_chunk(frame=0, name='particles/N')
        box_array = f_gsd.read_chunk(frame=0, name='configuration/box')
        box = boxdim(*box_array[0:3])
        pos = np.zeros((n_frames, n_p[0], 2))
        for j_frame in range(n_frames):
            pos_frame = f_gsd.read_chunk(frame=selected_frames[j_frame], name='particles/position')
            g += pair_correlation(pos_frame, box, n_bins = n_bins)
    g /= n_frames
    return g
Beispiel #12
0
 def to_hoomd_snapshot(self, snapshot=None):
     "Copy this frame to a HOOMD-blue snapshot."
     self.load()
     if snapshot is None:
         try:
             from hoomd import data
         except ImportError:
             try:
                 # Try importing from hoomd 1.x
                 from hoomd_script import data
             except ImportError:
                 raise ImportError('hoomd')
         box = data.boxdim(
             Lx=self.box.Lx,
             Ly=self.box.Ly,
             Lz=self.box.Lz,
             xy=self.box.xy,
             xz=self.box.xz,
             yz=self.box.yz,
             dimensions=self.box.dimensions,
         )
         snapshot = data.make_snapshot(
             N=len(self),
             box=box,
             particle_types=self.types,
         )
         np.copyto(
             snapshot.particles.typeid,
             np.array(self.typeid, dtype=snapshot.particles.typeid.dtype))
     for prop in PARTICLE_PROPERTIES:
         try:
             np.copyto(getattr(snapshot.particles, prop),
                       getattr(self, prop))
         except AttributeError:
             pass
     return snapshot
Beispiel #13
0
def plot_delone_triangulation(fpath, frame=0, fig=None, ax=None):
    with gsd.fl.GSDFile(fpath, 'rb') as f_gsd:
        n_frames_total = f_gsd.nframes
        if frame > n_frames_total:
            raise ValueError('frames beyond n_frames_total')
        #translate negative indices into positive domain:
        abs_frame = frame -(frame//n_frames_total)*n_frames_total
        pos = f_gsd.read_chunk(frame=abs_frame, name='particles/position')
        box_array = f_gsd.read_chunk(frame=0, name='configuration/box')
        box = boxdim(*box_array[0:3])

    if ax==None or fig==None:
        fig = plt.figure(figsize = figsize)
        ax = fig.add_subplot(111, aspect='equal', autoscale_on=False,
                             xlim=(-0.6*box.Lx, 0.6*box.Lx), ylim=(-0.6*box.Ly, 0.6*box.Ly))
    xlim = (-0.5*box.Lx, 0.5*box.Lx)
    ylim = (-0.5*box.Ly, 0.5*box.Ly)

    virtual_pos, virtual_ind = create_virtual_layer(pos, box)
    tri = Delaunay(virtual_pos[:, 0:2])
    ax.triplot(virtual_pos[:,0], virtual_pos[:,1], tri.simplices.copy(), color='black')
    ax.set_xlim(xlim)
    ax.set_ylim(ylim)
    return fig, ax
Beispiel #14
0
    def setUp(self):
        snap = data.make_snapshot(N=0, box=data.boxdim(Lx=10, Ly=10, Lz=10))

        self.system = init.read_snapshot(snap)
        self.mc = hpmc.integrate.convex_polyhedron(seed=123)
Beispiel #15
0
def read_pos(fname, ndim=3):
    from hoomd.data import boxdim
    Lx = 0
    Ly = 0
    Lz = 0
    xy = 0
    xz = 0
    yz = 0

    f_in = open(fname)

    positions = []  # list of particle positions
    orientations = []  # list of particle orientations
    types = []  # list of particle types

    t_rs = {}  # dictionary of position lists for defined particle types
    t_qs = {}  # dictionary of orientation lists for defined particle types
    t_params = {}  # additional particle parameters

    eof = 0  # count the number of frames
    for line in f_in:
        # get tokens on line
        tokens = line.split()
        if len(tokens) > 2:  # definition line
            if re.match('^def', line) is not None:
                # get particle type definition
                t = tokens[1]
                # add new definitions
                t_rs[t] = []
                t_qs[t] = []
                t_params[t] = {}

                tokens[2] = tokens[2].split('"')[-1]
                tokens[-1] = tokens[-1].split('"')[0]
                shape = tokens[2]
                t_params[t]['shape'] = shape
                if shape == "poly3d":
                    num_verts = int(tokens[3])
                    t_params[t]['verts'] = np.array([
                        float(n) for n in tokens[4:num_verts * 3 + 4]
                    ]).reshape(num_verts, 3)
                if shape == "spoly3d":
                    radius = float(tokens[3])
                    t_params[t]['radius'] = radius
                    num_verts = int(tokens[4])
                    t_params[t]['verts'] = np.array([
                        float(n) for n in tokens[5:num_verts * 3 + 5]
                    ]).reshape(num_verts, 3)
                if shape == "sphere":
                    diameter = float(tokens[3])
                    t_params[t]['diameter'] = diameter
                if shape == "cyl":
                    diameter = float(tokens[3])
                    t_params[t]['diameter'] = diameter
                    t_params[t]['length'] = float(tokens[4])
        if re.match('^box ', line) is not None:
            Lx = float(tokens[-3])
            Ly = float(tokens[-2])
            Lz = float(tokens[-1])
            box = boxdim(Lx, Ly, Lz)
            q = np.array([1, 0, 0, 0])
        elif re.match('^boxMatrix', line) is not None:
            # rotate the box matrix to be upper triangular
            pbox = np.array([float(f) for f in tokens[1:10]]).reshape(3, 3)
            a1 = pbox[:, 0]
            a2 = pbox[:, 1]
            a3 = pbox[:, 2]
            box, q = latticeToHoomd(a1, a2, a3, ndim)
        elif re.match('^eof',
                      line) is not None:  # clean up at the end of the frame
            eof += 1
            positions = np.concatenate([t_rs[t] for t in t_rs])
            orientations = np.concatenate([t_qs[t] for t in t_rs])
            types = []
            for t in t_rs:
                # build list of particle types with indices corresponding to other data structures
                types.extend([t] * len(t_rs[t]))

            # reset data structures for next frame
            t_rs = {}
            t_qs = {}
            # leave t_params intact... seems like the right thing to do
        else:
            for t in t_rs.keys():
                if re.match('^{}'.format(t), line) is not None:
                    # spheres don't have orientations in pos files
                    if len(tokens) > 4:
                        t_rs[t].append([float(f) for f in tokens[-7:-4]])
                        t_qs[t].append([float(f) for f in tokens[-4:]])
                    else:
                        t_rs[t].append([float(f) for f in tokens[-3:]])
                        t_qs[t].append([1., 0, 0, 0])

    # Try to recover from missing 'eof' string in single-frame files
    if eof == 0:
        positions = np.concatenate([t_rs[t] for t in t_rs])
        orientations = np.concatenate([t_qs[t] for t in t_rs])
        types = []
        for t in t_rs:
            # build list of particle types with indices corresponding to other data structures
            types.extend([t] * len(t_rs[t]))
        if len(positions) == 0:
            raise ValueError(
                "No frames read from {}. Invalid pos file?".format(fname))

    # rotate particles and positions, then wrap back into box just in case
    for i in range(len(positions)):
        positions[i] = quatRot(q, positions[i])
        positions[i], img = box.wrap(positions[i])
        orientations[i] = quatMult(q, orientations[i])
    f_in.close()
    return {
        'positions': positions,
        'orientations': orientations,
        'types': types,
        'param_dict': t_params,
        'box': box,
        'q': q
    }
Beispiel #16
0
    def test_access(self):
        N=2
        L=10
        context.initialize()
        self.snapshot = data.make_snapshot(N=N, box=data.boxdim(L=L, dimensions=2), particle_types=['A'])

        # sphere
        diam = 1.125;
        self.system = init.read_snapshot(self.snapshot)
        self.mc = hpmc.integrate.sphere(seed=2398, d=0.0)
        self.mc.shape_param.set('A', diameter=diam)
        self.assertAlmostEqual(self.mc.shape_param['A'].diameter, diam);
        del self.mc
        del self.system
        context.initialize()
        # ellipsoid
        a = 1.125;
        b = 0.238;
        c = 2.25;
        self.system = init.read_snapshot(self.snapshot)
        self.mc = hpmc.integrate.ellipsoid(seed=2398, d=0.0)
        self.mc.shape_param.set('A', a=a, b=b, c=c)
        self.assertAlmostEqual(self.mc.shape_param['A'].a, a);
        self.assertAlmostEqual(self.mc.shape_param['A'].b, b);
        self.assertAlmostEqual(self.mc.shape_param['A'].c, c);
        del self.mc
        del self.system
        context.initialize()


        # convex_polygon
        v = [(-1,-1), (1,-1), (1,1), (-1,1)];
        self.system = init.read_snapshot(self.snapshot)
        self.mc = hpmc.integrate.convex_polygon(seed=2398, d=0.1, a=0.1)
        self.mc.shape_param.set('A', vertices=v)
        diff = (np.array(v) - np.array(self.mc.shape_param['A'].vertices)).flatten();
        self.assertAlmostEqual(diff.dot(diff), 0);
        del self.mc
        del self.system
        context.initialize()

        # convex_spheropolygon
        v = [(-1,-1), (1,-1), (1,1), (-1,1)];
        r = 0.1234;
        self.system = init.read_snapshot(self.snapshot)
        self.mc = hpmc.integrate.convex_spheropolygon(seed=2398, d=0.1, a=0.1)
        self.mc.shape_param.set('A', vertices=v, sweep_radius=r)
        diff = (np.array(v) - np.array(self.mc.shape_param['A'].vertices)).flatten();
        self.assertAlmostEqual(diff.dot(diff), 0);
        self.assertAlmostEqual(self.mc.shape_param['A'].sweep_radius, r);
        del self.mc
        del self.system
        context.initialize()

        #simple_polygon
        v = [(-1,-1), (1,-1), (1,1), (-1,1)];
        self.system = init.read_snapshot(self.snapshot)
        self.mc = hpmc.integrate.simple_polygon(seed=2398, d=0.1, a=0.1)
        self.mc.shape_param.set('A', vertices=v)
        diff = (np.array(v) - np.array(self.mc.shape_param['A'].vertices)).flatten();
        self.assertAlmostEqual(diff.dot(diff), 0);
        del self.mc
        del self.system
        context.initialize()

        # polyhedron
        import math
        v = [(-0.5, -0.5, 0), (-0.5, 0.5, 0), (0.5, -0.5, 0), (0.5, 0.5, 0), (0,0, 1.0/math.sqrt(2)),(0,0,-1.0/math.sqrt(2))];
        f = [(0,4,1),(1,4,2),(2,4,3),(3,4,0),(0,5,1),(1,5,2),(2,5,3),(3,5,0)]
        r = 0.0;
        self.system = init.read_snapshot(self.snapshot)
        self.mc = hpmc.integrate.polyhedron(seed=10);
        self.mc.shape_param.set('A', vertices=v, faces =f, sweep_radius=r);
        diff = (np.array(v) - np.array(self.mc.shape_param['A'].vertices)).flatten();
        self.assertAlmostEqual(diff.dot(diff), 0);
        diff = (np.array(f) - np.array(self.mc.shape_param['A'].faces)).flatten();
        self.assertAlmostEqual(diff.dot(diff), 0);
        self.assertAlmostEqual(self.mc.shape_param['A'].sweep_radius, r);
        del self.mc
        del self.system
        context.initialize()

        # convex_polyhedron
        v = [(1,1,1), (1,-1,1), (-1,-1,1), (-1,1,1),(1,1,-1), (1,-1,-1), (-1,-1,-1), (-1,1,-1)];
        self.system = init.read_snapshot(self.snapshot)
        self.mc = hpmc.integrate.convex_polyhedron(seed=2398, d=0.1, a=0.1)
        self.mc.shape_param.set('A', vertices=v)
        diff = (np.array(v) - np.array(self.mc.shape_param['A'].vertices)).flatten();
        self.assertAlmostEqual(diff.dot(diff), 0);
        del self.mc
        del self.system
        context.initialize()

        # convex_spheropolyhedron
        v = [(1,1,1), (1,-1,1), (-1,-1,1), (-1,1,1),(1,1,-1), (1,-1,-1), (-1,-1,-1), (-1,1,-1)];
        r = 0.1234;
        self.system = init.read_snapshot(self.snapshot)
        self.mc = hpmc.integrate.convex_spheropolyhedron(seed=2398, d=0.1, a=0.1)
        self.mc.shape_param.set('A', vertices=v, sweep_radius=r)
        diff = (np.array(v) - np.array(self.mc.shape_param['A'].vertices)).flatten();
        self.assertAlmostEqual(diff.dot(diff), 0);
        self.assertAlmostEqual(self.mc.shape_param['A'].sweep_radius, r);
        del self.mc
        del self.system
        context.initialize()

        # faceted_sphere
        v =  [(-1,-1,-1),(-1,-1,1),(-1,1,-1),(-1,1,1),(1,-1,-1),(1,-1,1),(1,1,-1),(1,1,1)];
        offs = [-1]*6;
        norms =[(-1,0,0), (1,0,0), (0,1,0,), (0,-1,0), (0,0,1), (0,0,-1)];
        diam = 2;
        orig = (0,0,0);
        self.system = init.read_snapshot(self.snapshot)
        self.mc = hpmc.integrate.faceted_sphere(seed=10);
        self.mc.shape_param.set('A', normals=norms,
                                    offsets=offs,
                                    vertices=v,
                                    diameter=diam,
                                    origin=orig);

        diff = (np.array(v) - np.array(self.mc.shape_param['A'].vertices)).flatten();
        self.assertAlmostEqual(diff.dot(diff), 0);
        diff = (np.array(offs) - np.array(self.mc.shape_param['A'].offsets)).flatten();
        self.assertAlmostEqual(diff.dot(diff), 0);
        diff = (np.array(norms) - np.array(self.mc.shape_param['A'].normals)).flatten();
        self.assertAlmostEqual(diff.dot(diff), 0);
        diff = (np.array(orig) - np.array(self.mc.shape_param['A'].origin)).flatten();
        self.assertAlmostEqual(diff.dot(diff), 0);
        self.assertAlmostEqual(self.mc.shape_param['A'].diameter, diam);
        del self.mc
        del self.system
        context.initialize()

        # sphinx
        # GPU Sphinx is not built on most the time
        if not hoomd.context.exec_conf.isCUDAEnabled():
            cent = [(0,0,0), (0,0,1.15), (0,0,-1.15)]
            diams = [2,-2.2,-2.2];
            self.system = init.read_snapshot(self.snapshot)
            self.mc = hpmc.integrate.sphinx(seed=10);
            self.mc.shape_param.set('A', diameters=diams, centers=cent);
            diff = (np.array(cent) - np.array(self.mc.shape_param['A'].centers)).flatten();
            self.assertAlmostEqual(diff.dot(diff), 0);
            diff = (np.array(diams) - np.array(self.mc.shape_param['A'].diameters)).flatten();
            self.assertAlmostEqual(diff.dot(diff), 0);
            del self.mc
            del self.system
            context.initialize()

        # sphere_union
        cent = [(0,0,0), (0,0,1.15), (0,0,-1.15)]
        diams = [2,2.2,1.75];
        self.system = init.read_snapshot(self.snapshot)
        self.mc = hpmc.integrate.sphere_union(seed=10);
        self.mc.shape_param.set('A', diameters=diams, centers=cent);
        diff = (np.array(cent) - np.array(self.mc.shape_param['A'].centers)).flatten();
        self.assertAlmostEqual(diff.dot(diff), 0);
        for i,m in enumerate(self.mc.shape_param['A'].members):
            self.assertAlmostEqual(m.diameter, diams[i]);
        del self.mc
        del self.system
        del self.snapshot
        context.initialize()
Beispiel #17
0
def create_initial_configuration(traj):

    len_chrom = traj["len_chrom"]
    Cent = traj["Cent"]
    p_ribo = traj["p_ribo"]
    R = traj["R"]
    micron = traj["micron"]

    # Diffusing elements
    N_diffu = traj["N_diffu"]
    r_diffu = traj.get("diameter_diffu", 1) / 2

    # exit()
    p_origins = traj["p_origins"]

    if type(len_chrom) != list:
        len_chrom, _ = load_lengths_and_centro(len_chrom, traj["coarse"])

    if type(Cent) != list:
        _, Cent = load_lengths_and_centro(Cent, traj["coarse"])

    if type(p_origins) != list:
        p_origins = load_ori_position(traj["p_origins"], traj["ori_type"],
                                      len_chrom, traj["coarse"])
    p_ribo = [[int(position) // int(traj["coarse"] // 1000), length]
              for position, length in p_ribo]

    two_types = traj.get("two_types", False)
    p_second = traj.get("p_second", [])
    dstrength = traj.get("dstrength", 0)
    strengths = None
    if p_second != []:

        # Assign delta_strength
        if dstrength != 0:
            strengths = []
            for bands, pos in zip(p_second, p_origins):
                strengths.append([])
                for p in pos:
                    found = False
                    for Intervals in bands:
                        if Intervals[0] < p < Intervals[1]:
                            strengths[-1].append(dstrength)
                            found = True
                            break
                    if not found:
                        strengths[-1].append(1)

        ps = []
        for ch in p_second:
            ps.append([])
            for p1, p2 in ch:
                ps[-1] += range(p1, p2)
        p_second = ps

    boundaries = traj.get("boundaries", False)
    if boundaries:
        extra_boundaries = load_boundaries(coarse=traj["coarse"])
    print("strengths", strengths)
    # Yeast case
    spb = traj["spb"]
    nucleole = traj["nucleole"]
    telomere = traj["telomere"]
    microtubule_length = traj["microtubule_length"] * micron
    special_start = traj["special_start"]
    visu = traj["visu"]
    dump_hic = traj["dump_hic"]

    # Scenari
    diff_bind_when_free = traj["diff_bind_when_free"]

    # Simulation parameters

    Np = len(len_chrom)
    assert (len(len_chrom) == len(Cent) == len(p_ribo))
    if special_start:
        Sim = create_init_conf_yeast(len_chrom=len_chrom,
                                     dist_centro=Cent,
                                     p_ribo=p_ribo,
                                     Radius=R - 1,
                                     Mt=microtubule_length)
    else:
        Sim = []

    spbp = 0 if not spb else 1

    Total_particle = sum(len_chrom) + N_diffu * 2 + spbp
    list_nuc = [
        list(range(start, start + size)) if size != 0 else []
        for start, size in p_ribo
    ]
    # print(list_nuc)
    # exit()

    snapshot = data.make_snapshot(N=Total_particle,
                                  box=data.boxdim(L=2 * R),
                                  bond_types=['polymer'])

    spbb = Np if spb else 0

    if visu:
        spbb = 0

    bond_diffu = 0
    if diff_bind_when_free:
        bond_diffu = N_diffu

    snapshot.bonds.resize(sum(len_chrom) - len(len_chrom) + bond_diffu + spbb)

    bond_list = ['Mono_Mono', 'Diff_Diff', 'Mono_Diff']

    if spb:
        bond_list += ["Spb_Cen"]
    if nucleole:
        bond_list += ["Mono_Nuc", "Nuc_Nuc"]

    snapshot.bonds.types = bond_list

    plist = ['Mono', 'Ori', 'Diff', 'S_Diff', 'F_Diff', "I_Diff"]
    if two_types:
        plist.append("Mono1")

    if spb:
        plist.append("Spb")
        if visu:
            plist.append("Cen")
    if nucleole:
        plist += ['Nuc', 'A_Nuc', 'P_Nuc']

    if telomere:
        plist += ["Telo"]

    snapshot.particles.types = plist

    offset_bond = 0
    offset_particle = 0
    lPolymers = []

    ################################################
    # Polymer chains
    Cen_pos = []
    list_ori = []
    for i in range(Np):

        found_cen = False
        npp = len_chrom[i]  # Number of particles
        # Position of origin of replication
        pos_origins = p_origins[i]

        istrength = None
        if strengths is not None:
            istrength = strengths[i]

        if Sim == []:
            initp = 2 * np.random.rand(3) - 1
        else:
            # print(i)
            initp = Sim.molecules[i].coords[0]

        for p in range(npp - 1):
            inuc = 0
            if nucleole:
                if p in list_nuc[i]:
                    inuc += 1
                if p + 1 in list_nuc[i]:
                    inuc += 1

            snapshot.bonds.group[offset_bond + p] = [
                offset_particle + p, offset_particle + p + 1
            ]
            if inuc == 0:
                snapshot.bonds.typeid[offset_bond + p] = bond_list.index(
                    'Mono_Mono')  # polymer_A
            if inuc == 1:
                snapshot.bonds.typeid[offset_bond + p] = bond_list.index(
                    'Mono_Nuc')  # polymer_A
            if inuc == 2:
                snapshot.bonds.typeid[offset_bond + p] = bond_list.index(
                    'Nuc_Nuc')  # polymer_A

        offset_bond += npp - 1

        for p in range(npp):
            # print(offset_bond, offset_bond + p)
            if Sim == []:
                new = 2 * (2 * np.random.rand(3) - 1)
                while linalg.norm(initp + new) > R - 1:
                    new = 2 * (2 * np.random.rand(3) - 1)

                initp += new
            else:
                initp = Sim.molecules[i].coords[p]

            snapshot.particles.position[offset_particle + p] = initp
            # snapshot.particles.diameter[offset_particle + p] = 1

            if p in pos_origins:
                list_ori.append(offset_particle + p)

            if visu and (p in pos_origins):
                snapshot.particles.typeid[offset_particle + p] = plist.index(
                    'Ori')  # Ori
            else:
                snapshot.particles.typeid[offset_particle + p] = plist.index(
                    'Mono')  # A
                if two_types and p in p_second[i]:
                    snapshot.particles.typeid[offset_particle +
                                              p] = plist.index('Mono1')  # A

            if spb and p == Cent[i]:
                Cen_pos.append(offset_particle + p)
                if visu:
                    snapshot.particles.typeid[offset_particle +
                                              p] = plist.index('Cen')  # A
                found_cen = True

            if nucleole and p in list_nuc[i]:
                snapshot.particles.typeid[offset_particle +
                                          p] = plist.index('Nuc')

            if telomere and (p == 0 or p == npp - 1):
                snapshot.particles.typeid[offset_particle +
                                          p] = plist.index('Telo')

            if boundaries and p in extra_boundaries[i]:
                snapshot.particles.typeid[offset_particle +
                                          p] = plist.index('Telo')

        lPolymers.append(
            Polymer(i,
                    offset_particle,
                    offset_particle + npp - 1,
                    [po + offset_particle for po in pos_origins],
                    strengths=istrength))
        offset_particle += npp

        assert (found_cen == spb)

    phic = 0
    if dump_hic:
        phic = 0 + offset_particle - 1
    ###################################################
    # SPD
    tag_spb = None
    if spb:
        tag_spb = 0 + offset_particle
        # print(tag_spb)
        # print(snapshot.particles[offset_particle])
        snapshot.particles.position[offset_particle] = [-R + 0.1, 0, 0]
        snapshot.particles.typeid[offset_particle] = plist.index('Spb')
        offset_particle += 1

        if not visu:
            for i in range(Np):
                # print(offset_particle - 1, Cen_pos[i])
                snapshot.bonds.group[offset_bond] = [
                    offset_particle - 1, Cen_pos[i]
                ]
                snapshot.bonds.typeid[offset_bond] = bond_list.index(
                    'Spb_Cen')  # polymer_A

                offset_bond += 1
    ############################################################
    # Diffusing elements
    # Defining useful classes

    # Defining particles and bonds for the simulation
    p_tag_list = []
    for i in range(N_diffu):
        npp = 2  # Number of particles

        initp = (R - 2) * (2 * np.random.rand(3) - 1)
        while linalg.norm(initp) > R - 1:
            initp = (R - 2) * (2 * np.random.rand(3) - 1)
        if diff_bind_when_free:
            for p in range(npp - 1):
                snapshot.bonds.group[offset_bond + p] = [
                    offset_particle + p, offset_particle + p + 1
                ]
                snapshot.bonds.typeid[offset_bond + p] = bond_list.index(
                    'Diff_Diff')  # Diff_Diff
            offset_bond += npp - 1

        p_tag_list.append([])
        for p in range(npp):

            # print(offset_bond, offset_bond + p)
            if diff_bind_when_free:
                new = 2 * (2 * np.random.rand(3) - 1)
                while linalg.norm(initp + new) > R - 1:
                    new = 2 * (2 * np.random.rand(3) - 1)
                    # print(initp,new,R,linalg.norm(initp + new))
                    # exit()
                initp += new
            else:
                initp = (R - 2) * (2 * np.random.rand(3) - 1)
                while linalg.norm(initp) > R - 1:
                    initp = (R - 2) * (2 * np.random.rand(3) - 1)

            snapshot.particles.position[offset_particle + p] = initp
            # snapshot.particles.mass[offset_particle + p] = r_diffu**3 * 2**3
            snapshot.particles.typeid[offset_particle + p] = plist.index(
                "Diff")  # Diffu
            p_tag_list[-1].append(offset_particle + p)
        offset_particle += npp

    # Load the configuration

    for i, p in enumerate(snapshot.bonds.group):
        if p[0] == p[1]:
            print(i, p)

    return snapshot, phic, tag_spb, bond_list, plist, Cen_pos, lPolymers, list_ori, p_tag_list
Beispiel #18
0
    def test_access(self):
        N = 2
        L = 10
        context.initialize()
        self.snapshot = data.make_snapshot(N=N,
                                           box=data.boxdim(L=L, dimensions=2),
                                           particle_types=['A'])

        # sphere
        diam = 1.125
        self.system = init.read_snapshot(self.snapshot)
        self.mc = hpmc.integrate.sphere(seed=2398, d=0.0)
        self.mc.shape_param.set('A', diameter=diam)
        self.assertAlmostEqual(self.mc.shape_param['A'].diameter, diam)
        del self.mc
        del self.system
        context.initialize()
        # ellipsoid
        a = 1.125
        b = 0.238
        c = 2.25
        self.system = init.read_snapshot(self.snapshot)
        self.mc = hpmc.integrate.ellipsoid(seed=2398, d=0.0)
        self.mc.shape_param.set('A', a=a, b=b, c=c)
        self.assertAlmostEqual(self.mc.shape_param['A'].a, a)
        self.assertAlmostEqual(self.mc.shape_param['A'].b, b)
        self.assertAlmostEqual(self.mc.shape_param['A'].c, c)
        del self.mc
        del self.system
        context.initialize()

        # convex_polygon
        v = [(-1, -1), (1, -1), (1, 1), (-1, 1)]
        self.system = init.read_snapshot(self.snapshot)
        self.mc = hpmc.integrate.convex_polygon(seed=2398, d=0.1, a=0.1)
        self.mc.shape_param.set('A', vertices=v)
        diff = (np.array(v) -
                np.array(self.mc.shape_param['A'].vertices)).flatten()
        self.assertAlmostEqual(diff.dot(diff), 0)
        del self.mc
        del self.system
        context.initialize()

        # convex_spheropolygon
        v = [(-1, -1), (1, -1), (1, 1), (-1, 1)]
        r = 0.1234
        self.system = init.read_snapshot(self.snapshot)
        self.mc = hpmc.integrate.convex_spheropolygon(seed=2398, d=0.1, a=0.1)
        self.mc.shape_param.set('A', vertices=v, sweep_radius=r)
        diff = (np.array(v) -
                np.array(self.mc.shape_param['A'].vertices)).flatten()
        self.assertAlmostEqual(diff.dot(diff), 0)
        self.assertAlmostEqual(self.mc.shape_param['A'].sweep_radius, r)
        del self.mc
        del self.system
        context.initialize()

        #simple_polygon
        v = [(-1, -1), (1, -1), (1, 1), (-1, 1)]
        self.system = init.read_snapshot(self.snapshot)
        self.mc = hpmc.integrate.simple_polygon(seed=2398, d=0.1, a=0.1)
        self.mc.shape_param.set('A', vertices=v)
        diff = (np.array(v) -
                np.array(self.mc.shape_param['A'].vertices)).flatten()
        self.assertAlmostEqual(diff.dot(diff), 0)
        del self.mc
        del self.system
        context.initialize()

        # polyhedron
        import math
        v = [(-0.5, -0.5, 0), (-0.5, 0.5, 0), (0.5, -0.5, 0), (0.5, 0.5, 0),
             (0, 0, 1.0 / math.sqrt(2)), (0, 0, -1.0 / math.sqrt(2))]
        f = [(0, 4, 1), (1, 4, 2), (2, 4, 3), (3, 4, 0), (0, 5, 1), (1, 5, 2),
             (2, 5, 3), (3, 5, 0)]
        r = 0.0
        self.system = init.read_snapshot(self.snapshot)
        self.mc = hpmc.integrate.polyhedron(seed=10)
        self.mc.shape_param.set('A', vertices=v, faces=f, sweep_radius=r)
        diff = (np.array(v) -
                np.array(self.mc.shape_param['A'].vertices)).flatten()
        self.assertAlmostEqual(diff.dot(diff), 0)
        diff = (np.array(f) -
                np.array(self.mc.shape_param['A'].faces)).flatten()
        self.assertAlmostEqual(diff.dot(diff), 0)
        self.assertAlmostEqual(self.mc.shape_param['A'].sweep_radius, r)
        del self.mc
        del self.system
        context.initialize()

        # convex_polyhedron
        v = [(1, 1, 1), (1, -1, 1), (-1, -1, 1), (-1, 1, 1), (1, 1, -1),
             (1, -1, -1), (-1, -1, -1), (-1, 1, -1)]
        self.system = init.read_snapshot(self.snapshot)
        self.mc = hpmc.integrate.convex_polyhedron(seed=2398, d=0.1, a=0.1)
        self.mc.shape_param.set('A', vertices=v)
        diff = (np.array(v) -
                np.array(self.mc.shape_param['A'].vertices)).flatten()
        self.assertAlmostEqual(diff.dot(diff), 0)
        del self.mc
        del self.system
        context.initialize()

        # convex_spheropolyhedron
        v = [(1, 1, 1), (1, -1, 1), (-1, -1, 1), (-1, 1, 1), (1, 1, -1),
             (1, -1, -1), (-1, -1, -1), (-1, 1, -1)]
        r = 0.1234
        self.system = init.read_snapshot(self.snapshot)
        self.mc = hpmc.integrate.convex_spheropolyhedron(seed=2398,
                                                         d=0.1,
                                                         a=0.1)
        self.mc.shape_param.set('A', vertices=v, sweep_radius=r)
        diff = (np.array(v) -
                np.array(self.mc.shape_param['A'].vertices)).flatten()
        self.assertAlmostEqual(diff.dot(diff), 0)
        self.assertAlmostEqual(self.mc.shape_param['A'].sweep_radius, r)
        del self.mc
        del self.system
        context.initialize()

        # faceted_sphere
        v = [(-1, -1, -1), (-1, -1, 1), (-1, 1, -1), (-1, 1, 1), (1, -1, -1),
             (1, -1, 1), (1, 1, -1), (1, 1, 1)]
        offs = [-1] * 6
        norms = [(-1, 0, 0), (1, 0, 0), (
            0,
            1,
            0,
        ), (0, -1, 0), (0, 0, 1), (0, 0, -1)]
        diam = 2
        orig = (0, 0, 0)
        self.system = init.read_snapshot(self.snapshot)
        self.mc = hpmc.integrate.faceted_sphere(seed=10)
        self.mc.shape_param.set('A',
                                normals=norms,
                                offsets=offs,
                                vertices=v,
                                diameter=diam,
                                origin=orig)

        diff = (np.array(v) -
                np.array(self.mc.shape_param['A'].vertices)).flatten()
        self.assertAlmostEqual(diff.dot(diff), 0)
        diff = (np.array(offs) -
                np.array(self.mc.shape_param['A'].offsets)).flatten()
        self.assertAlmostEqual(diff.dot(diff), 0)
        diff = (np.array(norms) -
                np.array(self.mc.shape_param['A'].normals)).flatten()
        self.assertAlmostEqual(diff.dot(diff), 0)
        diff = (np.array(orig) -
                np.array(self.mc.shape_param['A'].origin)).flatten()
        self.assertAlmostEqual(diff.dot(diff), 0)
        self.assertAlmostEqual(self.mc.shape_param['A'].diameter, diam)
        del self.mc
        del self.system
        context.initialize()

        # sphinx
        # GPU Sphinx is not built on most the time
        if not hoomd.context.current.device.cpp_exec_conf.isCUDAEnabled():
            cent = [(0, 0, 0), (0, 0, 1.15), (0, 0, -1.15)]
            diams = [2, -2.2, -2.2]
            self.system = init.read_snapshot(self.snapshot)
            self.mc = hpmc.integrate.sphinx(seed=10)
            self.mc.shape_param.set('A', diameters=diams, centers=cent)
            diff = (np.array(cent) -
                    np.array(self.mc.shape_param['A'].centers)).flatten()
            self.assertAlmostEqual(diff.dot(diff), 0)
            diff = (np.array(diams) -
                    np.array(self.mc.shape_param['A'].diameters)).flatten()
            self.assertAlmostEqual(diff.dot(diff), 0)
            del self.mc
            del self.system
            context.initialize()

        # sphere_union
        cent = [(0, 0, 0), (0, 0, 1.15), (0, 0, -1.15)]
        diams = [2, 2.2, 1.75]
        self.system = init.read_snapshot(self.snapshot)
        self.mc = hpmc.integrate.sphere_union(seed=10)
        self.mc.shape_param.set('A', diameters=diams, centers=cent)
        diff = (np.array(cent) -
                np.array(self.mc.shape_param['A'].centers)).flatten()
        self.assertAlmostEqual(diff.dot(diff), 0)
        for i, m in enumerate(self.mc.shape_param['A'].members):
            self.assertAlmostEqual(m.diameter, diams[i])
        del self.mc
        del self.system
        del self.snapshot
        context.initialize()
Beispiel #19
0
    def setUp(self):
        snap = data.make_snapshot(N=0,box=data.boxdim(Lx = 10, Ly = 10, Lz = 10))

        self.system = init.read_snapshot(snap)
        self.mc = hpmc.integrate.convex_polyhedron(seed=123)
Beispiel #20
0
def simulate(traj_filename):

    with open(traj_filename, "r") as f:
        traj = json.load(f)

    seed = traj["seed"]
    len_chrom = traj["len_chrom"]
    Cent = traj["Cent"]
    p_ribo = traj["p_ribo"]
    R = traj["R"]
    micron = traj["micron"]
    data_folder = traj["data_folder"]

    # Diffusing elements
    N_diffu = traj["N_diffu"]
    cut_off_inte = traj["cut_off_inte"]
    p_inte = traj["p_inte"]
    dt = traj["dt"]
    p_origins = traj["p_origins"]

    # Yeast case
    spb = traj["spb"]
    nucleole = traj["nucleole"]
    telomere = traj["telomere"]
    microtubule_length = traj["microtubule_length"] * micron
    diameter_nuc = traj["diameter_nuc"] * micron
    special_start = traj["special_start"]
    Activ_Origins = traj["Activ_Origins"]
    visu = traj["visu"]
    dump_hic = traj["dump_hic"]

    # Scenari
    diff_alone = traj["diff_alone"]
    diff_bind_when_free = traj["diff_bind_when_free"]
    diff_bind_when_on_DNA = traj["diff_bind_when_on_DNA"]
    replicate_DNA = traj["replicate_DNA"]

    np.random.seed(seed)
    hoomd.context.initialize("--mode=cpu")

    if diff_alone:
        # Check
        assert (diff_bind_when_free is False)
        assert (diff_bind_when_on_DNA is False)

    # End of parameter
    ##########################################

    #########################################
    # Define polymer bonding and positions

    Np = len(len_chrom)
    assert (len(len_chrom) == len(Cent) == len(p_ribo))
    if special_start:
        Sim = create_init_conf_yeast(len_chrom=len_chrom,
                                     dist_centro=Cent,
                                     p_ribo=p_ribo,
                                     Radius=R,
                                     Mt=microtubule_length)
    else:
        Sim = []

    spbp = 0 if not spb else 1

    Total_particle = sum(len_chrom) + N_diffu * 2 + spbp
    list_nuc = [
        list(range(start, start + size)) if size != 0 else []
        for start, size in p_ribo
    ]
    # print(list_nuc)
    # exit()

    snapshot = data.make_snapshot(N=Total_particle,
                                  box=data.boxdim(L=2 * R),
                                  bond_types=['polymer'])

    spbb = Np if spb else 0

    if visu:
        spbb = 0

    bond_diffu = 0
    if diff_bind_when_free:
        bond_diffu = N_diffu

    snapshot.bonds.resize(sum(len_chrom) - len(len_chrom) + bond_diffu + spbb)

    bond_list = ['Mono_Mono', 'Diff_Diff', 'Mono_Diff']
    if spb:
        bond_list += ["Spb_Cen"]
    if nucleole:
        bond_list += ["Mono_Nuc", "Nuc_Nuc"]
    snapshot.bonds.types = bond_list

    plist = ['Mono', 'Ori', 'Diff', 'A_Ori', 'P_Ori', 'S_Diff', 'F_Diff']

    if spb:
        plist.append("Spb")
    if nucleole:
        plist += ['Nuc', 'A_Nuc', 'P_Nuc']

    if telomere:
        plist += ["Telo"]

    snapshot.particles.types = plist

    offset_bond = 0
    offset_particle = 0
    lPolymers = []

    ################################################
    # Polymer chains
    Cen_pos = []
    for i in range(Np):

        found_cen = False
        npp = len_chrom[i]  # Number of particles
        # Position of origin of replication
        pos_origins = p_origins[i]

        if Sim == []:
            initp = 2 * np.random.rand(3) - 1
        else:
            # print(i)
            initp = Sim.molecules[i].coords[0]

        for p in range(npp - 1):
            inuc = 0
            if nucleole:
                if p in list_nuc[i]:
                    inuc += 1
                if p + 1 in list_nuc[i]:
                    inuc += 1

            snapshot.bonds.group[offset_bond + p] = [
                offset_particle + p, offset_particle + p + 1
            ]
            if inuc == 0:
                snapshot.bonds.typeid[offset_bond + p] = bond_list.index(
                    'Mono_Mono')  # polymer_A
            if inuc == 1:
                snapshot.bonds.typeid[offset_bond + p] = bond_list.index(
                    'Mono_Nuc')  # polymer_A
            if inuc == 2:
                snapshot.bonds.typeid[offset_bond + p] = bond_list.index(
                    'Nuc_Nuc')  # polymer_A

        offset_bond += npp - 1

        for p in range(npp):
            # print(offset_bond, offset_bond + p)
            if Sim == []:
                new = 2 * (2 * np.random.rand(3) - 1)
                while linalg.norm(initp + new) > R - 1:
                    new = 2 * (2 * np.random.rand(3) - 1)

                initp += new
            else:
                initp = Sim.molecules[i].coords[p]

            snapshot.particles.position[offset_particle + p] = initp

            if p in pos_origins:
                snapshot.particles.typeid[offset_particle + p] = plist.index(
                    'Ori')  # Ori
            else:
                snapshot.particles.typeid[offset_particle + p] = plist.index(
                    'Mono')  # A

            if spb and p == Cent[i]:
                Cen_pos.append(offset_particle + p)

                found_cen = True

            if nucleole and p in list_nuc[i]:
                snapshot.particles.typeid[offset_particle +
                                          p] = plist.index('Nuc')

            if telomere and (p == 0 or p == npp - 1):
                snapshot.particles.typeid[offset_particle +
                                          p] = plist.index('Telo')

        lPolymers.append(
            Polymer(i, offset_particle, offset_particle + npp - 1,
                    [po + offset_particle for po in pos_origins]))
        offset_particle += npp

        assert (found_cen == spb)

    phic = 0
    if dump_hic:
        phic = 0 + offset_particle - 1
    ###################################################
    # SPD
    if spb:
        tag_spb = 0 + offset_particle
        # print(tag_spb)
        # print(snapshot.particles[offset_particle])
        snapshot.particles.position[offset_particle] = [-R + 0.1, 0, 0]
        snapshot.particles.typeid[offset_particle] = plist.index('Spb')
        offset_particle += 1

        if not visu:
            for i in range(Np):
                # print(offset_particle - 1, Cen_pos[i])
                snapshot.bonds.group[offset_bond] = [
                    offset_particle - 1, Cen_pos[i]
                ]
                snapshot.bonds.typeid[offset_bond] = bond_list.index(
                    'Spb_Cen')  # polymer_A

                offset_bond += 1

    ############################################################
    # Diffusing elements
    # Defining useful classes

    # Defining particles and bonds for the simulation

    for i in range(N_diffu):
        npp = 2  # Number of particles

        initp = (R - 2) * (2 * np.random.rand(3) - 1)
        while linalg.norm(initp) > R - 1:
            initp = (R - 2) * (2 * np.random.rand(3) - 1)
        if diff_bind_when_free:
            for p in range(npp - 1):
                snapshot.bonds.group[offset_bond + p] = [
                    offset_particle + p, offset_particle + p + 1
                ]
                snapshot.bonds.typeid[offset_bond + p] = bond_list.index(
                    'Diff_Diff')  # Diff_Diff
            offset_bond += npp - 1

        for p in range(npp):
            # print(offset_bond, offset_bond + p)
            if diff_bind_when_free:
                new = 2 * (2 * np.random.rand(3) - 1)
                while linalg.norm(initp + new) > R - 1:
                    new = 2 * (2 * np.random.rand(3) - 1)
                    # print(initp,new,R,linalg.norm(initp + new))
                    # exit()
                initp += new
            else:
                initp = (R - 1) * (2 * np.random.rand(3) - 1)

            snapshot.particles.position[offset_particle + p] = initp
            snapshot.particles.typeid[offset_particle + p] = plist.index(
                "Diff")  # Diffu

        offset_particle += npp

    # Load the configuration

    for i, p in enumerate(snapshot.bonds.group):
        if p[0] == p[1]:
            print(i, p)

    system = init.read_snapshot(snapshot)

    for i, p in enumerate(system.particles):
        # print(p)
        # exit()
        assert p.tag == i

    for i, b in enumerate(system.bonds):
        if b.a == b.b:
            print(b.a, b.b)

            raise
        # print(p)
        # exit()
        assert b.tag == i
    ###############################################

    ###############################################
    # Defining force field:
    harmonic = md.bond.harmonic()
    harmonic.bond_coeff.set(bond_list, k=330.0, r0=1)

    harmonic.bond_coeff.set('Mono_Diff', k=10.0, r0=1)

    if spb:
        harmonic.bond_coeff.set('Spb_Cen', k=1000.0, r0=microtubule_length)

    if nucleole:
        harmonic.bond_coeff.set('Nuc_Nuc', k=330, r0=diameter_nuc)
        harmonic.bond_coeff.set('Mono_Nuc',
                                k=330,
                                r0=diameter_nuc / 2. + 1. / 2)

    nl = md.nlist.tree(r_buff=0.4, check_period=1)

    # Potential for warmup
    gauss = md.pair.gauss(r_cut=3.0, nlist=nl)

    gauss.pair_coeff.set(plist, plist, epsilon=1.0, sigma=1.0)

    if nucleole:
        for ip1, p1 in enumerate(plist):
            for p2 in plist[ip1:]:
                inuc = 0
                if "Nuc" in p1:
                    inuc += 1
                if "Nuc" in p2:
                    inuc += 1
                if inuc == 1:
                    gauss.pair_coeff.set(p1,
                                         p2,
                                         epsilon=.5,
                                         sigma=0.5 + diameter_nuc / 2.,
                                         r_cut=(0.5 + diameter_nuc / 2.) * 3)
                if inuc == 2:
                    gauss.pair_coeff.set(p1,
                                         p2,
                                         epsilon=1.0,
                                         sigma=diameter_nuc,
                                         r_cut=3 * diameter_nuc)
    # gauss.pair_coeff.set('A', 'A', epsilon=1.0, sigma=1.0)
    # gauss.pair_coeff.set('A', 'A', epsilon=1.0, sigma=1.0)

    # Spherical confinement
    sphere = md.wall.group()
    sphere.add_sphere(r=R, origin=(0.0, 0.0, 0.0), inside=True)

    wall_force_slj = md.wall.slj(sphere, r_cut=3.0)
    wall_force_slj.force_coeff.set(plist, epsilon=1.0, sigma=1.0, r_cut=1.12)

    if nucleole:
        wall_force_slj.force_coeff.set('Nuc',
                                       epsilon=1.0,
                                       sigma=diameter_nuc,
                                       r_cut=diameter_nuc * 1.12)
    if telomere:
        wall_force_slj.force_coeff.set(plist, epsilon=2.0, sigma=1.5, r_cut=3)

    # Group;
    all_beads = group.all()
    if spb:
        Spb_g = group.tag_list(name="Spb", tags=[tag_spb])
        pspb = [p.position for p in Spb_g]
        print(pspb)

        all_move = group.difference(name="move", a=all_beads, b=Spb_g)
    else:
        all_move = all_beads
    # Log
    logger = analyze.log(filename=data_folder + 'mylog.log',
                         period=1000,
                         quantities=[
                             'temperature', 'potential_energy',
                             'kinetic_energy', 'volume', 'pressure'
                         ],
                         overwrite=True)

    # Warmup
    converged = False
    dt = 0.005
    while not converged and not visu:
        try:

            method = md.integrate.mode_minimize_fire(group=all_move, dt=dt)
            while not (method.has_converged()):

                if spb:
                    pspb = [p.position for p in Spb_g]
                    """
                    print(pspb)
                    for cen in Cen_pos:
                        cent_tmp = system.particles[cen]
                        print(cent_tmp.position)
                        print(linalg.norm(np.array(pspb[0])-np.array(cent_tmp.position)))
                        print(R * microtubule_length)
                    """
                # exit()
                hoomd.run(100)
            converged = True
        except:
            converged = False
            dt /= 2.
            print(dt)
            # Restore positions
            for ip, p in enumerate(snapshot.particles.position):

                system.particles[ip].position = p
    """
    gauss.disable()

    slj=md.pair.slj(r_cut=2, nlist=nl)
    slj.pair_coeff.set(plist,plist,sigma=1,epsilon=1,r_cut=1.12)
    print("Second minimizing")
    method=md.integrate.mode_minimize_fire(group=all_beads,dt=0.05)
    while not(method.has_converged()):
       hoomd.run(100)
    """
    # hoomd.run(1000000)
    # method.disable()

    # Dumping

    if visu:
        xml = deprecated.dump.xml(filename=data_folder + "atoms.hoomdxml",
                                  period=None,
                                  group=all_beads,
                                  vis=True)
        exit()
    # gsd = dump.gsd(filename=data_folder + "atoms.gsd",period=None,group=all_beads)
    dcd = dump.dcd(filename=data_folder + 'poly.dcd',
                   period=100,
                   overwrite=True)

    # Dynamics

    t0 = time.time()
    md.integrate.mode_standard(dt=0.01)
    method = md.integrate.langevin(group=all_move, kT=1, seed=seed)
    snp = system  # .take_snapshot()

    def Change_type(typep, particle_list, snp, msg=""):
        # print(particle_list)
        for p in particle_list:
            snp.particles[p].type = typep
        if particle_list != [] and msg != "":
            print(msg)

    def Bind(typeb, bondlist, snp):
        btags = []
        for b1, b2 in bondlist:
            btags.append(snp.bonds.add(typeb, b1, b2))
        return btags

    def Release(btags, snp):
        for bt in btags:
            snp.bonds.remove(bt)

    def AddParticle(position, type):
        snp.particles.add(type)
        snp.particles[-1].position = position

    def Shift(bonds, snp):
        for tag, new in bonds:
            b = snp.bonds.get(tag)
            btype = "" + b.type
            fork = b.b + 0
            snp.bonds.remove(tag)

            # print(b.type)
            snp.bonds.add(btype, new, fork)
            # print(new,b)
            # print(dir(snp.bonds))
            # b.a = new

    group_diffu = group.type(name="Diff", type='Diff')

    if Activ_Origins != []:
        group_origin = group.type(name="Activ_Ori", type=Activ_Origins[0])
        if len(Activ_Origins) > 1:
            for t in Activ_Origins[1:]:
                group_origin = group.union(name="Activ_origin",
                                           a=group_origin,
                                           b=group.type(name="tmp", type=t))

    r_hic = []
    if dump_hic:
        group_hic = group.tags(name="hic", tag_min=0, tag_max=phic)
    # nl.tune(warmup=1,steps=1000)

    for i in range(100):

        # Chek that the microtubule length is correct
        if spb:
            for cen in Cen_pos:
                cent_tmp = system.particles[cen]
                # print(cent_tmp.position)
                d = linalg.norm(
                    np.array(pspb[0]) - np.array(cent_tmp.position))
                if d > 2 * microtubule_length:
                    print("MT too long", d)
                    exit()

        # Dump the Hi-Cs

        # system.restore_snapshot(snp)
        hoomd.run(1000)

        if dump_hic:
            ph = np.array([p.position for p in group_hic])

            D = cdist(ph, ph)
            D[D < 2] = 1
            D[D >= 2] = 0
            np.fill_diagonal(D, 0)
            if r_hic != []:
                r_hic += D
            else:
                r_hic = D
            np.save(data_folder + "/hic", r_hic)

        # snp = system.take_snapshot()

        # update the position of the monomer by updating bonds

        for iP, P in enumerate(lPolymers):
            verbose = False
            # if iP == 9:
            #    verbose = True
            bind_diff, diff_diff, shifted_bonds, \
                passivated_origin, to_release, alone = P.increment_time(
                    1, verbose)

            Change_type('P_Ori', passivated_origin, snp,
                        msg="")  # Passivated origin

            if not diff_alone:
                Shift(shifted_bonds, snp)
                # Bond tags to release (Alone particle)
                Release(to_release, snp)

                if diff_bind_when_free:
                    # Pair of diffu to attach
                    Bind("Diff_Diff", bind_diff, snp)
                    # We cannot use the single diff anymore
                    Change_type("S_Diff", alone, snp)
                    # Change type for pair of diff diff
                    Change_type("Diff", diff_diff, snp)

        group_diffu.force_update()
        group_origin.force_update()
        # Update Type because of (Ori to passivated)

        # Update group

        # Find new interacting particles

        # First check if Dimer are close from one origin

        p_diffu = np.array([p.position for p in group_diffu])
        tag_diffu = [p.tag for p in group_diffu]

        p_origin = np.array([p.position for p in group_origin])
        tag_origin = [p.tag for p in group_origin]

        if tag_diffu != [] and tag_origin != []:
            distances = cdist(p_diffu, p_origin)
            print(distances.shape)
            # Reorder the distances with the dimer tags
            Indexes = []
            PTags = []
            # t0 = time.time()
            Btags = []
            # Groups Diff-Diff by bond to compute the distances

            if diff_bind_when_free:
                for b in system.bonds:
                    if b.type == 'Diff_Diff' and system.particles[
                            b.a].type == 'Diff':
                        Indexes.append(tag_diffu.index(b.a))
                        Indexes.append(tag_diffu.index(b.b))
                        Btags.append(b.tag)
                        PTags.append([b.a, b.b])

                # print(time.time() -t0)

                d2 = distances[Indexes][::2] / 2 + distances[Indexes][1::2] / 2
            else:
                n_diffu = len(tag_diffu)
                Indexes = list(range(n_diffu))
                Btags = [None] * n_diffu
                PTags = [[t] for t in tag_diffu]
                d2 = distances[Indexes]

            activated = []
            for iD, (btag, ptags) in enumerate(zip(Btags, PTags)):
                # print(d2.shape)
                # print(d2[iD])
                for iorigin, di in enumerate(d2[iD]):
                    if iorigin in activated:
                        # Needed because we don't want an origin to be activated
                        # twice
                        continue
                    if di > cut_off_inte:
                        continue
                    if np.random.rand() > p_inte:
                        continue

                    for P in lPolymers:
                        if not P.has_origin(tag_origin[iorigin]):
                            continue

                        if diff_bind_when_free and \
                           not diff_bind_when_on_DNA:
                            Release([btag], snp)  # Break the dimer
                            btag = None  # We need btag only in the case where they stays attached

                        if not diff_alone:
                            # Or attached separatly or already bound:

                            if diff_bind_when_free:

                                # We are sure they are two and we can
                                # start
                                Change_type('F_Diff', ptags,
                                            snp)  # Diffusive element attached
                                particular_origin = tag_origin[iorigin]
                                new_btags = Bind(
                                    "Mono_Diff",
                                    [[particular_origin, ptags[0]],
                                     [particular_origin, ptags[1]]], snp)
                                Change_type('A_Ori', [particular_origin], snp)
                                activated.append(iorigin)
                                P.add_fork(ptags, particular_origin, new_btags,
                                           btag)

                            else:
                                Change_type('F_Diff', ptags,
                                            snp)  # Diffusive element attached
                                particular_origin = tag_origin[iorigin]
                                new_btags = Bind(
                                    "Mono_Diff",
                                    [[particular_origin, ptags[0]]], snp)
                                start = P.attach_one_diff(
                                    ptags[0], particular_origin, new_btags[0])

                                if start:
                                    # get particles involves
                                    p1, p2 = P.get_diff_at_origin(
                                        particular_origin)
                                    if diff_bind_when_on_DNA:
                                        btag = Bind("Diff_Diff",
                                                    [[p1[0], p2[0]]], snp)[0]

                                    Change_type('A_Ori', [particular_origin],
                                                snp)
                                    P.add_fork([p1[0], p2[0]],
                                               particular_origin,
                                               [p1[1], p2[1]], btag)

                        else:
                            # start when touched and release
                            particular_origin = tag_origin[iorigin]
                            activated.append(iorigin)
                            Change_type('A_Ori', [particular_origin], snp)
                            P.add_fork([None, None], particular_origin,
                                       [None, None], None)

                        break
                    # If we arrive there it means that one interaction has beeen
                    # found
                    break
        # t0 = time.time()
        with open(data_folder + "polymer_timing.dat", "wb") as f:
            cPickle.dump(lPolymers, f)
        # print(time.time() -t0)
        # Then if it is the case attach them according to p law to the origin

    print(gauss.get_energy(all_beads), wall_force_slj.get_energy(all_beads))
    print(time.time() - t0)
Beispiel #21
0
def animate_gsd(fpath, savefile = None, periodic = False, center_fixed = True, interval = 100, figsize = (12, 12), rcut = 1.4,\
               neighb = False):
    """
    Create animation from a gsd file, where fpath is the path+filename to the gsd file.
    lx, ly - dimensions of the rectangular simulation box;
    savefile - filename for saving the animation. Not trying to save if the value is None;
    periodic - show with periodic boundary conditions if True, let particles migrate out of box if False;
    interval - time interval between frames in microseconds;
    
    return fig, ax
    """
    def init():
        scat.set_offsets(pos[0, :, :])
        
        time_text.set_text('')
        return scat, time_text

    def update(frame_number):
        scat.set_offsets(pos[frame_number, :, :])
        time_text.set_text('frame = {} of {}'.format(frame_number, n_frames))
        if neighb:
            five_ind = np.where(neighbor_num[frame_number, :] == 5)[0]
            seven_ind = np.where(neighbor_num[frame_number, :] == 7)[0]
            five_scat.set_offsets(pos[frame_number, five_ind, :])
            seven_scat.set_offsets(pos[frame_number, seven_ind, :])
        else:
            five_scat.set_offsets(empty_pos)
            seven_scat.set_offsets(empty_pos)
        return scat, time_text, five_scat, seven_scat
    
    with gsd.fl.GSDFile(fpath, 'rb') as f_gsd:
        n_frames = f_gsd.nframes
        n_p = f_gsd.read_chunk(frame=0, name='particles/N')
        box = f_gsd.read_chunk(frame=0, name='configuration/box')
        pos = np.zeros((n_frames, n_p[0], 2))
        neighbor_num = np.zeros((n_frames, int(n_p)), dtype = int)
        pos_frame = f_gsd.read_chunk(frame=0, name='particles/position')
        pos_frame_raw = pos_frame
        mean_pos_0 = np.mean(pos_frame, axis = 0)
        for j_frame in range(n_frames):
            pos_m1 = pos_frame
            pos_m1_raw = pos_frame_raw
            pos_frame_raw = f_gsd.read_chunk(frame=j_frame, name='particles/position')
            if not periodic:
                pos_frame = correct_jumps(pos_frame_raw, pos_m1, pos_m1_raw, box[0], box[1])
            else:
                pos_frame = pos_frame_raw
            if center_fixed:
                pos_frame -= np.mean(pos_frame, axis = 0) - mean_pos_0
            pos[j_frame, :, :] = pos_frame[:, 0:2]
            if neighb:
                boxdim_box = boxdim(box[0], box[1], box[2])
                neighbor_list, neighbor_num[j_frame, :] = find_neighbors_delone(pos[j_frame, :,:], boxdim_box, rcut = rcut)
    
    fig = plt.figure(figsize = figsize)
    ax = fig.add_subplot(111, aspect='equal', autoscale_on=False,
                         xlim=(-box[0], box[0]), ylim=(-box[1], box[1]))

    scat = ax.scatter(pos[0, :, 0], pos[0, :, 1],
                      s = 3,
                      facecolors='blue')
    empty_pos = np.zeros(0)
    if neighb:
        five_ind_0 = np.where(neighbor_num[0, :] == 5)[0]
        seven_ind_0 = np.where(neighbor_num[0, :] == 7)[0]
        seven_scat = ax.scatter(pos[0, seven_ind_0, 0], pos[0, seven_ind_0, 1],
                          s = 5,
                          facecolors='green')
        five_scat = ax.scatter(pos[0, five_ind_0, 0], pos[0, five_ind_0, 1],
                          s = 5,
                          facecolors='red')
    else:
        seven_scat = ax.scatter(empty_pos, empty_pos)
        five_scat = ax.scatter(empty_pos, empty_pos)
    time_text = ax.text(0.02, 1.05, '', transform=ax.transAxes)

    animation = FuncAnimation(fig, update, interval=interval, frames=n_frames, blit=True)
    
    if not savefile == None:
        try:
            animation.save(savefile, fps=30)
        except Exception as ee: print(ee)
    return fig, ax, animation
Beispiel #22
0
def read_pos(fname, ndim=3):
    from hoomd.data import boxdim
    Lx=0; Ly=0; Lz=0; xy=0; xz=0; yz=0;

    f_in = open(fname)

    positions=[] # list of particle positions
    orientations=[] # list of particle orientations
    types=[] # list of particle types

    t_rs={} # dictionary of position lists for defined particle types
    t_qs={} # dictionary of orientation lists for defined particle types
    t_params={} # additional particle parameters

    eof = 0 # count the number of frames
    for line in f_in:
        # get tokens on line
        tokens = line.split()
        if len(tokens)>2: # definition line
            if re.match('^def', line) is not None:
                # get particle type definition
                t = tokens[1]
                # add new definitions
                t_rs[t]=[]
                t_qs[t]=[]
                t_params[t]={}

                tokens[2]=tokens[2].split('"')[-1]
                tokens[-1]=tokens[-1].split('"')[0]
                shape = tokens[2]
                t_params[t]['shape'] = shape
                if shape == "poly3d":
                    num_verts=int(tokens[3])
                    t_params[t]['verts']=np.array([float(n) for n in tokens[4:num_verts*3+4]]).reshape(num_verts,3)
                if shape == "spoly3d":
                    radius = float(tokens[3])
                    t_params[t]['radius'] = radius
                    num_verts = int(tokens[4])
                    t_params[t]['verts']=np.array([float(n) for n in tokens[5:num_verts*3+5]]).reshape(num_verts,3)
                if shape == "sphere":
                    diameter = float(tokens[3])
                    t_params[t]['diameter'] = diameter
                if shape == "cyl":
                    diameter = float(tokens[3])
                    t_params[t]['diameter'] = diameter
                    t_params[t]['length'] = float(tokens[4])
        if re.match('^box ', line) is not None:
            Lx=float(tokens[-3])
            Ly=float(tokens[-2])
            Lz=float(tokens[-1])
            box = boxdim(Lx, Ly, Lz)
            q = np.array([1,0,0,0])
        elif re.match('^boxMatrix',line) is not None:
            # rotate the box matrix to be upper triangular
            pbox=np.array([float(f) for f in tokens[1:10]]).reshape(3,3)
            a1 = pbox[:,0]
            a2 = pbox[:,1]
            a3 = pbox[:,2]
            box, q = latticeToHoomd(a1, a2, a3, ndim)
        elif re.match('^eof',line) is not None: # clean up at the end of the frame
            eof += 1
            positions = np.concatenate([t_rs[t] for t in t_rs])
            orientations = np.concatenate([t_qs[t] for t in t_rs])
            types = []
            for t in t_rs:
                # build list of particle types with indices corresponding to other data structures
                types.extend([t]*len(t_rs[t]))

            # reset data structures for next frame
            t_rs = {}
            t_qs = {}
            # leave t_params intact... seems like the right thing to do
        else:
            for t in t_rs.keys():
                if re.match('^{}'.format(t), line) is not None:
                    # spheres don't have orientations in pos files
                    if len(tokens) > 4:
                        t_rs[t].append([float(f) for f in tokens[-7:-4]])
                        t_qs[t].append([float(f) for f in tokens[-4:]])
                    else:
                        t_rs[t].append([float(f) for f in tokens[-3:]])
                        t_qs[t].append([1.,0,0,0])

    # Try to recover from missing 'eof' string in single-frame files
    if eof == 0:
        positions = np.concatenate([t_rs[t] for t in t_rs])
        orientations = np.concatenate([t_qs[t] for t in t_rs])
        types = []
        for t in t_rs:
            # build list of particle types with indices corresponding to other data structures
            types.extend([t]*len(t_rs[t]))
        if len(positions) == 0:
            raise ValueError("No frames read from {}. Invalid pos file?".format(fname))

    # rotate particles and positions, then wrap back into box just in case
    for i in range(len(positions)):
        positions[i] = quatRot(q, positions[i])
        positions[i], img = box.wrap(positions[i])
        orientations[i] = quatMult(q, orientations[i])
    f_in.close()
    return {'positions':positions, 'orientations':orientations, 'types':types, 'param_dict':t_params, 'box':box, 'q':q}