Ejemplo n.º 1
0
    def test_same_minima_Frenkel(self):
        nparticles = 32
        hs_radii = 0.05 * np.random.randn(nparticles) + 1
        volpart = np.sum(4. / 3. * np.pi * hs_radii**3)
        phi = 0.7
        boxl = (volpart / phi)**(1 / 3.)
        boxv = [boxl, boxl, boxl]
        coords = np.random.rand(nparticles * 3) * boxl
        ncellx_scale = get_ncellsx_scale(np.ones(nparticles), boxv)
        pot_cellists = Frenkel(boxvec=boxv,
                               celllists=True,
                               ncellx_scale=ncellx_scale)
        pot_no_cellists = Frenkel(boxvec=boxv,
                                  celllists=False,
                                  ncellx_scale=ncellx_scale)
        nsteps = 1000
        tol = 1e-5
        res_cell_lists = lbfgs_cpp(coords,
                                   pot_cellists,
                                   nsteps=nsteps,
                                   tol=tol)
        res_no_cell_lists = lbfgs_cpp(coords,
                                      pot_no_cellists,
                                      nsteps=nsteps,
                                      tol=tol)

        fcoords_cell_lists = res_cell_lists.coords
        fcoords_no_cell_lists = res_no_cell_lists.coords
        # self.assertEqual(fcoords_no_cell_lists,fcoords_cell_lists)
        self.assertTrue(np.all(fcoords_no_cell_lists == fcoords_cell_lists))
Ejemplo n.º 2
0
def bench_python_cpp(coords):
    print ""
    lj = LJcpp()
    t0 = time.time()
    lbfgs_cpp(coords.copy(), lj, iprint=1000, nsteps=100000)
    t1 = time.time()

    print "python wrapped pure c++ LJ minimization : time {}".format(t1 - t0)
Ejemplo n.º 3
0
def bench_python_cpp(coords):
    print ""
    lj = LJcpp()
    t0 = time.time()
    lbfgs_cpp(coords.copy(), lj, iprint=1000, nsteps=100000)
    t1 = time.time()
    
    print "python wrapped pure c++ LJ minimization : time {}".format(t1-t0)
Ejemplo n.º 4
0
def func(pot, coords):
    #print coords
    #print "start energy", pot.getEnergy(coords)
    results = lbfgs_cpp(coords, pot, nsteps=1e5, tol=1e-9, iprint=-1, maxstep=10)
    #results = modifiedfire_cpp(coords, pot, nsteps=1e5, tol=1e-5, iprint=-1)
    #print "quenched energy", results.energy
    if results.success:
        return [results.coords, results.energy, results.nfev]    
Ejemplo n.º 5
0
    def test_same_minima_HS_WCA(self):
        nparticles = 32
        radius_sca = 0.9085602964160698
        pot_sca = 0.1
        eps = 1.0
        hs_radii = 0.05 * np.random.randn(nparticles) + 1
        volpart = np.sum(4. / 3. * np.pi * hs_radii**3)
        phi = 0.7
        boxl = (volpart / phi)**(1 / 3.)
        boxv = [boxl, boxl, boxl]
        coords = np.random.rand(nparticles * 3) * boxl
        ncellx_scale = get_ncellsx_scale(np.ones(nparticles), boxv)
        bdim = 3
        distance_method = Distance.PERIODIC
        pot_cellists = HS_WCA(use_cell_lists=True,
                              eps=eps,
                              sca=pot_sca,
                              radii=hs_radii * radius_sca,
                              boxvec=boxv,
                              ndim=bdim,
                              ncellx_scale=ncellx_scale,
                              distance_method=distance_method)
        pot_no_cellists = HS_WCA(use_cell_lists=False,
                                 eps=eps,
                                 sca=pot_sca,
                                 radii=hs_radii * radius_sca,
                                 boxvec=boxv,
                                 ndim=bdim,
                                 ncellx_scale=ncellx_scale,
                                 distance_method=distance_method)
        nsteps = 1000
        tol = 1e-5
        res_cell_lists = lbfgs_cpp(coords,
                                   pot_cellists,
                                   nsteps=nsteps,
                                   tol=tol)
        res_no_cell_lists = lbfgs_cpp(coords,
                                      pot_no_cellists,
                                      nsteps=nsteps,
                                      tol=tol)

        fcoords_cell_lists = res_cell_lists.coords
        fcoords_no_cell_lists = res_no_cell_lists.coords
        # self.assertEqual(fcoords_no_cell_lists,fcoords_cell_lists)
        self.assertTrue(np.all(fcoords_no_cell_lists == fcoords_cell_lists))
