Пример #1
0
 def setUp(self):
     self._name = None;
     hexuc = hoomd.lattice.hex(a=2.0);
     system = init.read_snapshot(hexuc.get_snapshot());
     system.replicate(nx=8, ny=8, nz=1);
     self.snapshot2d = system.take_snapshot(particles=True);
     context.initialize();
     bccuc = hoomd.lattice.bcc(a=4.0);
     system = init.read_snapshot(bccuc.get_snapshot());
     system.replicate(nx=4, ny=4, nz=4);
     self.snapshot3d = system.take_snapshot(particles=True);
     # self.snapshot3d = data.make_snapshot(N=20, box=system.box, particle_types=['A']);
     context.initialize();
     v2d = 0.33*np.array([(-1,-1), (1,-1), (1,1), (-1,1)]);
     v2dup = v2d+0.1*np.array([(1,-1), (-1,-1), (1,-1), (1,1)]);
     r = 0.1234;
     rup = 0.3;
     v3d = 0.33*np.array([(1,1,1), (1,-1,1), (-1,-1,1), (-1,1,1),(1,1,-1), (1,-1,-1), (-1,-1,-1), (-1,1,-1)]);
     v3dup = v3d + 0.1*np.array([(-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.a = 0.5;
     self.d = 0.5;
     self.params = dict(
         sphere=dict(first=dict(diameter=1.5), second=dict(diameter=3.0)),
         ellipsoid=dict(first=dict(a=0.5, b=0.54, c=0.35), second=dict(a=0.98*0.5, b=1.05*0.54, c=1.1*0.35)),
         convex_polygon=dict(first=dict(vertices=v2d), second=dict(vertices=v2dup)),
         convex_spheropolygon=dict(first=dict(vertices=v2d, sweep_radius=r), second=dict(vertices=v2dup, sweep_radius=rup)),
         simple_polygon=dict(first=dict(vertices=v2d), second=dict(vertices=v2dup)),
         convex_polyhedron=dict(first=dict(vertices=v3d), second=dict(vertices=v3dup)),
         convex_spheropolyhedron=dict(first=dict(vertices=v3d, sweep_radius=r), second=dict(vertices=v3dup, sweep_radius=rup))
     )
    def test_head_to_tail_antiparallel(self):
        self.snapshot.particles.position[0, :] = (0, 0, 0)
        self.snapshot.particles.position[1, :] = (self.diameter, 0, 0)
        self.snapshot.particles.orientation[0, :] = (1, 0, 0, 0)
        self.snapshot.particles.orientation[1, :] = (0, 0, 1, 0)
        init.read_snapshot(self.snapshot)
        self.mc = hpmc.integrate.sphere(seed=10, a=0, d=0)
        self.mc.shape_param.set('A', diameter=self.diameter, orientable=True)
        self.patch = jit.patch.user(mc=self.mc,
                                    r_cut=self.r_cut,
                                    code=self.dipole_dipole)
        self.log = analyze.log(filename=None,
                               quantities=['hpmc_patch_energy'],
                               period=0,
                               overwrite=True)
        hoomd.run(0, quiet=True)
        self.assertEqual(self.log.query('hpmc_patch_energy'), self.lamb)

        # Disable patch with log = True and check logged energy is correct
        self.patch.disable(log=True)
        hoomd.run(2, quiet=True)
        self.assertEqual(self.log.query('hpmc_patch_energy'), self.lamb)

        # Re-enable patch and check energy is correct again
        self.patch.enable()
        hoomd.run(2, quiet=True)
        self.assertEqual(self.log.query('hpmc_patch_energy'), self.lamb)

        # Disable patch w/o log option and check energy is 0
        self.patch.disable()
        hoomd.run(2, quiet=True)
        self.assertEqual(self.log.query('hpmc_patch_energy'), 0)
Пример #3
0
 def setUp(self):
     self._name = None;
     hexuc = hoomd.lattice.hex(a=2.0);
     system = init.read_snapshot(hexuc.get_snapshot());
     system.replicate(nx=8, ny=8, nz=1);
     self.snapshot2d = system.take_snapshot(particles=True);
     context.initialize();
     bccuc = hoomd.lattice.bcc(a=4.0);
     system = init.read_snapshot(bccuc.get_snapshot());
     system.replicate(nx=4, ny=4, nz=4);
     self.snapshot3d = system.take_snapshot(particles=True);
     # self.snapshot3d = data.make_snapshot(N=20, box=system.box, particle_types=['A']);
     context.initialize();
     v2d = 0.33*np.array([(-1,-1), (1,-1), (1,1), (-1,1)]);
     v2dup = v2d+0.1*np.array([(1,-1), (-1,-1), (1,-1), (1,1)]);
     r = 0.1234;
     rup = 0.3;
     v3d = 0.33*np.array([(1,1,1), (1,-1,1), (-1,-1,1), (-1,1,1),(1,1,-1), (1,-1,-1), (-1,-1,-1), (-1,1,-1)]);
     v3dup = v3d + 0.1*np.array([(-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.a = 0.5;
     self.d = 0.5;
     self.params = dict(
         sphere=dict(first=dict(diameter=1.5,orientable=False), second=dict(diameter=3.0,orientable=True)),
         ellipsoid=dict(first=dict(a=0.5, b=0.54, c=0.35), second=dict(a=0.98*0.5, b=1.05*0.54, c=1.1*0.35)),
         convex_polygon=dict(first=dict(vertices=v2d), second=dict(vertices=v2dup)),
         convex_spheropolygon=dict(first=dict(vertices=v2d, sweep_radius=r), second=dict(vertices=v2dup, sweep_radius=rup)),
         simple_polygon=dict(first=dict(vertices=v2d), second=dict(vertices=v2dup)),
         convex_polyhedron=dict(first=dict(vertices=v3d), second=dict(vertices=v3dup)),
         convex_spheropolyhedron=dict(first=dict(vertices=v3d, sweep_radius=r), second=dict(vertices=v3dup, sweep_radius=rup))
     )
 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)
Пример #5
0
 def run_test_1(self, name, dim):
     filename = "{}.gsd".format(name)
     mc_cls = hoomd.hpmc.integrate.__dict__[name]
     if dim == 3:
         self.system = init.read_snapshot(self.snapshot3d)
     else:
         self.system = init.read_snapshot(self.snapshot2d)
     self.mc = mc_cls(seed=2398)
     self.mc.shape_param.set('A', **self.params[name]['first'])
     self.gsd = hoomd.dump.gsd(filename, group=hoomd.group.all(), period=1, overwrite=True);
     self.gsd.dump_state(self.mc)
     hoomd.run(5);
     self.mc.shape_param.set('A', **self.params[name]['second']);
     self.mc.set_params(a=self.a, d=self.d);
     hoomd.run(5);
     self.gsd.disable();
     self.gsd = None;
     with self.assertRaises(RuntimeError):
         self.mc.restore_state();
Пример #6
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)
Пример #7
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)
Пример #8
0
 def run_test_1(self, name, dim):
     filename = "{}.gsd".format(name)
     mc_cls = hoomd.hpmc.integrate.__dict__[name]
     if dim == 3:
         self.system = init.read_snapshot(self.snapshot3d)
     else:
         self.system = init.read_snapshot(self.snapshot2d)
     self.mc = mc_cls(seed=2398)
     self.mc.shape_param.set('A', **self.params[name]['first'])
     self.gsd = hoomd.dump.gsd(filename, group=hoomd.group.all(), period=1, overwrite=True);
     self.gsd.dump_state(self.mc)
     hoomd.run(5);
     self.mc.shape_param.set('A', **self.params[name]['second']);
     self.mc.set_params(a=self.a, d=self.d);
     hoomd.run(5);
     self.gsd.disable();
     self.gsd = None;
     with self.assertRaises(RuntimeError):
         self.mc.restore_state();
    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)
Пример #10
0
def create_empty(**kwargs):
    snap = data.make_snapshot(**kwargs);
    return init.read_snapshot(snap);
Пример #11
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)
Пример #12
0
def simulate(syst, n_steps, data_folder="./repli", params={}, seed=False):
    import time as Time
    global t0
    t0 = Time.time()

    def time(where):
        global t0
        print(where, "elapsed %.1f" % (Time.time() - t0))
        t0 = Time.time()

    stretch = syst["stretch"]
    verbose = syst["verbose"]

    data_folder = os.path.join(data_folder)

    os.makedirs(data_folder, exist_ok=True)

    print(data_folder)

    time("Start")
    snapshot, syst = initialize_snap(syst)
    time("Initialize")
    length_steps = syst["length_steps"]  # 50000

    if comm.get_rank() == 0:
        snapshot = create_snapshot(snapshot, syst, seed=seed)

    snapshot.broadcast()

    system = init.read_snapshot(snapshot)

    bond = md.bond.harmonic(name="mybond")
    bond.bond_coeff.set(syst["bond_list"], k=100.0, r0=0.84)
    bond.bond_coeff.set("weak", k=10.0, r0=0.84)

    nl = md.nlist.cell()
    #nl = md.nlist.tree()

    sc = 0.5
    gauss = md.pair.gauss(r_cut=3.0 * sc, nlist=nl)
    gauss.pair_coeff.set(syst["plist"],
                         syst["plist"],
                         epsilon=4.0,
                         sigma=1.0 * sc)
    gauss.pair_coeff.set("fDNA", syst["plist"], epsilon=0.5, sigma=.5 * sc)
    gauss.pair_coeff.set("uDNA", syst["plist"], epsilon=0, sigma=1.0 * sc)

    ##################################################
    # wall
    sphere = md.wall.group()
    r_extrap = 0.5
    r0 = 0.5

    sphere.add_sphere(r=syst["Rf"], origin=(0.0, 0.0, 0.0), inside=True)
    wall_force_slj = md.wall.lj(sphere, r_cut=1.12)
    wall_force_slj.force_coeff.set(syst["plist"],
                                   epsilon=1,
                                   sigma=0.5 + r0 * 1.0,
                                   r_cut=1.12 * (0.5 + r0 * 1.0),
                                   mode="shift",
                                   r_extrap=0.5 + r0 * r_extrap)

    all = group.all()
    period = length_steps

    if stretch:
        period = 1000
    gsd = dump.gsd(group=all,
                   filename=os.path.join(data_folder, 'poly.gsd'),
                   period=period,
                   overwrite=True,
                   dynamic=["attribute", "topology"],
                   phase=0)

    ##################################################
    # Run the simulation

    sim_dt = 0.01

    snp = system
    md.integrate.mode_standard(dt=sim_dt)
    if seed:
        seed = 0
    else:
        seed = np.random.randint(10000)

    method = md.integrate.langevin(group=all, kT=1, seed=seed, dscale=False)

    group_hic = all  # group.tags(name="hic", tag_min=0, tag_max=Nparticule)

    r_hic = []
    Oml = []
    Nel = []

    cdists = []

    print(len(snapshot.particles.typeid))
    Free_firing_factor = [
        i for i in range(syst["np"])
        if snapshot.particles.typeid[i] == syst["plist"].index("fFactor")
    ]
    Unrep = [
        i for i in range(syst["np"])
        if snapshot.particles.typeid[i] == syst["plist"].index("uDNA")
    ]

    g_firing_factor = group.tag_list("free", Free_firing_factor)
    g_unrep = group.type("uDNA", update=True)

    if stretch:
        md.force.constant(fx=-2.0, fy=0, fz=0, group=group.tag_list("0", [0]))
        md.force.constant(fx=2.0,
                          fy=0,
                          fz=0,
                          group=group.tag_list("0",
                                               [syst["len_polymers"][0] - 1]))

    print("Firing factors", Free_firing_factor)
    #hoomd.run(length_steps*10, profile=False,quiet=True)

    #from repli3d.replication import replicator
    global iname
    iname = 0

    def gname(name):
        global iname
        iname += 1
        return name + str(iname)

    time("End define all")
    l_ch = []

    for i, X_len in enumerate(syst["len_polymers"]):
        start = sum(syst["len_polymers"][:i])
        rand = list(
            set(
                np.random.choice(range(start, X_len + start),
                                 int(syst["ori_density"] * X_len))))
        if "origin_position" in syst:
            Potential_ori = syst["origin_position"]
        else:
            Potential_ori = rand
        print("Potential ori", Potential_ori)
        l_ch.append(
            chromosome(start,
                       start + X_len - 1,
                       Potential_ori,
                       attached=syst["attached"],
                       verbose=syst["verbose"],
                       verbose_replicon=syst["verbose"]))

    hoomd.run(syst["equi"], profile=False, quiet=True)
    time("Start loop")
    for i in range(n_steps):
        time("Start run")
        hoomd.run(length_steps, profile=False, quiet=True)
        #snapshot = system.take_snapshot(all=True)
        # snapshot.broadcast()
        time("End run")

        p_ori_tag = []
        for X in l_ch:
            p_ori_tag.extend(X.l_ori)

        p_ori = np.array(
            [system.particles.get(ptag).position for ptag in p_ori_tag])

        free = np.array([p.position for p in g_firing_factor])
        free_tag = [p.tag for p in g_firing_factor]

        if len(p_ori) > 0 and len(free) > 0:
            D1 = cdist(p_ori, free)
            if stretch:
                d = 4
            else:
                d = 2
            D1[D1 > d] = 0
            used_ori = []
            used_free = []
            for ifree, free_number in enumerate(free_tag):
                for ipori, pori_number in enumerate(p_ori_tag):

                    # insert the replicon correctly in the list
                    if D1[ipori,
                          ifree] > 1e-7 and pori_number not in used_ori and free_number not in used_free:

                        if verbose:
                            print("Activate", pori_number)
                        for X in l_ch:
                            if pori_number in X.l_ori:
                                X.add_forks(free_number,
                                            pori_number,
                                            system,
                                            time=i)
                        # Remove ori
                        # Remove firing factor
                        g_firing_factor = group.difference(
                            gname("delta2"), g_firing_factor,
                            group.tag_list(gname("rand"), [free_number]))

                        used_ori.append(pori_number)
                        used_free.append(free_number)

                        continue
        if verbose:
            for iX, X in enumerate(l_ch):
                print("Chromosome %i" % iX)
                print("List replicator")
                for repl in X.l_replicator:
                    print(repl.left, repl.right)
                print("End list")
        time("Ori association")
        hoomd.run(length_steps, profile=True, quiet=False)
        time("Run length %i" % i)
        # get list of position where to add material

        if i % 15 == 0:
            for X in l_ch:
                Frees = X.propagate(system, g_unrep, time=i)
                g_firing_factor = group.union(
                    gname("delta3"), g_firing_factor,
                    group.tag_list(gname("rand"), Frees))
            time("Propagation ")
            if verbose:
                print("Firing", [p.tag for p in g_firing_factor])

        for iX, X in enumerate(l_ch):
            np.save(data_folder + "/rep_%i.npy" % iX, X.rfd)
Пример #13
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()
Пример #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)
    def test_lattice(self):
        N = 128
        latticeq = [[1, 0, 0, 0] for i in range(N)]
        k = 10.0
        kalt = np.exp(15)
        dx2d = np.array([0.1, 0.1, 0.0])
        theta = np.pi / 6
        eng_check2d = round(N * k * dx2d.dot(dx2d), 3)
        dx3d = np.array([0.1, 0.1, 0.1])
        eng_check3d = round(N * k * dx3d.dot(dx3d), 3)

        dq = np.array([np.cos(theta / 2.0), 0., 0., np.sin(theta / 2)])
        ddq = np.array([1., 0., 0., 0.]) - dq
        eng_checkq = round(10.0 * k * N * ddq.dot(ddq), 3)

        hexuc = hoomd.lattice.hex(a=2.0)
        self.system = init.read_snapshot(hexuc.get_snapshot())
        self.system.replicate(nx=8, ny=8, nz=1)

        self.snapshot2d = self.system.take_snapshot(particles=True)
        #data.make_snapshot(N=N, box=data.boxdim(L=L, dimensions=3), particle_types=['A'])
        lattice2d = []
        if hoomd.comm.get_rank() == 0:
            lattice2d = self.snapshot2d.particles.position[:]

        self.snapshot2d_s = data.make_snapshot(N=N,
                                               box=self.system.box,
                                               particle_types=['A'])
        if hoomd.comm.get_rank() == 0:
            self.snapshot2d_s.particles.position[:] = self.snapshot2d.particles.position[:] + dx2d
            self.snapshot2d_s.particles.orientation[:] = np.array(
                [dq for _ in range(N)])
        del self.system
        context.initialize()

        bccuc = hoomd.lattice.bcc(a=2.0)
        self.system = init.read_snapshot(bccuc.get_snapshot())
        self.system.replicate(nx=4, ny=4, nz=4)
        self.snapshot3d = self.system.take_snapshot(particles=True)
        #data.make_snapshot(N=N, box=data.boxdim(L=L, dimensions=3), particle_types=['A'])
        lattice3d = []
        if hoomd.comm.get_rank() == 0:
            lattice3d = self.snapshot3d.particles.position[:]
        self.snapshot3d_s = data.make_snapshot(N=N,
                                               box=self.system.box,
                                               particle_types=['A'])
        if hoomd.comm.get_rank() == 0:
            self.snapshot3d_s.particles.position[:] = self.snapshot3d.particles.position[:] + dx3d
            self.snapshot3d_s.particles.orientation[:] = np.array(
                [dq for _ in range(N)])
        del self.system
        context.initialize()

        # sphere
        print("****************************************")
        print("*               sphere                 *")
        print("****************************************")
        # d = 0.0014284726343172743, p = 0.20123046875
        uein = 1.5  # kT
        diam = 1.0
        self.system = init.read_snapshot(self.snapshot3d)
        self.mc = hpmc.integrate.sphere(seed=2398, d=0.0)
        self.mc.shape_param.set('A', diameter=diam)
        self.run_test(latticep=lattice3d,
                      latticeq=[],
                      k=k,
                      kalt=kalt,
                      q=0,
                      qalt=0,
                      uein=1.5,
                      snapshot_s=self.snapshot3d_s,
                      eng_check=eng_check3d,
                      d=0.001428)
        self.tear_down()

        # ellipsoid
        print("****************************************")
        print("*              ellipsoid               *")
        print("****************************************")
        # a = 0.00038920117896296716, p = 0.2035860456051452
        # d = 0.0014225507698958867, p = 0.19295361127422195
        a = 0.5
        b = 0.54
        c = 0.35
        uein = 3.0  # kT
        self.system = init.read_snapshot(self.snapshot3d)
        self.mc = hpmc.integrate.ellipsoid(seed=2398, d=0.0, a=0.0)
        self.mc.shape_param.set('A', a=a, b=b, c=c)
        self.run_test(latticep=lattice3d,
                      latticeq=latticeq,
                      k=k,
                      kalt=kalt,
                      q=k * 10.0,
                      qalt=kalt * 10.0,
                      uein=3.0,
                      snapshot_s=self.snapshot3d_s,
                      eng_check=(eng_check3d + eng_checkq),
                      a=0.000389,
                      d=0.001423)
        self.tear_down()

        # convex_polygon
        print("****************************************")
        print("*           convex_polygon             *")
        print("****************************************")
        # a = 0.001957745443687172, p = 0.19863574351978172
        # d = 0.0017185407622231329, p = 0.2004306126443531
        self.system = init.read_snapshot(self.snapshot2d)
        v = 0.33 * np.array([(-1, -1), (1, -1), (1, 1), (-1, 1)])
        self.mc = hpmc.integrate.convex_polygon(seed=2398, d=0.0, a=0.0)
        self.mc.shape_param.set('A', vertices=v)
        self.run_test(latticep=lattice2d,
                      latticeq=latticeq,
                      k=k,
                      kalt=kalt,
                      q=k * 10.0,
                      qalt=kalt * 10.0,
                      uein=1.5,
                      snapshot_s=self.snapshot2d_s,
                      eng_check=(eng_check2d + eng_checkq),
                      a=0.001958,
                      d=0.001719)
        self.tear_down()

        # convex_spheropolygon
        print("****************************************")
        print("*        convex_spheropolygon          *")
        print("****************************************")

        self.system = init.read_snapshot(self.snapshot2d)
        v = 0.33 * np.array([(-1, -1), (1, -1), (1, 1), (-1, 1)])
        r = 0.1234
        self.mc = hpmc.integrate.convex_spheropolygon(seed=2398, d=0.0, a=0.0)
        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.run_test(latticep=lattice2d,
                      latticeq=latticeq,
                      k=k,
                      kalt=kalt,
                      q=k * 10.0,
                      qalt=kalt * 10.0,
                      uein=None,
                      snapshot_s=self.snapshot2d_s,
                      eng_check=(eng_check2d + eng_checkq))
        self.tear_down()

        #simple_polygon
        print("****************************************")
        print("*           simple_polygon             *")
        print("****************************************")

        self.system = init.read_snapshot(self.snapshot2d)
        v = 0.33 * np.array([(-1, -1), (1, -1), (1, 1), (-1, 1)])
        self.mc = hpmc.integrate.simple_polygon(seed=2398, d=0.0, a=0.0)
        self.mc.shape_param.set('A', vertices=v)
        self.run_test(latticep=lattice2d,
                      latticeq=latticeq,
                      k=k,
                      kalt=kalt,
                      q=k * 10.0,
                      qalt=kalt * 10.0,
                      uein=None,
                      snapshot_s=self.snapshot2d_s,
                      eng_check=(eng_check2d + eng_checkq))
        self.tear_down()

        # polyhedron
        print("****************************************")
        print("*             polyhedron               *")
        print("****************************************")

        self.system = init.read_snapshot(self.snapshot3d)
        v = 0.33 * np.array([(-0.5, -0.5, -0.5), (-0.5, -0.5, 0.5),
                             (-0.5, 0.5, -0.5), (-0.5, 0.5, 0.5),
                             (0.5, -0.5, -0.5), (0.5, -0.5, 0.5),
                             (0.5, 0.5, -0.5), (0.5, 0.5, 0.5)])
        f = [(7, 3, 1, 5), (7, 5, 4, 6), (7, 6, 2, 3), (3, 2, 0, 1),
             (0, 2, 6, 4), (1, 0, 4, 5)]
        r = 0.0
        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
        print("****************************************")
        print("*          convex_polyhedron           *")
        print("****************************************")
        #a = 0.00038920117896296716, p = 0.2035860456051452
        #d = 0.0014225507698958867, p = 0.19295361127422195
        self.system = init.read_snapshot(self.snapshot3d)
        v = 0.33 * np.array([(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.mc = hpmc.integrate.convex_polyhedron(seed=2398, d=0.0, a=0.0)
        self.mc.shape_param.set('A', vertices=v)
        self.run_test(latticep=lattice3d,
                      latticeq=latticeq,
                      k=k,
                      kalt=kalt,
                      q=k * 10.0,
                      qalt=kalt * 10.0,
                      uein=3.0,
                      snapshot_s=self.snapshot3d_s,
                      eng_check=(eng_check3d + eng_checkq),
                      a=0.0003892,
                      d=0.00142255)
        self.tear_down()

        # convex_spheropolyhedron
        print("****************************************")
        print("*       convex_spheropolyhedron        *")
        print("****************************************")

        self.system = init.read_snapshot(self.snapshot3d)
        v = 0.33 * np.array([(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.mc = hpmc.integrate.convex_spheropolyhedron(seed=2398,
                                                         d=0.0,
                                                         a=0.0)
        self.mc.shape_param.set('A', vertices=v, sweep_radius=r)
        self.run_test(latticep=lattice3d,
                      latticeq=latticeq,
                      k=k,
                      kalt=kalt,
                      q=k * 10.0,
                      qalt=kalt * 10.0,
                      uein=None,
                      snapshot_s=self.snapshot3d_s,
                      eng_check=(eng_check3d + eng_checkq))
        self.tear_down()

        # faceted_sphere
        print("****************************************")
        print("*            faceted_sphere            *")
        print("****************************************")

        self.system = init.read_snapshot(self.snapshot3d)
        v = 0.33 * np.array([(-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 = 1.0
        orig = (0, 0, 0)
        self.mc = hpmc.integrate.faceted_sphere(seed=10, d=0.0, a=0.0)
        self.mc.shape_param.set('A',
                                normals=norms,
                                offsets=offs,
                                vertices=v,
                                diameter=diam,
                                origin=orig)
        self.run_test(latticep=lattice3d,
                      latticeq=latticeq,
                      k=k,
                      kalt=kalt,
                      q=k * 10.0,
                      qalt=kalt * 10.0,
                      uein=None,
                      snapshot_s=self.snapshot3d_s,
                      eng_check=(eng_check3d + eng_checkq))
        self.tear_down()

        # sphinx
        print("****************************************")
        print("*               sphinx                 *")
        print("****************************************")

        self.system = init.read_snapshot(self.snapshot3d)
        cent = [(0, 0, 0), (0, 0, 1.15), (0, 0, -1.15)]
        diams = [1, -1.2, -1.2]
        self.mc = hpmc.integrate.sphinx(seed=10, d=0.0, a=0.0)
        self.mc.shape_param.set('A', diameters=diams, centers=cent)
        self.run_test(latticep=lattice3d,
                      latticeq=latticeq,
                      k=k,
                      kalt=kalt,
                      q=k * 10.0,
                      qalt=kalt * 10.0,
                      uein=None,
                      snapshot_s=self.snapshot3d_s,
                      eng_check=(eng_check3d + eng_checkq))
        self.tear_down()

        # sphere_union
        print("****************************************")
        print("*            sphere_union              *")
        print("****************************************")

        self.system = init.read_snapshot(self.snapshot3d)
        cent = [(0, 0, 0), (0, 0, 0.15), (0, 0, -0.15)]
        diams = [1, 1, 1]
        self.mc = hpmc.integrate.sphere_union(seed=10, d=0.0, a=0.0)
        self.mc.shape_param.set('A', diameters=diams, centers=cent)
        self.run_test(latticep=lattice3d,
                      latticeq=latticeq,
                      k=k,
                      kalt=kalt,
                      q=k * 10.0,
                      qalt=kalt * 10.0,
                      uein=None,
                      snapshot_s=self.snapshot3d_s,
                      eng_check=(eng_check3d + eng_checkq))
        self.tear_down()
Пример #16
0
    R = traj["R"]
    data_folder = traj["data_folder"]
    dcd_period = traj["dcd_period"]
    control = traj["control"]

    plist = ["A", "B"]
    bond_list = ["A-A"]
    snapshot.particles.types = plist
    snapshot.bonds.types = bond_list
    for p in range(len(snapshot.particles.typeid)):
        snapshot.particles.typeid[p] = np.random.randint(2)
    for p in range(len(snapshot.bonds.typeid)):
        snapshot.bonds.typeid[p] = 0

    system = init.read_snapshot(snapshot)

    xml = deprecated.dump.xml(filename=data_folder + "atoms.hoomdxml",
                              period=None,
                              group=group.all(),
                              vis=True)

    logger = analyze.log(filename=data_folder + 'mylog.log',
                         period=1000,
                         quantities=[
                             'temperature', 'potential_energy',
                             'bond_harmonic_energy', 'external_wall_lj_energy',
                             "pair_table_energy", 'kinetic_energy', 'volume',
                             'pressure'
                         ],
                         overwrite=True)
Пример #17
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()
Пример #18
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)
Пример #19
0
def simulate(traj):

    seed = traj["seed"]

    micron = traj["micron"]
    data_folder = traj["data_folder"]

    # Diffusing elements
    cut_off_inte = traj["cut_off_inte"]
    p_inte = traj["p_inte"]
    p_off = traj["p_off"]
    sim_dt = traj["sim_dt"]
    fork_speed = traj["fork_speed"]
    dt_speed = traj["dt_speed"]
    dscale = traj["dscale"]
    # Yeast case
    spb = traj["spb"]
    assert (type(spb) == bool)

    microtubule_length = traj["microtubule_length"] * micron
    Activ_Origins = traj["Activ_Origins"]
    visu = traj["visu"]
    dump_hic = traj["dump_hic"]
    two_types = traj.get("two_types", False)
    r_diffu = traj.get("diameter_diffu", 1) / 2

    # 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"]
    assert (type(diff_alone) == bool)
    assert (type(diff_bind_when_on_DNA) == bool)
    assert (type(diff_bind_when_free) == bool)

    # Simulation parameters
    n_steps = traj["n_steps"]
    length_steps = traj["length_steps"]
    benchmark = traj["benchmark"]
    warmup = traj["warmup"]
    dcd_period = traj["dcd_period"]
    dump_inte = traj.get("dump_inte", False)

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

    ramp_type = traj.get("ramp_type", "exp")
    ramp = traj.get("ramp_time", 3)

    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

    snapshot, phic, tag_spb, bond_list, plist, Cen_pos, lPolymers, list_ori, p_tag_list = \
        create_initial_configuration(traj)
    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
        assert b.tag == i
    ###############################################

    ###############################################
    # Defining force field:
    all_beads, all_move, Spb_g, nl = force_field(traj,
                                                 bond_list=bond_list,
                                                 plist=plist,
                                                 tag_spb=tag_spb,
                                                 two_types=two_types)

    # Log
    if not visu:
        logger = analyze.log(filename=data_folder + 'mylog.log',
                             period=1000,
                             quantities=[
                                 'temperature', 'potential_energy',
                                 'bond_harmonic_energy',
                                 'external_wall_lj_energy',
                                 "pair_table_energy", 'kinetic_energy',
                                 'volume', 'pressure'
                             ],
                             overwrite=True)

    # Warmup

    minimize(traj, all_move, system, snapshot, Spb_g, Cen_pos,
             microtubule_length)

    # Dumping

    if visu:
        xml = deprecated.dump.xml(filename=data_folder + "atoms.hoomdxml",
                                  period=None,
                                  group=all_beads,
                                  vis=True)
        # xml.disable()
        return
    # gsd = dump.gsd(filename=data_folder + "atoms.gsd",period=None,group=all_beads)

    # Dynamics

    def Change_type(typep, particle_list, snp, msg=""):
        # print(particle_list)
        for p in particle_list:
            if "Ori" in typep:
                # Remove it from the list activated
                # list_ori.remove(p)
                pass
            else:
                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

    snp = system  # .take_snapshot()

    if ramp_type == "exp":
        for couple in p_tag_list:
            Change_type("I_Diff", couple, snp)

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

    # nl.tune(warmup=1,steps=1000)

    # Small warmup

    t0 = time.time()
    md.integrate.mode_standard(dt=sim_dt)
    method = md.integrate.langevin(group=all_move,
                                   kT=1,
                                   seed=seed,
                                   dscale=False)

    print(plist)
    for p in ['Diff', 'S_Diff', 'F_Diff', "I_Diff"]:
        print(p, dscale * r_diffu)
        method.set_gamma(p, dscale * r_diffu)
    for p in ['Mono', 'Ori']:
        method.set_gamma(p, dscale)
    if two_types:
        method.set_gamma(p, dscale)
    # exit()

    if benchmark:
        print(nl.tune(warmup=4000, r_min=0.3, r_max=0.8, jumps=5, steps=5000))
        return
    """

    md.integrate.mode_standard(dt=sim_dt / 4)
    hoomd.run(100)
    md.integrate.mode_standard(dt=sim_dt / 2)
    hoomd.run(100)
    md.integrate.mode_standard(dt=sim_dt)
    """
    if warmup != 0:
        hoomd.run(warmup)

    dcd = dump.dcd(filename=data_folder + 'poly.dcd',
                   period=dcd_period,
                   overwrite=True)

    r_hic = []
    # if dump_hic:
    group_hic = group.tags(name="hic", tag_min=0, tag_max=phic)

    if dump_inte:
        r_inte = []

    Ndiff_libre_t = []

    N_diffu = traj["N_diffu"]

    offset_diff = np.min(p_tag_list)
    print(offset_diff)

    record_diffusing = [Diffusing(d) for d in np.arange(N_diffu * 2)]

    global timeit
    timeit = True
    global t0
    t0 = time.time()

    def Timeit(where=""):
        global timeit
        global t0
        if timeit:
            if where == "":
                print(time.time() - t0)
            else:
                print(where, time.time() - t0)
            t0 = time.time()

    previous_actifs = 0
    for i in range(n_steps):

        # Chek that the microtubule length is correct
        if spb:
            for cen in Cen_pos:
                cent_tmp = system.particles[cen]
                # print(cent_tmp.position)
                pspb = [p.position for p in Spb_g]
                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
        Timeit()
        # system.restore_snapshot(snp)

        N_actifs = int(len(p_tag_list) * (1 - np.exp(-i * dt_speed / ramp)))
        print(previous_actifs, N_actifs)
        for couple in p_tag_list[previous_actifs:N_actifs]:
            Change_type("Diff", couple, snp)
            print("Activated", couple)
        previous_actifs = N_actifs

        hoomd.run(length_steps // 2, profile=False)
        Timeit("After first half")

        if dump_hic and i % traj.get("hic_period", 1) == 0:
            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
            if i % 32 == 0:
                np.save(data_folder + "/hic", r_hic)

        # snp = system.take_snapshot()

        # update the position of the monomer by updating bonds
        ended = 0
        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(
                    dt_speed, verbose)

            ###################################################################
            # Only to keep track of the diffusing elements
            for diff1, diff2 in bind_diff:

                record_diffusing[diff1 - offset_diff].end_replication(
                    i * dt_speed, pos=snp.particles[diff1].position)
                record_diffusing[diff2 - offset_diff].end_replication(
                    i * dt_speed, pos=snp.particles[diff2].position)

            for diff in alone:
                if record_diffusing[diff - offset_diff].bound:
                    record_diffusing[diff - offset_diff].end_bound(
                        i * dt_speed, pos=snp.particles[diff].position)
                elif record_diffusing[diff - offset_diff].replicating:
                    record_diffusing[diff - offset_diff].end_replication(
                        i * dt_speed, pos=snp.particles[diff].position)
                else:
                    print(diff, record_diffusing[diff - offset_diff].free)
                    raise

            ###################################################################

            ###################################################################
            # take care of the bondings

            for ori in passivated_origin:
                list_ori.remove(ori)

            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)

            # check for releasing alone binded elements

            for ori_not_started in P.get_free_origins():
                diff = P.get_diff_at_origin(ori_not_started)
                if diff != []:
                    if np.random.rand() > p_off:
                        continue
                    ptag, bond_tag = diff[0]
                    P.dettach_one_diff(ptag, ori_not_started)
                    Release([bond_tag], snp)
                    Change_type("Diff", [ptag], snp)

            if P.modules == []:
                ended += 1

        Timeit("AFter update")
        hoomd.run(length_steps // 2, profile=True)
        Timeit("AFter second half")

        group_diffu.force_update()

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

        p_origin = np.array([snp.particles[ori].position for ori in list_ori])

        Ndiff_libre_t.append(len(tag_diffu))

        if not (tag_diffu != [] and list_ori != []):
            print("No interactions")

        # Generate the measures we are interested in
        # Matrice interaction DNA / particules
        if dump_inte and i % traj.get("inte_period",
                                      1) == 0 and len(group_diffu) != 0:
            ph = np.array([p.position for p in group_hic])
            pi = np.array([p.position for p in group_diffu])

            print(ph.shape, pi.shape)
            D = cdist(ph, pi)
            D[D < 2] = 0.5 + r_diffu
            D[D >= 2] = 0
            # np.fill_diagonal(D, 0)
            if r_inte != []:
                r_inte += D
            else:
                r_inte = D
            if i % 32 == 0:
                np.save(data_folder + "/inte", r_inte)

        start_replication = False
        if tag_diffu != [] and list_ori != [] and start_replication:
            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':
                        if b.a in tag_diffu:
                            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])
                lo = list(range(len(d2[iD])))
                np.random.shuffle(lo)
                for iorigin in lo:
                    di = d2[iD][iorigin]
                    if iorigin in activated:
                        # Needed because we don't want an origin to be activated
                        # twice
                        continue
                    if di > cut_off_inte:
                        continue

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

                        if np.random.rand(
                        ) > p_inte * P.o_strength[list_ori[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 = list_ori[iorigin]
                                new_btags = Bind(
                                    "Mono_Diff",
                                    [[particular_origin, ptags[0]],
                                     [particular_origin, ptags[1]]], snp)

                                activated.append(0 + iorigin)
                                P.add_fork(ptags,
                                           particular_origin,
                                           new_btags,
                                           btag,
                                           fork_speed=fork_speed)

                                for diff in ptags:
                                    record_diffusing[
                                        diff - offset_diff].start_replication(
                                            particular_origin,
                                            i * dt_speed,
                                            pos=snp.particles[diff].position)

                            else:
                                Change_type('F_Diff', ptags,
                                            snp)  # Diffusive element attached
                                particular_origin = list_ori[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]

                                    activated.append(0 + iorigin)
                                    P.add_fork([p1[0], p2[0]],
                                               particular_origin,
                                               [p1[1], p2[1]],
                                               btag,
                                               fork_speed=fork_speed)

                                    record_diffusing[
                                        p1[0] - offset_diff].start_replication(
                                            particular_origin,
                                            i * dt_speed,
                                            pos=snp.particles[p1[0]].position)
                                    record_diffusing[
                                        p2[0] - offset_diff].start_replication(
                                            particular_origin,
                                            i * dt_speed,
                                            pos=snp.particles[p2[0]].position)
                                else:
                                    record_diffusing[
                                        ptags[0] - offset_diff].start_bound(
                                            particular_origin,
                                            i * dt_speed,
                                            pos=snp.particles[
                                                ptags[0]].position)

                        else:
                            # start when touched and release
                            particular_origin = list_ori[iorigin]
                            activated.append(iorigin)

                            P.add_fork([None, None],
                                       particular_origin, [None, None],
                                       None,
                                       fork_speed=fork_speed)

                        break
                    # If we arrive there it means that one interaction has beeen
                    # found
                    break
            activated.sort()
            print(activated)
            print(list_ori)

            for io in activated[::-1]:
                print(io)
                list_ori.pop(io)
        Timeit("After binding")
        # t0 = time.time()
        with open(data_folder + "polymer_timing.dat", "wb") as f:
            cPickle.dump(lPolymers, f, protocol=2)
        with open(data_folder + "Ndiff_libre_t.dat", "wb") as f:
            cPickle.dump(Ndiff_libre_t, f, protocol=2)

        with open(data_folder + "record_diffusing.dat", "wb") as f:
            cPickle.dump(record_diffusing, f, protocol=2)

        Timeit("After writing")

        if traj.get("early_stop",
                    True) and list_ori == [] and ended == len(lPolymers):
            break

        # 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)
    logger.disable()
    method.disable()
    dcd.disable()
Пример #20
0
    def test_lattice(self):
        N=128;
        latticeq = [[1,0,0,0] for i in range(N)];
        k = 10.0;
        kalt = np.exp(15);
        dx2d = np.array([0.1, 0.1, 0.0]);
        theta = np.pi/6;
        eng_check2d = round(N*k*dx2d.dot(dx2d), 3);
        dx3d = np.array([0.1, 0.1, 0.1]);
        eng_check3d = round(N*k*dx3d.dot(dx3d), 3);

        dq = np.array([np.cos(theta/2.0),0.,0.,np.sin(theta/2)])
        ddq = np.array([1.,0.,0.,0.]) - dq;
        eng_checkq = round(10.0*k*N*ddq.dot(ddq), 3);

        hexuc = hoomd.lattice.hex(a=2.0);
        self.system = init.read_snapshot(hexuc.get_snapshot());
        self.system.replicate(nx=8, ny=8, nz=1);

        self.snapshot2d = self.system.take_snapshot(particles=True); #data.make_snapshot(N=N, box=data.boxdim(L=L, dimensions=3), particle_types=['A'])
        lattice2d = [];
        if hoomd.comm.get_rank() == 0:
            lattice2d = self.snapshot2d.particles.position[:];

        self.snapshot2d_s = data.make_snapshot(N=N, box=self.system.box, particle_types=['A']);
        if hoomd.comm.get_rank() == 0:
            self.snapshot2d_s.particles.position[:] = self.snapshot2d.particles.position[:]+dx2d;
            self.snapshot2d_s.particles.orientation[:] = np.array([dq for _ in range(N)]);
        del self.system
        context.initialize();

        bccuc = hoomd.lattice.bcc(a=2.0);
        self.system = init.read_snapshot(bccuc.get_snapshot());
        self.system.replicate(nx=4, ny=4, nz=4);
        self.snapshot3d = self.system.take_snapshot(particles=True); #data.make_snapshot(N=N, box=data.boxdim(L=L, dimensions=3), particle_types=['A'])
        lattice3d = [];
        if hoomd.comm.get_rank() == 0:
            lattice3d = self.snapshot3d.particles.position[:];
        self.snapshot3d_s = data.make_snapshot(N=N, box=self.system.box, particle_types=['A']);
        if hoomd.comm.get_rank() == 0:
            self.snapshot3d_s.particles.position[:] = self.snapshot3d.particles.position[:]+dx3d;
            self.snapshot3d_s.particles.orientation[:] = np.array([dq for _ in range(N)]);
        del self.system
        context.initialize();

        # sphere
        print("****************************************")
        print("*               sphere                 *")
        print("****************************************")
        # d = 0.0014284726343172743, p = 0.20123046875
        uein = 1.5 # kT
        diam = 1.0;
        self.system = init.read_snapshot(self.snapshot3d)
        self.mc = hpmc.integrate.sphere(seed=2398, d=0.0)
        self.mc.shape_param.set('A', diameter=diam)
        self.run_test(latticep=lattice3d, latticeq=[], k=k, kalt=kalt, q=0, qalt=0, uein=1.5, snapshot_s=self.snapshot3d_s, eng_check=eng_check3d, d=0.001428 );
        self.tear_down()

        # ellipsoid
        print("****************************************")
        print("*              ellipsoid               *")
        print("****************************************")
        # a = 0.00038920117896296716, p = 0.2035860456051452
        # d = 0.0014225507698958867, p = 0.19295361127422195
        a = 0.5;
        b = 0.54;
        c = 0.35;
        uein = 3.0 # kT
        self.system = init.read_snapshot(self.snapshot3d)
        self.mc = hpmc.integrate.ellipsoid(seed=2398, d=0.0, a=0.0)
        self.mc.shape_param.set('A', a=a, b=b, c=c)
        self.run_test(latticep=lattice3d, latticeq=latticeq, k=k, kalt=kalt, q=k*10.0, qalt=kalt*10.0, uein=3.0, snapshot_s=self.snapshot3d_s, eng_check=(eng_check3d+eng_checkq), a = 0.000389, d = 0.001423);
        self.tear_down()

        # convex_polygon
        print("****************************************")
        print("*           convex_polygon             *")
        print("****************************************")
        # a = 0.001957745443687172, p = 0.19863574351978172
        # d = 0.0017185407622231329, p = 0.2004306126443531
        self.system = init.read_snapshot(self.snapshot2d)
        v = 0.33*np.array([(-1,-1), (1,-1), (1,1), (-1,1)]);
        self.mc = hpmc.integrate.convex_polygon(seed=2398, d=0.0, a=0.0)
        self.mc.shape_param.set('A', vertices=v)
        self.run_test(latticep=lattice2d, latticeq=latticeq, k=k, kalt=kalt, q=k*10.0, qalt=kalt*10.0, uein=1.5, snapshot_s=self.snapshot2d_s, eng_check=(eng_check2d+eng_checkq), a = 0.001958, d = 0.001719);
        self.tear_down()


        # convex_spheropolygon
        print("****************************************")
        print("*        convex_spheropolygon          *")
        print("****************************************")

        self.system = init.read_snapshot(self.snapshot2d)
        v = 0.33*np.array([(-1,-1), (1,-1), (1,1), (-1,1)]);
        r = 0.1234;
        self.mc = hpmc.integrate.convex_spheropolygon(seed=2398, d=0.0, a=0.0)
        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.run_test(latticep=lattice2d, latticeq=latticeq, k=k, kalt=kalt, q=k*10.0, qalt=kalt*10.0, uein=None, snapshot_s=self.snapshot2d_s, eng_check=(eng_check2d+eng_checkq));
        self.tear_down()

        #simple_polygon
        print("****************************************")
        print("*           simple_polygon             *")
        print("****************************************")

        self.system = init.read_snapshot(self.snapshot2d)
        v = 0.33*np.array([(-1,-1), (1,-1), (1,1), (-1,1)]);
        self.mc = hpmc.integrate.simple_polygon(seed=2398, d=0.0, a=0.0)
        self.mc.shape_param.set('A', vertices=v)
        self.run_test(latticep=lattice2d, latticeq=latticeq, k=k, kalt=kalt, q=k*10.0, qalt=kalt*10.0, uein=None, snapshot_s=self.snapshot2d_s, eng_check=(eng_check2d+eng_checkq));
        self.tear_down()

        # polyhedron
        print("****************************************")
        print("*             polyhedron               *")
        print("****************************************")

        self.system = init.read_snapshot(self.snapshot3d)
        v = 0.33*np.array([(-0.5, -0.5, -0.5), (-0.5, -0.5, 0.5), (-0.5, 0.5, -0.5), (-0.5, 0.5, 0.5), (0.5, -0.5, -0.5), (0.5, -0.5, 0.5), (0.5, 0.5, -0.5), (0.5, 0.5, 0.5)]);
        f = [(7, 3, 1, 5), (7, 5, 4, 6), (7, 6, 2, 3), (3, 2, 0, 1), (0, 2, 6, 4), (1, 0, 4, 5)];
        r = 0.0;
        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
        print("****************************************")
        print("*          convex_polyhedron           *")
        print("****************************************")
        #a = 0.00038920117896296716, p = 0.2035860456051452
        #d = 0.0014225507698958867, p = 0.19295361127422195
        self.system = init.read_snapshot(self.snapshot3d)
        v = 0.33*np.array([(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.mc = hpmc.integrate.convex_polyhedron(seed=2398, d=0.0, a=0.0)
        self.mc.shape_param.set('A', vertices=v)
        self.run_test(latticep=lattice3d, latticeq=latticeq, k=k, kalt=kalt, q=k*10.0, qalt=kalt*10.0, uein=3.0, snapshot_s=self.snapshot3d_s, eng_check=(eng_check3d+eng_checkq), a = 0.0003892, d = 0.00142255);
        self.tear_down()

        # convex_spheropolyhedron
        print("****************************************")
        print("*       convex_spheropolyhedron        *")
        print("****************************************")

        self.system = init.read_snapshot(self.snapshot3d)
        v = 0.33*np.array([(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.mc = hpmc.integrate.convex_spheropolyhedron(seed=2398, d=0.0, a=0.0)
        self.mc.shape_param.set('A', vertices=v, sweep_radius=r)
        self.run_test(latticep=lattice3d, latticeq=latticeq, k=k, kalt=kalt, q=k*10.0, qalt=kalt*10.0, uein=None, snapshot_s=self.snapshot3d_s, eng_check=(eng_check3d+eng_checkq));
        self.tear_down()

        # faceted_sphere
        print("****************************************")
        print("*            faceted_sphere            *")
        print("****************************************")

        self.system = init.read_snapshot(self.snapshot3d)
        v =  0.33*np.array([(-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 = 1.0;
        orig = (0,0,0);
        self.mc = hpmc.integrate.faceted_sphere(seed=10, d=0.0, a=0.0);
        self.mc.shape_param.set('A', normals=norms,
                                    offsets=offs,
                                    vertices=v,
                                    diameter=diam,
                                    origin=orig);
        self.run_test(latticep=lattice3d, latticeq=latticeq, k=k, kalt=kalt, q=k*10.0, qalt=kalt*10.0, uein=None, snapshot_s=self.snapshot3d_s, eng_check=(eng_check3d+eng_checkq));
        self.tear_down()

        # sphinx
        print("****************************************")
        print("*               sphinx                 *")
        print("****************************************")

        self.system = init.read_snapshot(self.snapshot3d)
        cent = [(0,0,0), (0,0,1.15), (0,0,-1.15)]
        diams = [1,-1.2,-1.2];
        self.mc = hpmc.integrate.sphinx(seed=10, d=0.0, a=0.0);
        self.mc.shape_param.set('A', diameters=diams, centers=cent);
        self.run_test(latticep=lattice3d, latticeq=latticeq, k=k, kalt=kalt, q=k*10.0, qalt=kalt*10.0, uein=None, snapshot_s=self.snapshot3d_s, eng_check=(eng_check3d+eng_checkq));
        self.tear_down()

        # sphere_union
        print("****************************************")
        print("*            sphere_union              *")
        print("****************************************")

        self.system = init.read_snapshot(self.snapshot3d)
        cent = [(0,0,0), (0,0,0.15), (0,0,-0.15)]
        diams = [1,1,1];
        self.mc = hpmc.integrate.sphere_union(seed=10, d=0.0, a=0.0);
        self.mc.shape_param.set('A', diameters=diams, centers=cent);
        self.run_test(latticep=lattice3d, latticeq=latticeq, k=k, kalt=kalt, q=k*10.0, qalt=kalt*10.0, uein=None, snapshot_s=self.snapshot3d_s, eng_check=(eng_check3d+eng_checkq));
        self.tear_down()
Пример #21
0
def create_empty(**kwargs):
    snap = data.make_snapshot(**kwargs)
    return init.read_snapshot(snap)
Пример #22
0
def simulate(traj):

    seed = traj["seed"]

    micron = traj["micron"]
    data_folder = traj["data_folder"]

    # Diffusing elements
    cut_off_inte = traj["cut_off_inte"]
    p_inte = traj["p_inte"]
    p_off = traj["p_off"]
    sim_dt = traj["sim_dt"]

    dscale = traj["dscale"]
    # Yeast case
    spb = traj["spb"]
    assert (type(spb) == bool)

    microtubule_length = traj["microtubule_length"] * micron
    visu = traj["visu"]
    dump_hic = traj["dump_hic"]
    two_types = traj.get("two_types", False)

    # 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"]
    assert (type(diff_alone) == bool)
    assert (type(diff_bind_when_on_DNA) == bool)
    assert (type(diff_bind_when_free) == bool)

    # Simulation parameters
    n_steps = traj["n_steps"]
    length_steps = traj["length_steps"]
    benchmark = traj["benchmark"]
    warmup = traj["warmup"]
    dcd_period = traj["dcd_period"]

    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

    snapshot, phic, tag_spb, bond_list, plist, Cen_pos, lPolymers, list_ori, p_tag_list = \
        create_initial_configuration(traj)
    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
        assert b.tag == i
    ###############################################

    ###############################################
    # Defining force field:
    all_beads, all_move, Spb_g, nl = force_field(traj,
                                                 bond_list=bond_list,
                                                 plist=plist,
                                                 tag_spb=tag_spb,
                                                 two_types=two_types)

    # Log
    if not visu:
        logger = analyze.log(filename=data_folder + 'mylog.log',
                             period=1000,
                             quantities=[
                                 'temperature', 'potential_energy',
                                 'bond_harmonic_energy',
                                 'external_wall_lj_energy',
                                 "pair_table_energy", 'kinetic_energy',
                                 'volume', 'pressure'
                             ],
                             overwrite=True)

    # Warmup

    minimize(traj, all_move, system, snapshot, Spb_g, Cen_pos,
             microtubule_length)

    # Dumping

    if visu:
        xml = deprecated.dump.xml(filename=data_folder + "atoms.hoomdxml",
                                  period=None,
                                  group=all_beads,
                                  vis=True)
        # xml.disable()
        return
    # gsd = dump.gsd(filename=data_folder + "atoms.gsd",period=None,group=all_beads)

    # Dynamics

    def Change_type(typep, particle_list, snp, msg=""):
        # print(particle_list)
        for p in particle_list:
            if "Ori" in typep:
                # Remove it from the list activated
                # list_ori.remove(p)
                pass
            else:
                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

    snp = system  # .take_snapshot()

    # nl.tune(warmup=1,steps=1000)

    # Small warmup

    t0 = time.time()
    md.integrate.mode_standard(dt=sim_dt)
    method = md.integrate.langevin(group=all_move,
                                   kT=1,
                                   seed=seed,
                                   dscale=dscale)

    if benchmark:
        print(nl.tune(warmup=4000, r_min=0.3, r_max=0.8, jumps=5, steps=5000))
        return

    md.integrate.mode_standard(dt=sim_dt / 4)
    hoomd.run(100)
    md.integrate.mode_standard(dt=sim_dt / 2)
    hoomd.run(100)
    md.integrate.mode_standard(dt=sim_dt)

    if warmup != 0:
        hoomd.run(warmup)

    dcd = dump.dcd(filename=data_folder + 'poly.dcd',
                   period=dcd_period,
                   overwrite=True)

    r_hic = []
    if dump_hic:
        group_hic = group.tags(name="hic", tag_min=0, tag_max=phic)

    global timeit
    timeit = True
    global t0
    t0 = time.time()

    def Timeit(where=""):
        global timeit
        global t0
        if timeit:
            if where == "":
                print(time.time() - t0)
            else:
                print(where, time.time() - t0)
            t0 = time.time()

    bonds = []
    for i in range(n_steps):

        # Chek that the microtubule length is correct
        if spb:
            for cen in Cen_pos:
                cent_tmp = system.particles[cen]
                # print(cent_tmp.position)
                pspb = [p.position for p in Spb_g]
                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
        Timeit()
        # system.restore_snapshot(snp)

        hoomd.run(length_steps // 2, profile=False)
        Timeit("After first half")

        if dump_hic and i % traj.get("hic_period", 1) == 0:
            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
            if i % 32 == 0:
                np.save(data_folder + "/hic", r_hic)

        # snp = system.take_snapshot()

        # Bond tags to release (Alone particle)
        remv = []
        for ib, b in enumerate(bonds):
            if np.random.rand() > p_off:
                continue

            p_tag_list.append(b[2])
            list_ori.append(b[1])

            Release([b[0]], snp)
            remv.append(ib)

        remv.sort()
        for ib in remv[::-1]:
            bonds.pop(ib)

        Timeit("AFter update")
        hoomd.run(length_steps // 2, profile=True)
        Timeit("AFter second half")

        # Update Type because of (Ori to passivated)

        # Update group

        # Find new interacting particles

        # First check if Dimer are close from one origin

        print("LAAAAAAAAAAAAAAA", p_tag_list, list_ori, bonds)
        p_diffu = np.array(
            [snp.particles[diff].position for diff in p_tag_list])

        p_origin = np.array([snp.particles[ori].position for ori in list_ori])

        if not (p_tag_list != [] and list_ori != []):
            print("No interactions")

        if p_tag_list != [] and list_ori != []:
            distances = cdist(p_diffu, p_origin)
            print(distances.shape)
            # Reorder the distances with the dimer tags

            # Groups Diff-Diff by bond to compute the distances

            activated_ori = []
            activated_p = []

            for iD, ptag in enumerate(p_tag_list):
                # print(d2.shape)
                # print(d2[iD])
                lo = list(range(len(distances[iD])))
                np.random.shuffle(lo)

                for iorigin in lo:
                    di = distances[iD][iorigin]
                    if iorigin in activated_ori:
                        # 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
                    activated_ori.append(iorigin + 0)
                    activated_p.append(iD)

                    new_btags = Bind("Mono_Diff", [[list_ori[iorigin], ptag]],
                                     snp)

                    bonds.append([new_btags[0], list_ori[iorigin], ptag])

                    break
            activated_ori.sort()
            for ori in activated_ori[::-1]:
                list_ori.pop(ori)

            activated_p.sort()
            for p in activated_p[::-1]:
                p_tag_list.pop(p)

        Timeit("After binding")
        # t0 = time.time()

        # 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)
    logger.disable()
    method.disable()
    dcd.disable()