Ejemplo n.º 6
0
 def minimize(pot, coords):
     print "shape", coords.shape
     print "start energy", pot.getEnergy(coords)
     results = lbfgs_cpp(coords, pot, M=4, nsteps=1e5, tol=1e-9, iprint=1, verbosity=1, maxstep=10)
     print "quenched energy", results.energy
     print "E: {}, nsteps: {}".format(results.energy, results.nfev)
     if results.success:
         # return [results.coords, results.energy, results.nfev]
         return results
Ejemplo n.º 7
0
def mytest():
    system = test_functions.BealeSystem()
    print "do pot"
    pot = system.get_potential()
    print "done pot"
    x = pot.target_coords.copy() 
    x += np.random.uniform(-0.2, 0.2, x.shape)
    from pele.optimize import LBFGS_CPP
    lbfgs = LBFGS_CPP(x, pot, verbosity=100)
    print "done setting up"
    res = lbfgs.run()
    res = _quench.lbfgs_cpp(x, pot, verbosity=100)
#    print res
    print res
Ejemplo n.º 8
0
def mytest():
    system = test_functions.BealeSystem()
    print("do pot")
    pot = system.get_potential()
    print("done pot")
    x = pot.target_coords.copy()
    x += np.random.uniform(-0.2, 0.2, x.shape)
    from pele.optimize import LBFGS_CPP

    lbfgs = LBFGS_CPP(x, pot, verbosity=100)
    print("done setting up")
    lbfgs.run()
    res = _quench.lbfgs_cpp(x, pot, verbosity=100)
    # print res
    print(res)
Ejemplo n.º 9
0
 def minimize(pot, coords):
     print "start energy", pot.getEnergy(coords)
     results = lbfgs_cpp(coords,
                         pot,
                         M=4,
                         nsteps=1e5,
                         tol=1e-5,
                         iprint=-1,
                         verbosity=0,
                         maxstep=n)
     print "quenched energy", results.energy
     print "E: {}, nsteps: {}".format(results.energy, results.nfev)
     print results
     if results.success:
         return [results.coords, results.energy, results.nfev]
Ejemplo n.º 10
0
def minimize(coords, pot):
    result = lbfgs_cpp(coords, pot)
    return result.coords, result.energy, result.grad, result.rms
def minimize(coords, pot):
    result = lbfgs_cpp(coords, pot)
    # result = modifiedfire_cpp(coords, pot)
    return result.coords, result.energy, result.grad, result.rms
Ejemplo n.º 12
0
 def test_lbfgs_cpp(self):
     res = _quench.lbfgs_cpp(self.x0, self.pot, tol=1e-7)
     self.assertTrue(res.success)
     self.assertAlmostEqual(self.E, res.energy, 4)
     self.check_attributes(res)
Ejemplo n.º 13
0
def main():
    p = 3
    nspins = 20
    interactions = np.ones(np.power(nspins, p))
    coords = np.ones(nspins)
    pot = MeanFieldPSpinSpherical(interactions, nspins, p, tol=1e-6)
    e = pot.getEnergy(coords)
    assert e + comb(nspins, p) / np.power(nspins, (p - 1) / 2) < 1e-10
    print("passed")

    #interactions = np.random.normal(0, np.sqrt(factorial(p)), [nspins for i in xrange(p)])
    assert p == 3, "the interaction matrix setup at the moment requires that p==3"
    interactions = np.empty([nspins for i in range(p)])
    for i in range(nspins):
        for j in range(i, nspins):
            for k in range(j, nspins):
                w = np.random.normal(0, np.sqrt(factorial(p)))
                interactions[i][j][k] = w
                interactions[k][i][j] = w
                interactions[k][j][i] = w
                interactions[j][k][i] = w
                interactions[i][k][j] = w
                interactions[j][i][k] = w

    interactionsfl = interactions.flatten()
    pot = MeanFieldPSpinSpherical(interactionsfl, nspins, p, tol=1e-6)
    energies = []
    nfevs = []
    coords_list = []

    for _ in range(1000):
        coords = np.random.normal(0, 1, nspins)
        coords /= (np.linalg.norm(coords) / np.sqrt(nspins))
        coords_list.append(coords)

    if False:

        start = time.time()

        out = Parallel(n_jobs=max(1, 4))(delayed(func)(pot, x)
                                         for x in coords_list)
        out = np.array(out)

        done = time.time()
        elapsed = done - start
        print('elapsed time: ', elapsed)

        fig = plt.figure()
        ax = fig.add_subplot(111)
        ax.hist(out[:, 1] / nspins)
        ax.set_xlabel('E/N')
        fig1 = plt.figure()
        ax1 = fig1.add_subplot(111)
        ax1.hist(out[:, 2])
        ax1.set_xlabel('nfev')
        fig.savefig('energy_histogram_n{}.pdf'.format(nspins))
        fig1.savefig('nfev_histogram_n{}.pdf'.format(nspins))
        plt.show()

    if True:
        #check how many different minima

        start = time.time()

        out = Parallel(n_jobs=max(1, 4))(delayed(func)(pot, x)
                                         for x in coords_list)
        out = np.array(out)
        done = time.time()
        elapsed = done - start
        print('elapsed time: ', elapsed)

        #print out[:,0]

        uniquex = []
        for x1 in out[:, 0]:
            unique = True
            for x2 in uniquex:
                if compare_exact(x1, x2, rel_tol=1e-7):
                    unique = False
                    break
            if unique:
                uniquex.append(x1)

        print("distinct minima", len(uniquex))

    if False:
        # create a graph object, add n nodes to it, and the edges
        Gm = nx.MultiGraph()
        Gm.add_nodes_from(range(nspins))

        l = 0
        for c in combinations(list(range(nspins)), p):
            i, j, k = c
            if i != j and j != k and i != k:
                w = interactions[i][j][k]
                Gm.add_edge(i, j, weight=w)
                Gm.add_edge(j, k, weight=w)
                Gm.add_edge(k, i, weight=w)
            l += 1
        print(l * 3)
        assert comb(nspins, p) == l
        assert l * 3 == len(Gm.edges())

        #merge edges of multigraph
        G = nx.Graph()
        for u, v, data in Gm.edges_iter(data=True):
            w = data['weight']
            if G.has_edge(u, v):
                G[u][v]['weight'] += w
            else:
                G.add_edge(u, v, weight=w)

        # use one of the edge properties to control line thickness
        epos = [(u, v)
                for (u, v,
                     d) in sorted(G.edges(data=True),
                                  key=lambda a_b_dct: a_b_dct[2]['weight'],
                                  reverse=True) if d['weight'] > 0]
        eneg = [(u, v) for (u, v, d) in sorted(
            G.edges(data=True), key=lambda a_b_dct1: a_b_dct1[2]['weight'])
                if d['weight'] <= 0]
        assert len(epos) + len(eneg) == len(G.edges())
        #        print epos
        #        print [(u, v, d['weight']) for (u, v, d) in sorted(G.edges(data=True), key = lambda (a, b, dct): dct['weight'], reverse=True) if d['weight'] > 0]
        #        print "eneg"
        #        print eneg
        #        print [(u, v, d['weight']) for (u, v, d) in sorted(G.edges(data=True), key = lambda (a, b, dct): dct['weight']) if d['weight'] <= 0]
        maxlen = 50 - 50 % p
        epos = epos[0:min(len(epos), maxlen)]
        eneg = eneg[0:min(len(eneg), maxlen)]
        #        print "truncated"
        #        for (u, v) in epos:
        #            print u, v, G[u][v]['weight']

        #print [wei[(u,v)] for (u,v) in eneg]
        # layout
        pos = nx.spring_layout(G, iterations=int(1e3))
        #pos = nx.circular_layout(G)

        fig = plt.figure(figsize=(10, 20))
        ax = fig.add_subplot(211)

        plt.axis('off')
        ax.set_title('Random coords')
        # rendering
        nodesize = abs(coords_list[0]) / np.amax(coords_list[0]) * 1e3
        nx.draw_networkx_nodes(G,
                               pos,
                               node_color=coords_list[0],
                               cmap=plt.cm.get_cmap('RdYlBu'),
                               alpha=0.7,
                               linewidths=0,
                               node_size=nodesize,
                               label=list(range(nspins)),
                               ax=ax)
        nx.draw_networkx_edges(G,
                               pos,
                               edgelist=epos,
                               width=2,
                               alpha=0.3,
                               edge_color='r',
                               ax=ax)
        nx.draw_networkx_edges(G,
                               pos,
                               edgelist=eneg,
                               width=2,
                               alpha=0.3,
                               edge_color='b',
                               style='dashed',
                               ax=ax)
        #nx.draw_networkx_labels(G, pos, font_color='k', ax=ax)

        ax2 = fig.add_subplot(212)
        ax2.set_title('Minimum coords')
        plt.axis('off')

        # rendering
        minimum = lbfgs_cpp(coords,
                            pot,
                            nsteps=1e5,
                            tol=1e-5,
                            iprint=10,
                            maxstep=10).coords
        nodesize = abs(minimum) / np.amax(minimum) * 1e3
        nx.draw_networkx_nodes(G,
                               pos,
                               node_color=minimum,
                               cmap=plt.cm.get_cmap('RdYlBu'),
                               alpha=0.7,
                               linewidths=0,
                               node_size=nodesize,
                               label=list(range(nspins)),
                               ax=ax2)
        nx.draw_networkx_edges(G,
                               pos,
                               edgelist=epos,
                               width=2,
                               alpha=0.3,
                               edge_color='r',
                               ax=ax2)
        nx.draw_networkx_edges(G,
                               pos,
                               edgelist=eneg,
                               width=2,
                               alpha=0.3,
                               edge_color='b',
                               style='dashed',
                               ax=ax2)
        #nx.draw_networkx_labels(G, pos, font_color='k', ax=ax2)

        #plt.axes().set_aspect('equal', 'datalim')
        plt.savefig('pspin_n{}_network.pdf'.format(nspins))
Ejemplo n.º 14
0
 def test_lbfgs_cpp(self):
     res = _quench.lbfgs_cpp(self.x0, self.pot, tol=1e-7)
     self.assertTrue(res.success)
     self.assertAlmostEqual(self.E, res.energy, 4)
     self.check_attributes(res)
Ejemplo n.º 15
0
def main():
    p=3
    nspins=20
    interactions = np.ones(np.power(nspins,p))
    coords = np.ones(nspins)
    pot = MeanFieldPSpinSpherical(interactions, nspins, p, tol=1e-6)
    e = pot.getEnergy(coords)
    assert e + comb(nspins,p)/np.power(nspins,(p-1)/2) < 1e-10
    print "passed"
    
    #interactions = np.random.normal(0, np.sqrt(factorial(p)), [nspins for i in xrange(p)])
    assert p==3, "the interaction matrix setup at the moment requires that p==3"
    interactions = np.empty([nspins for i in xrange(p)])
    for i in xrange(nspins):
        for j in xrange(i, nspins):
            for k in xrange(j, nspins):
                w = np.random.normal(0, np.sqrt(factorial(p)))
                interactions[i][j][k] = w
                interactions[k][i][j] = w
                interactions[k][j][i] = w
                interactions[j][k][i] = w
                interactions[i][k][j] = w
                interactions[j][i][k] = w
    
    interactionsfl = interactions.flatten()
    pot = MeanFieldPSpinSpherical(interactionsfl, nspins, p, tol=1e-6)
    energies = []
    nfevs = []
    coords_list = []
    
    for _ in xrange(1000):
        coords = np.random.normal(0, 1, nspins)
        coords /= (np.linalg.norm(coords)/np.sqrt(nspins))
        coords_list.append(coords)
    
    if False:
        
        start = time.time()
        
        out = Parallel(n_jobs=max(1,4))(delayed(func)(pot, x) for x in coords_list)
        out = np.array(out)
        
        done = time.time()
        elapsed = done - start
        print 'elapsed time: ',elapsed
        
        fig = plt.figure()
        ax = fig.add_subplot(111)
        ax.hist(out[:,1]/nspins)
        ax.set_xlabel('E/N')
        fig1 = plt.figure()
        ax1 = fig1.add_subplot(111)
        ax1.hist(out[:,2])
        ax1.set_xlabel('nfev')
        fig.savefig('energy_histogram_n{}.pdf'.format(nspins))
        fig1.savefig('nfev_histogram_n{}.pdf'.format(nspins))
        plt.show()
    
    if True:
        #check how many different minima
        
        start = time.time()
        
        out = Parallel(n_jobs=max(1,4))(delayed(func)(pot, x) for x in coords_list)
        out = np.array(out)
        done = time.time()
        elapsed = done - start
        print 'elapsed time: ',elapsed
        
        #print out[:,0]
        
        uniquex = []
        for x1 in out[:,0]:
            unique = True
            for x2 in uniquex:
                if compare_exact(x1, x2, rel_tol=1e-7):
                    unique = False
                    break
            if unique:
                uniquex.append(x1)
                 
        print "distinct minima", len(uniquex)
        
    
    if False:
        # create a graph object, add n nodes to it, and the edges
        Gm = nx.MultiGraph()
        Gm.add_nodes_from(xrange(nspins))
        
        l = 0
        for c in combinations(range(nspins), p):
            i, j, k = c
            if i != j and j != k and i != k:
                w = interactions[i][j][k]
                Gm.add_edge(i, j, weight=w)
                Gm.add_edge(j, k, weight=w)
                Gm.add_edge(k, i, weight=w)
            l += 1
        print l*3
        assert comb(nspins,p) == l
        assert l*3 == len(Gm.edges())
        
        #merge edges of multigraph
        G = nx.Graph()
        for u,v,data in Gm.edges_iter(data=True):
            w = data['weight']
            if G.has_edge(u,v):
                G[u][v]['weight'] += w
            else:
                G.add_edge(u, v, weight=w)
        
        # use one of the edge properties to control line thickness
        epos = [(u,v) for (u,v,d) in sorted(G.edges(data=True), key = lambda (a, b, dct): dct['weight'], reverse=True) if d['weight'] > 0]
        eneg = [(u,v) for (u,v,d) in sorted(G.edges(data=True), key = lambda (a, b, dct): dct['weight']) if d['weight'] <= 0]
        assert len(epos)+len(eneg) == len(G.edges())
#        print epos
#        print [(u, v, d['weight']) for (u, v, d) in sorted(G.edges(data=True), key = lambda (a, b, dct): dct['weight'], reverse=True) if d['weight'] > 0]
#        print "eneg"
#        print eneg
#        print [(u, v, d['weight']) for (u, v, d) in sorted(G.edges(data=True), key = lambda (a, b, dct): dct['weight']) if d['weight'] <= 0]
        maxlen = 50 - 50 % p
        epos = epos[0:min(len(epos),maxlen)]
        eneg = eneg[0:min(len(eneg),maxlen)]
#        print "truncated"
#        for (u, v) in epos:
#            print u, v, G[u][v]['weight']
        
        #print [wei[(u,v)] for (u,v) in eneg]
        # layout
        pos = nx.spring_layout(G, iterations=int(1e3))
        #pos = nx.circular_layout(G)
        
        fig = plt.figure(figsize=(10,20))
        ax = fig.add_subplot(211)
        
        plt.axis('off')
        ax.set_title('Random coords')
        # rendering
        nodesize = abs(coords_list[0])/np.amax(coords_list[0])*1e3
        nx.draw_networkx_nodes(G, pos, node_color=coords_list[0], cmap=plt.cm.get_cmap('RdYlBu'), alpha=0.7, 
                               linewidths=0, node_size=nodesize, label=range(nspins), ax=ax)
        nx.draw_networkx_edges(G, pos, edgelist=epos, width=2, alpha=0.3, edge_color='r', ax=ax)
        nx.draw_networkx_edges(G, pos, edgelist=eneg, width=2, alpha=0.3, edge_color='b', style='dashed', ax=ax)
        #nx.draw_networkx_labels(G, pos, font_color='k', ax=ax)
        
        ax2 = fig.add_subplot(212)
        ax2.set_title('Minimum coords')
        plt.axis('off')
        
        # rendering
        minimum = lbfgs_cpp(coords, pot, nsteps=1e5, tol=1e-5, iprint=10, maxstep=10).coords
        nodesize = abs(minimum)/np.amax(minimum)*1e3
        nx.draw_networkx_nodes(G, pos, node_color=minimum, cmap=plt.cm.get_cmap('RdYlBu'), alpha=0.7, 
                               linewidths=0, node_size=nodesize, label=range(nspins), ax=ax2)
        nx.draw_networkx_edges(G, pos, edgelist=epos, width=2, alpha=0.3, edge_color='r', ax=ax2)
        nx.draw_networkx_edges(G, pos, edgelist=eneg, width=2, alpha=0.3, edge_color='b', style='dashed', ax=ax2)
        #nx.draw_networkx_labels(G, pos, font_color='k', ax=ax2)
        
        #plt.axes().set_aspect('equal', 'datalim')
        plt.savefig('pspin_n{}_network.pdf'.format(nspins))