Error: Unable to cast Python instance to C++ type

61 views
Skip to first unread message

oyin alabi

unread,
Apr 29, 2023, 9:49:53 PM4/29/23
to hoomd...@googlegroups.com
Hi,
I keep getting this error message when I run this code.
Error message "   File "trial2.py", line 296, in equilibrate 
sim.run(run_steps) 
RuntimeError: Unable to cast Python instance to C++ type"
Code:

@FlowProject.pre.isfile('Compression_c1.gsd')

@FlowProject.post.isfile('trajectory_c.gsd')

@FlowProject.operation

def equilibrate(job):

    with job:

        d = job.sp.d

        a = job.sp.a

        k = job.sp.k

        InertiaTarget= job.sp.InertiaTarget

        ## dumping period during compression

        dump_period = job.sp.dump_period

        ## logging period during compression

        log_period = job.sp.log_period

        run_steps = job.sp.run_steps

        ## random seed

        seed = job.sp.seed

        ## packing fraction

        ## run afterward

 

 

        #setup mc integrator  

        mc = hoomd.hpmc.integrate.ConvexPolyhedron()

      

         

 

        cpu = hoomd.device.CPU()

        sim = hoomd.Simulation(device=cpu,seed=1)

        #read state file 

        sim.create_state_from_gsd(filename='Compression_c1.gsd')     

        mc = hoomd.hpmc.integrate.ConvexPolyhedron()

         

        sim.operations.integrator = mc

 

        logger = hoomd.logging.Logger()

        logger.add(mc, quantities=['type_shapes'])

 

        sim.run(100)

 

        overlaps = mc.overlaps

        print("overlaps",overlaps)

 

 

        Biased_move = hoomd.hpmc.shape_move.Biased(mc=mc, k=k, default_step_size= 0.01, InertiaTarget=InertiaTarget, vertex_move_probability = 0.1)

        Biased_move.volume['A'] = 1

        updater = hoomd.hpmc.update.Shape(shape_move=Biased_move, trigger=hoomd.trigger.Periodic(1))

        updater.shape_move = Biased_move

        sim.operations.updaters.append(updater) 

 

 

        #%%Equilibrate the sys

        gsd_file = hoomd.write.GSD(trigger=hoomd.trigger.Periodic(1000),filename='trajectory_c.gsd',mode='wb')

        logger = hoomd.logging.Logger()  

        gsd_file.log=logger

        logger.add(mc, quantities=['type_shapes'])

        sim.operations.writers.append(gsd_file)

       

        tune = hoomd.hpmc.tune.MoveSize.scale_solver(

            moves=['a', 'd'],

            target=0.2,

            trigger=hoomd.trigger.And([

                hoomd.trigger.Periodic(100),

                hoomd.trigger.Before(sim.timestep + 5000)

            ]))

         

        sim.operations.tuners.append(tune)

        

 

        sim.run(run_steps) 

.
I would appreciate any suggestions. Please find below a more detailed version of the code.

from __future__ import division

from __future__ import print_function

import numpy as np

import copy

import math

import itertools

from collections import OrderedDict

import garnett

import signac

import freud

import gsd

import gsd.hoomd 

import coxeter

import hoomd

from hoomd import hpmc

from flow import FlowProject

#from flow import with_job

 

# project = signac.get_project()

 

 

@FlowProject.post.isfile("lattice_c.gsd")

@FlowProject.post.isfile("Compression_c.gsd")

@FlowProject.operation

def initialize(job):

    with job:

        N_particles = job.sp.N_particles

        ## m parameter    

        m = job.sp.m           

        ## step sizes   

        d = job.sp.d   

        a = job.sp.a

        T = job.sp.T

        k = job.sp.k

        InertiaTarget= job.sp.InertiaTarget

        # seed

        seed = job.sp.seed

        ## equilibration time

        equil_steps = job.sp.equil_steps

        seed = 1 

 

        #setup initial spacing with no overlaps 

        spacing = 1.2

        K = math.ceil(N_particles**(1 / 3))

        L = K * spacing

        x = np.linspace(-L / 2, L / 2, K, endpoint=False)

        position = list(itertools.product(x, repeat=3))

        position = position[0:N_particles]

        orientation = [(1, 0, 0, 0)] * N_particles        

                     

        #define initial snapshot state 

        snapshot = gsd.hoomd.Snapshot()

        snapshot.particles.N = N_particles

        snapshot.configuration.box = [L, L, L,0, 0, 0]

        snapshot.particles.typeid = [0] * N_particles                

        snapshot.particles.types = ['A']                

        snapshot.particles.position = position        

        snapshot.particles.orientation = orientation        

        with gsd.hoomd.open(name='lattice_c.gsd', mode='wb') as f:               

            f.append(snapshot)          

 

        #define computation device to store the state   

        cpu = hoomd.device.CPU()

        sim = hoomd.Simulation(device=cpu,seed=seed)   

        verts=[

        (0.21148922, 0.22627276, 0.77175814),

        (0.33755697, -0.95091281, 0.31423103),

        (0.27022411, 0.62174096, -0.83995131),

        (0.43026415, 0.82755934, 0.51838333),

        (0.34515256, 0.12072877, 0.93284621),

        (-0.92738684, -0.33247756, -0.82156785),

        (0.33699158, 0.29175872, 0.22843193),

        (-0.8563681, 0.88964499, 0.59505754),

        (0.2283875, 0.56205495, -0.86597468),

        (0.20049869, -0.67177166, 0.33690927),

        (-0.82489381, 0.13129898, -0.71304647),

        (0.93007831, -0.97913281, 0.15260125),

        (0.16171859, 0.60549746, 0.18660708),

        (-0.56605983, -0.4376672, -0.80355261),

        (-0.8542315, 0.59777026, 0.54903978),

        (-0.78070602, -0.6196942, 0.30881963),

        (0.6553524, 0.39294286, -0.90164643),

        (0.65043392, -0.96413667, 0.25880116),

        (0.30577482, 0.62580161, 0.24217116),

        (0.15274576, -0.50988537, -0.70052125),

        (0.12438968, 0.36590175, 0.62994281),

        (0.38698022, 0.22453555, -0.85110107),

        (-0.80355275, 0.44346009, 0.88224876),

        (0.26313235, -0.73589295, 0.33647919),

        (-0.92072183, -0.8748703, 0.20241242),

        (-0.97819777, -0.82760802, 0.13292609),

        (0.11923232, -0.65643469, -0.66725997),

        (0.88294149, 0.17092129, 0.92493397),

        (0.17553081, -0.90884513, 0.77924176),

        (0.22442608, 0.96223872, 0.45966687),

        (0.76130224, -0.28672245, 0.18463901),

        (-0.55113045, -0.77260838, -0.89789975)]

        shape = coxeter.shapes.ConvexPolyhedron(verts)

        vol = shape.volume

 

        # get a scaling factor to set the volume to one

        scale = vol**(1.0/3.0)

 

        # re-scale all of the vertices

        verts /= scale

 

        # re-create the shape with the scaled vertices

        shape = coxeter.shapes.ConvexPolyhedron(verts)

        vol = shape.volume

 

        # check that the volume of the new particle is actually one

        print("initial particle volume",vol)

        #setup mc integrator  

        mc = hoomd.hpmc.integrate.ConvexPolyhedron();

        mc.shape['A'] = dict(vertices=verts)

        mc.d['A'] = d

        mc.a['A'] = a

 

        cpu = hoomd.device.CPU()

        sim = hoomd.Simulation(device=cpu,seed=seed)

        #read state file 

        sim.create_state_from_gsd(filename='lattice_c.gsd')     

 

        sim.operations.integrator = mc

        #sim.operations.writers.append(gsd)

        logger = hoomd.logging.Logger()       

        logger.add(mc, quantities=['type_shapes'])                   

        sim.run(100)        

        overlaps = mc.overlaps

        print(overlaps)                              

        initial_volume_fraction = (sim.state.N_particles * vol/sim.state.box.volume)       

        print(initial_volume_fraction)        

        gsd_file = hoomd.write.GSD(trigger=hoomd.trigger.Periodic(10),filename='Compression_c.gsd',mode='wb')      

        gsd_file.log=logger

        logger.add(mc, quantities=['type_shapes'])

        sim.operations.writers.append(gsd_file)                

        initial_box = sim.state.box

        final_box = hoomd.Box.from_box(initial_box)

        final_volume_fraction = 0.1 #change accordingly

        final_box.volume = sim.state.N_particles * vol / final_volume_fraction                                

        compress = hoomd.hpmc.update.QuickCompress(trigger=hoomd.trigger.Periodic(10),target_box=final_box)

        logger.add(compress)        

        #add compress operation to simulation

        sim.operations.updaters.append(compress)

        Biased_move = hoomd.hpmc.shape_move.Biased(mc=mc, k=k, default_step_size= 0.01, InertiaTarget =InertiaTarget, vertex_move_probability = 0.1)

        Biased_move.volume['A'] = 1

        updater = hoomd.hpmc.update.Shape(shape_move=Biased_move, trigger=hoomd.trigger.Periodic(1))

        updater.shape_move = Biased_move

        sim.operations.updaters.append(updater) 

        logger.add(Biased_move)

        #sim.operations.updaters.add(sim.operations, vertex_move) 

        logger.add(mc, quantities=['type_shapes'])

        tune = hoomd.hpmc.tune.MoveSize.scale_solver(moves=['a', 'd'],

                                             target=0.2,

                                             trigger= hoomd.trigger.Periodic(10),

                                             max_translation_move=0.2,

                                             max_rotation_move=0.2)

        #add tune operation to simulation

        sim.operations.tuners.append(tune)

        # InertiaTarget loop

        #check the InertiaTarget is met if not run for another 1000 step

        inertia=0.1

        j = 0

 

        while (abs(inertia-InertiaTarget) > 0.025):

            sim.run(1000)

            newverts=mc.shape['A']

            print(mc.shape['A'])

            shape = coxeter.shapes.ConvexPolyhedron(newverts['vertices'])

            moment_of_inertia=shape.inertia_tensor.round(3) 

            inertia= np.trace(moment_of_inertia)

            vol=shape.volume

            print('Tr(I):',inertia)

            j += 1

        sim.run(50000)

        shapemove = updater.shape_moves

        print("shape_moves", shapemove)

        Biased_sm= mc.shape['A'] 

        print (Biased_sm)

 

        hoomd.write.GSD.write(state=sim.state, mode='wb', filename='Compression_c.gsd') 

            

@FlowProject.label()

def initialized(job):

    try :

        with open(job.fn('Compression_c.gsd')) as temp_file :

            return True

    except :

        return False

 

@FlowProject.pre.isfile('Compression_c.gsd')

@FlowProject.post.isfile('Compression_c1.gsd')

@FlowProject.operation

def compress1(job):

    with job:

        d = job.sp.d

        a = job.sp.a

        ## dumping period during compression

        dump_period = job.sp.dump_period

        ## logging period during compression

        log_period = job.sp.log_period

        ## random seed

        seed = job.sp.seed

        ## packing fraction

        phi = job.sp.phi

        ## run afterward

        run_steps = job.sp.run_steps

        T = job.sp.T

        seed = 1 #chnage this to an iN_particlesut if I get signac running

        #setup initial spacing with no overlaps 

        InertiaTarget=job.sp.InertiaTarget

        k = job.sp.k

 

        mc = hoomd.hpmc.integrate.ConvexPolyhedron()

        Biased_move = hoomd.hpmc.shape_move.Biased(mc=mc, k=k, default_step_size= 0.01, InertiaTarget=InertiaTarget, vertex_move_probability = 0.1)

        Biased_move.volume['A'] = 1

        updater = hoomd.hpmc.update.Shape(shape_move=Biased_move, trigger=hoomd.trigger.Periodic(1))

        updater.shape_move = Biased_move

 

        #define computation device to store the state   

        cpu = hoomd.device.CPU()

        sim = hoomd.Simulation(device=cpu,seed=seed)

        #read state file 

        sim.create_state_from_gsd(filename='Compression_c.gsd')     

        sim.operations.updaters.append(updater) 

        sim.operations.integrator = mc 

        logger = hoomd.logging.Logger()       

        logger.add(mc, quantities=['type_shapes'])   

        vol=1

        initial_volume_fraction = (sim.state.N_particles * vol/sim.state.box.volume)       

        N_particles = sim.state.N_particles

        print(initial_volume_fraction)        

        gsd_file = hoomd.write.GSD(trigger=hoomd.trigger.Periodic(10),filename='Compression_c1.gsd',mode='wb')      

        gsd_file.log=logger

        logger.add(mc, quantities=['type_shapes'])

        sim.operations.writers.append(gsd_file)                

        

        initial_box = sim.state.box

        final_box = hoomd.Box.from_box(initial_box)

        final_volume_fraction = phi #change accordingly

        final_box.volume = sim.state.N_particles * vol / final_volume_fraction                                

        print(initial_box.Lx,final_box.Ly)

        compress = hoomd.hpmc.update.QuickCompress(trigger=hoomd.trigger.Periodic(10),target_box=final_box)

        logger.add(compress)

        #add compress operation to simulation

        sim.operations.updaters.append(compress)

        print('The packing fraction is', sim.state.N_particles * vol/sim.state.box.volume)   

        

        hoomd.write.GSD.write(state=sim.state, mode='wb', filename='Compression_c1.gsd')    

 

@FlowProject.label

def compressed1(job) :

    try :

        with open(job.fn('Compression_c1.gsd')) as temp_file :

            return True

    except :

        return False

 

 

@FlowProject.pre.isfile('Compression_c1.gsd')

@FlowProject.post.isfile('trajectory_c.gsd')

@FlowProject.operation

def equilibrate(job):

    with job:

        d = job.sp.d

        a = job.sp.a

        k = job.sp.k

        InertiaTarget= job.sp.InertiaTarget

        ## dumping period during compression

        dump_period = job.sp.dump_period

        ## logging period during compression

        log_period = job.sp.log_period

        run_steps = job.sp.run_steps

        ## random seed

        seed = job.sp.seed

        ## packing fraction

        ## run afterward

 

 

        #setup mc integrator  

        mc = hoomd.hpmc.integrate.ConvexPolyhedron()

      

         

 

        cpu = hoomd.device.CPU()

        sim = hoomd.Simulation(device=cpu,seed=1)

        #read state file 

        sim.create_state_from_gsd(filename='Compression_c1.gsd')     

        mc = hoomd.hpmc.integrate.ConvexPolyhedron()

         

        sim.operations.integrator = mc

 

        logger = hoomd.logging.Logger()

        logger.add(mc, quantities=['type_shapes'])

 

        sim.run(100)

 

        overlaps = mc.overlaps

        print("overlaps",overlaps)

 

 

        Biased_move = hoomd.hpmc.shape_move.Biased(mc=mc, k=k, default_step_size= 0.01, InertiaTarget=InertiaTarget, vertex_move_probability = 0.1)

        Biased_move.volume['A'] = 1

        updater = hoomd.hpmc.update.Shape(shape_move=Biased_move, trigger=hoomd.trigger.Periodic(1))

        updater.shape_move = Biased_move

        sim.operations.updaters.append(updater) 

 

 

        #%%Equilibrate the sys

        gsd_file = hoomd.write.GSD(trigger=hoomd.trigger.Periodic(1000),filename='trajectory_c.gsd',mode='wb')

        logger = hoomd.logging.Logger()  

        gsd_file.log=logger

        logger.add(mc, quantities=['type_shapes'])

        sim.operations.writers.append(gsd_file)

       

        tune = hoomd.hpmc.tune.MoveSize.scale_solver(

            moves=['a', 'd'],

            target=0.2,

            trigger=hoomd.trigger.And([

                hoomd.trigger.Periodic(100),

                hoomd.trigger.Before(sim.timestep + 5000)

            ]))

         

        sim.operations.tuners.append(tune)

        

 

        sim.run(run_steps) 





Thanks,

Oyin

Joshua Anderson

unread,
May 1, 2023, 10:55:15 AM5/1/23
to hoomd...@googlegroups.com
Oyin,

Your code is not a minimal demonstration of the issue and appears to use a modified version of HOOMD-blue. Only you are able to troubleshoot this problem further. If you would like help from users on this mailing list, please post a minimal script that runs with HOOMD-blue v3.11.0 and requires no external dependencies along with the full error message (including the backtrace).
------
Joshua A. Anderson, Ph.D.
Research Area Specialist, Chemical Engineering, University of Michigan

--
You received this message because you are subscribed to the Google Groups "hoomd-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to hoomd-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/hoomd-users/CAEPx1DwzNH3L_aJStAEwEQx2FaKxdC818ryzT1SWQdqtvYd6nA%40mail.gmail.com.

oyin alabi

unread,
May 5, 2023, 6:56:19 AM5/5/23
to hoomd...@googlegroups.com
Hi,
Please find below the code that uses Hoomd version 3.11.0. Here is the initialize code:

 

import argparse

from hashlib import sha1

 

import signac

import numpy as np

import random

 

def main(args, random_seed) :

    project = signac.get_project()

    m = 4

     

    for N_particles in [432]:

        for phi in [0.6] :

            for rep in range(args.num_replicas) :

                statepoint = dict(

                    m = m,

                    # number of particles

                    N_particles= 2* m**3,

                    ## trans and rot moves

                    d = 0.15,

                    a = 0.2,

                    T = 10000,

                    ## packing fraction

                    phi = 0.55,

                    

                    rep = rep,

                    ## dumping period during compression

                    dump_period = 1e6,

                    ## logging period during compression

                    log_period = 1e6,

                    ## equilibration time

                    equil_steps = 1e5,

                    ## run steps

                    run_steps = 1e6,

                    # random seed

                    seed =  random.randint(1,1e6))

    project.open_job(statepoint).init()

 

 

    seeds = []

    for job in project.find_jobs() :

        seeds.append(job.statepoint()['seed'])

    if (len(seeds) == len(set(seeds))) :

        print("all random seed numbers are unique!")

    else :

        print("all random seed numbers are not unique!")

 

if __name__ == '__main__' :

    parser = argparse.ArgumentParser(

        description="Initialize the data space.")

    parser.add_argument(

        '--random',

        type=str,

        help="A string to generate a random seed.")

    parser.add_argument(

        '-n', '--num-replicas',

        type=int,

        default=1,

        help="Initialize multiple replications.")

    args = parser.parse_args()

 

    # Generate an integer from the random str.

    try :

        random_seed = args.random

    except ValueError :

        random_seed = sha1(args.random.encode().hexdigest(), 16) % (10 ** 8)

 

    main(args, random_seed)

Here is the operations code

        #k = job.sp.k

        #InertiaTarget= job.sp.InertiaTarget

        mc = hoomd.hpmc.integrate.ConvexPolyhedron()

        mc.shape['A'] = dict(vertices=verts)

        mc.d['A'] = d

        mc.a['A'] = a

 

         

        #read state file 

        sim.create_state_from_gsd(filename='lattice_c.gsd')     

 

        sim.operations.integrator = mc

        #sim.operations.writers.append(gsd)

        logger = hoomd.logging.Logger()       

        logger.add(mc, quantities=['type_shapes'])                   

        sim.run(100)        

        overlaps = mc.overlaps

        print(overlaps)                              

        initial_volume_fraction = (sim.state.N_particles * vol/sim.state.box.volume)       

        print(initial_volume_fraction)        

        gsd_file = hoomd.write.GSD(trigger=hoomd.trigger.Periodic(10),filename='Compression_c.gsd',mode='wb')      

        gsd_file.log=logger

        logger.add(mc, quantities=['type_shapes'])

        sim.operations.writers.append(gsd_file)                

        initial_box = sim.state.box

        final_box = hoomd.Box.from_box(initial_box)

        final_volume_fraction = 0.1 #change accordingly

        final_box.volume = sim.state.N_particles * vol / final_volume_fraction                                

        compress = hoomd.hpmc.update.QuickCompress(trigger=hoomd.trigger.Periodic(10),target_box=final_box)

        logger.add(compress)        

        #add compress operation to simulation

        sim.operations.updaters.append(compress)

        default_step_size= 0.01 

        nselect=1

        vertex_move = hpmc.shape_move.Vertex(vertex_move_probability = 1)

        vertex_move.volume['A'] = 1

        updater = hpmc.update.Shape(shape_move=vertex_move, trigger=hoomd.trigger.Periodic(1))

        updater.shape_move = vertex_move

        logger.add(vertex_move)

        #sim.operations.updaters.add(sim.operations, vertex_move) 

        logger.add(mc, quantities=['type_shapes'])

        tune = hoomd.hpmc.tune.MoveSize.scale_solver(moves=['a', 'd'],

                                             target=0.2,

                                             trigger= hoomd.trigger.Periodic(10),

                                             max_translation_move=0.2,

                                             max_rotation_move=0.2)

        

        sim.run(50000)

         

        shapemove = updater.shape_moves

        print("shape_moves", shapemove)

        vertex_move= mc.shape['A'] 

        print (vertex_move)

        default_step_size= 0.01 

        nselect=1

        vertex_move = hpmc.shape_move.Vertex(vertex_move_probability = 1)

        vertex_move.volume['A'] = 1

        updater = hpmc.update.Shape(shape_move=vertex_move, trigger=hoomd.trigger.Periodic(1))

        updater.shape_move = vertex_move

        ## dumping period during compression

        dump_period = job.sp.dump_period

        ## logging period during compression

        log_period = job.sp.log_period

        run_steps = job.sp.run_steps

        ## random seed

        seed = job.sp.seed

        ## packing fraction

        ## run afterward

 

 

        #setup mc integrator  

        mc = hoomd.hpmc.integrate.ConvexPolyhedron()

      

         

 

        cpu = hoomd.device.CPU()

        sim = hoomd.Simulation(device=cpu,seed=1)

        #read state file 

        sim.create_state_from_gsd(filename='Compression_c1.gsd')     

        mc = hoomd.hpmc.integrate.ConvexPolyhedron()

        n_verts= mc.shape['A']

        mc.shape['A'] = dict(vertices=n_verts['vertices']) # Because the vertex has changed I can't use the initial vertices so I tried this out

        

        sim.operations.integrator = mc

 

        logger = hoomd.logging.Logger()

        logger.add(mc, quantities=['type_shapes'])


        nselect=1

        vertex_move = hpmc.shape_move.Vertex(default_step_size= 0.01, vertex_move_probability = 1)

        vertex_move.volume['A'] = 1

        updater = hpmc.update.Shape(shape_move=vertex_move, trigger=hoomd.trigger.Periodic(1))

        updater.shape_move = vertex_move

        sim.operations.updaters.append(updater) 

 

 

        #%%Equilibrate the sys

        gsd_file = hoomd.write.GSD(trigger=hoomd.trigger.Periodic(1000),filename='trajectory_c.gsd',mode='wb')

        logger = hoomd.logging.Logger()  

        gsd_file.log=logger

        logger.add(mc, quantities=['type_shapes'])

        sim.operations.writers.append(gsd_file)

       

        tune = hoomd.hpmc.tune.MoveSize.scale_solver(

            moves=['a', 'd'],

            target=0.2,

            trigger=hoomd.trigger.And([

                hoomd.trigger.Periodic(100),

                hoomd.trigger.Before(sim.timestep + 5000)

            ]))

         

        sim.operations.tuners.append(tune)

        

 

        sim.run(run_steps)  #here is the part that gives the error

 

 

@FlowProject.pre.isfile('trajectory_c.gsd')

@FlowProject.post.isfile('Simf_c.gsd')

@FlowProject.operation

def equilibrate1(job):

        traj = gsd.hoomd.open('trajectory_c.gsd') #open previous trajectory

        num_frames= len(traj)

        solid = freud.order.SolidLiquid(l=6, q_threshold=0.7, solid_threshold=6)

        is_solid = []

        for frame in traj:

            solid.compute(system=(frame.configuration.box, frame.particles.position),

                  neighbors=dict(mode='nearest', num_neighbors=8))

            is_solid.append(solid.num_connections > solid.solid_threshold)

        num_solid = np.array([np.sum(a) for a in is_solid])

        np.savetxt('num_parts.csv',num_solid, delimiter= ',')

        print(num_solid)

        gsd_file = hoomd.write.GSD( trigger=hoomd.trigger.Periodic(10), mode='wb', filename='Simf_c.gsd', log=logger) #save for next part

        gsd_file.log =logger

        logger.add(mc, quantities=['type_shapes'])

        sim.operations.writers.append(gsd_file)

        sim.run(T)

        num_overlaps = mc.overlaps #The integrator performs the MC steps(i.e altering a,d), then it checks for overlaps

        print('overlaps=',num_overlaps)

        from garnett.reader import GSDHOOMDFileReader

        from garnett.writer import PosFileWriter

        gsd_reader = GSDHOOMDFileReader()

        writer = PosFileWriter()

        with open('Simf_c.gsd', 'rb') as gsdfile:

            traj = gsd_reader.read(gsdfile)

            with open('Simf_c.pos', 'w', encoding='utf-8') as posfile:

                writer.write(traj, posfile)

        gsd_reader = GSDHOOMDFileReader()

        writer = PosFileWriter()

        with open('Compression_c1.gsd', 'rb') as gsdfile:

            traj = gsd_reader.read(gsdfile)

            with open('Compression_c1.pos', 'w', encoding='utf-8') as posfile:

                writer.write(traj, posfile)

if __name__ == '__main__':

    from flow import FlowProject

    FlowProject().main()

  And Here  is the error message 

Error message

(base) tola@lasiurus:~/Downloads/hoomd2/hoomd-blue/build/my_project$ python SigVertSm.py run --progress

Using environment configuration: StandardEnvironment

  0%|                                                                                           | 0/1 [00:00<?, ?it/s]

Traceback (most recent call last):

  File "/home/tola/miniconda3/lib/python3.8/site-packages/flow/project.py", line 3475, in _execute_operation

    self._operations[operation.name](*operation._jobs)

  File "/home/tola/miniconda3/lib/python3.8/site-packages/flow/project.py", line 625, in __call__

    return self._op_func(*jobs)

  File "SigVertSm.py", line 316, in equilibrate

    sim.run(run_steps) 

  File "/home/tola/miniconda3/lib/python3.8/site-packages/hoomd/simulation.py", line 453, in run

    self.operations._schedule()

  File "/home/tola/miniconda3/lib/python3.8/site-packages/hoomd/operations.py", line 184, in _schedule

    self.integrator._attach()

  File "/home/tola/miniconda3/lib/python3.8/site-packages/hoomd/hpmc/integrate.py", line 425, in _attach

    super()._attach()

  File "/home/tola/miniconda3/lib/python3.8/site-packages/hoomd/operation.py", line 395, in _attach

    super()._attach()

  File "/home/tola/miniconda3/lib/python3.8/site-packages/hoomd/operation.py", line 226, in _attach

    self._apply_typeparam_dict(self._cpp_obj, self._simulation)

  File "/home/tola/miniconda3/lib/python3.8/site-packages/hoomd/operation.py", line 255, in _apply_typeparam_dict

    typeparam._attach(cpp_obj, simulation.state)

  File "/home/tola/miniconda3/lib/python3.8/site-packages/hoomd/data/typeparam.py", line 171, in _attach

    self.param_dict._attach(cpp_obj, self.name,

  File "/home/tola/miniconda3/lib/python3.8/site-packages/hoomd/data/parameterdicts.py", line 515, in _attach

    self._single_setitem(key, parameters[key])

  File "/home/tola/miniconda3/lib/python3.8/site-packages/hoomd/data/parameterdicts.py", line 458, in _single_setitem

    getattr(self._cpp_obj, self._setter)(key, item)

RuntimeError: Unable to cast Python instance to C++ type (compile in debug mode for details)

 

The above exception was the direct cause of the following exception:

 

Traceback (most recent call last):

  File "SigVertSm.py", line 357, in <module>

    FlowProject().main()

  File "/home/tola/miniconda3/lib/python3.8/site-packages/flow/project.py", line 5132, in main

    args.func(args)

  File "/home/tola/miniconda3/lib/python3.8/site-packages/flow/project.py", line 4844, in _main_run

    run()

  File "/home/tola/miniconda3/lib/python3.8/site-packages/flow/project.py", line 3720, in run

    self._run_operations(

  File "/home/tola/miniconda3/lib/python3.8/site-packages/flow/project.py", line 3305, in _run_operations

    self._execute_operation(operation, timeout, pretend)

  File "/home/tola/miniconda3/lib/python3.8/site-packages/flow/project.py", line 3477, in _execute_operation

    raise UserOperationError(execution_error_message) from error

flow.errors.UserOperationError: An exception was raised during operation equilibrate for job or aggregate with id 9a1c427d69e72f81804ae08dca35cb48.

 

 I'd appraciate any suggestion.


Thanks,

Oyin

 

 

 


Brandon Butler

unread,
May 5, 2023, 10:03:50 AM5/5/23
to hoomd...@googlegroups.com

Hey Ovin,

Thanks for moving to hoomd version 3.11.0. However, this really isn't a minimal example. You are using signac in the example and it looks like there is a lot of code likely not related to the problem. It is helpful to people on the list if a bug is shown in a minimal script. That is a script that contains the minimal complexity, but still errors. While this takes some effort on the person asking's side, it greatly aids though attempting to help debug you script.

Best,

  File "/home/tola/miniconda3/lib/python3.8/site-packages/hoomd/data/parameterdicts.py",line 515, in _attach

To view this discussion on the web visit https://groups.google.com/d/msgid/hoomd-users/CAEPx1DwUg8H1vn_fGR0nvR0R21Z%3D5Kd3Mr85c%2Bd_0ce7U8w%3Dkw%40mail.gmail.com.
--
Brandon Butler
MolSSI Fellow
PhD Candidate, Chemical Engineering and Scientific Computing | Glotzer Lab, University of Michigan
Email: butl...@umich.edu

oyin alabi

unread,
May 8, 2023, 7:19:51 AM5/8/23
to hoomd...@googlegroups.com
Hi,
I found the error, I used:
nvert=mc.shape['A']["vertices"]
mc.shape['A']= dict(vertices=[ ])

And the code works now.

Thanks,
Oyin

oyin alabi

unread,
May 9, 2023, 5:49:58 AM5/9/23
to hoomd...@googlegroups.com
Hi,
Although I am not getting any errors, I am unable to get the current vertices for use in the equilbrate section of the code. Is there a way to extract the current vertices from the code below after the vertex move and use them in the next step? Please find below the minimal version.

Thanks,
Oyin

 
from __future__ import division
from __future__ import print_function
import numpy as np
import copy
import math
import itertools
from collections import OrderedDict
import garnett
import gsd
import gsd.hoomd
import coxeter
import hoomd
from hoomd import hpmc

# %% startup parameters  
T =10000  
m= 2
N_particles= 2* m**3

seed = 1  

#setup  

spacing = 1.2
K = math.ceil(N_particles**(1 / 3))
L = K * spacing
x = np.linspace(-L / 2, L / 2, K, endpoint=False)
position = list(itertools.product(x, repeat=3))
position = position[0:N_particles]
orientation = [(1, 0, 0, 0)] * N_particles

#define initial snapshot state
snapshot = gsd.hoomd.Snapshot()
snapshot.particles.N = N_particles
snapshot.configuration.box = [L, L, L,0, 0, 0]
snapshot.particles.typeid = [0] * N_particles
snapshot.particles.types = ['cube']

snapshot.particles.position = position
snapshot.particles.orientation = orientation
with gsd.hoomd.open(name='lattice_c.gsd', mode='wb') as f:
    f.append(snapshot)

cpu = hoomd.device.CPU()
sim = hoomd.Simulation(device=cpu,seed=seed)

verts = [[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]]

shape = coxeter.shapes.ConvexPolyhedron(verts)
vol = shape.volume
#setup mc integrator  
mc = hoomd.hpmc.integrate.ConvexPolyhedron();
mc.shape['cube'] = dict(vertices=[
    (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)
])
mc.d['cube'] = 0.15
mc.a['cube'] = 0.2

 
#read state file
sim.create_state_from_gsd(filename='lattice_c.gsd')    
sim.operations.integrator = mc
logger = hoomd.logging.Logger()
logger.add(mc, quantities=['type_shapes'])          
sim.run(100)

overlaps = mc.overlaps
print(overlaps)              

initial_volume_fraction = (sim.state.N_particles * vol/sim.state.box.volume)
print(initial_volume_fraction)

gsd_file = hoomd.write.GSD(trigger=hoomd.trigger.Periodic(10),filename='Compression_c.gsd',mode='wb')      #added a file to just record compression and on

gsd_file.log=logger
logger.add(mc, quantities=['type_shapes'])
sim.operations.writers.append(gsd_file)

 
initial_box = sim.state.box
final_box = hoomd.Box.from_box(initial_box)
final_volume_fraction = 0.7                #change accordingly

final_box.volume = sim.state.N_particles * vol / final_volume_fraction

compress = hoomd.hpmc.update.QuickCompress(trigger=hoomd.trigger.Periodic(10),target_box=final_box)

logger.add(compress)
#add compress operation to simulation
sim.operations.updaters.append(compress)

"VERTEX MOVES"
nselect =0.01
 
cube_verts = [ (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)]
mc.shape['cube'] = dict(vertices=np.asarray([ (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)]))

"VERTEX MOVES"
vertex_move = hoomd.hpmc.shape_move.Vertex(default_step_size= 0.01, vertex_move_probability = 1)
vertex_move.volume['cube'] = 1
updater = hoomd.hpmc.update.Shape(shape_move=vertex_move, trigger=hoomd.trigger.Periodic(1))
updater.shape_move = vertex_move
sim.operations.updaters.append(updater)
logger.add(vertex_move)

 
logger.add(mc, quantities=['type_shapes'])

tune = hoomd.hpmc.tune.MoveSize.scale_solver(moves=['a', 'd'],
                                             target=0.2,
                                             trigger= hoomd.trigger.Periodic(10),
                                             max_translation_move=0.2,
                                             max_rotation_move=0.2)

#add tune operation to simulation
sim.operations.tuners.append(tune)
sim.run(1000)

shapemove = updater.shape_moves
print("shape_moves", shapemove)

vertex_sm= mc.shape['cube']
print (vertex_sm)
 
hoomd.write.GSD.write(state=sim.state, mode='wb', filename='simulation.gsd')  

Brandon Butler

unread,
May 9, 2023, 10:39:58 AM5/9/23
to hoomd...@googlegroups.com

Oyin,

Does "mc.shape['cube']" not work?

Also you have logger.add(mc, ["type_shapes"]) multiple times. You only need it once. You also only need to set the mc.shape values once.

Best,

Brandon

oyin alabi

unread,
May 9, 2023, 1:05:01 PM5/9/23
to hoomd...@googlegroups.com

Hi,

I have edited the code as suggested however the mc.shape['cube'] does not work in the equilibrate part of the code. The equilibrate tutorial specifies the vertices before creating the state from a gsd file. But in this case the vertices have changed and  I am wondering if there is a way to read the current vertices from the gsd file or snapshot. Please find below the edited code.

Thanks,
Oyin

from __future__ import division

 

from __future__ import print_function

 

import numpy as np

 

import copy

 

import math

 

import itertools

 

from collections import OrderedDict

 

import garnett

 

import signac

 

import freud

 

import gsd

 

import gsd.hoomd

 

import coxeter

 

import hoomd

 

from hoomd import hpmc

 

# %% startup parameters 

 

T =10000 

 

m= 2

 

N_particles= 2* m**3

 

 

 

seed = 1 

 

 

 

#setup initial spacing with no overlaps

 

spacing = 1.2

 

K = math.ceil(N_particles**(1 / 3))

 

L = K * spacing

 

x = np.linspace(-L / 2, L / 2, K, endpoint=False)

 

position = list(itertools.product(x, repeat=3))

 

position = position[0:N_particles]

 

orientation = [(1, 0, 0, 0)] * N_particles

 

 

 

#define initial snapshot state

 

snapshot = gsd.hoomd.Snapshot()

 

snapshot.particles.N = N_particles

 

snapshot.configuration.box = [L, L, L,0, 0, 0]

 

snapshot.particles.typeid = [0] * N_particles

 

snapshot.particles.types = ['cube']

 

snapshot.particles.position = position

 

snapshot.particles.orientation = orientation

 

with gsd.hoomd.open(name='lattice_c.gsd', mode='wb') as f:

 

    f.append(snapshot)

 

 

 

#define computation device to store the state  

 

cpu = hoomd.device.CPU()

 

sim = hoomd.Simulation(device=cpu,seed=seed)

 

 

 

 

 

# %% particle volume using coxeter

 

cube_verts = [ (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)]

 

 

 

shape = coxeter.shapes.ConvexPolyhedron(cube_verts)

 

vol = shape.volume

 

#setup mc integrator 

 

mc = hoomd.hpmc.integrate.ConvexPolyhedron()

 

mc.shape['cube'] = dict(vertices=[

 

    (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)

 

])

 

mc.d['cube'] = 0.15

 

mc.a['cube'] = 0.2

 

 

 

#read state file

 

sim.create_state_from_gsd(filename='lattice_c.gsd')    

 

sim.operations.integrator = mc

 

#sim.operations.writers.append(gsd)

 

 

 

sim.run(100)

 

 

 

overlaps = mc.overlaps

 

print(overlaps)             

 

 

 

initial_volume_fraction = (sim.state.N_particles * vol/sim.state.box.volume)

 

print(initial_volume_fraction)

 

 

 

gsd_file = hoomd.write.GSD(trigger=hoomd.trigger.Periodic(10),filename='Compression_c.gsd',mode='wb')      #added a file to just record compression and on

 

gsd_file.log=logger

 

logger.add(mc, quantities=['type_shapes'])

 

sim.operations.writers.append(gsd_file)

 

 

 

initial_box = sim.state.box

 

final_box = hoomd.Box.from_box(initial_box)

 

final_volume_fraction = 0.7                #change accordingly

 

final_box.volume = sim.state.N_particles * vol / final_volume_fraction

 

 

 

compress = hoomd.hpmc.update.QuickCompress(trigger=hoomd.trigger.Periodic(10),target_box=final_box)

 

 

 

logger.add(compress)

 

#add compress operation to simulation

 

sim.operations.updaters.append(compress)

 

 

 

"VERTEX MOVES"

 

nselect =0.0005

 

 

"VERTEX MOVES"

 

vertex_move = hoomd.hpmc.shape_move.Vertex(default_step_size= 0.01, vertex_move_probability = 1)

 

vertex_move.volume['cube'] = 1

 

updater = hoomd.hpmc.update.Shape(shape_move=vertex_move, trigger=hoomd.trigger.Periodic(1))

 

updater.shape_move = vertex_move

 

sim.operations.updaters.append(updater)

 

logger.add(vertex_move)

 

logger.add(mc, quantities=['type_shapes'])

 

 

 

tune = hoomd.hpmc.tune.MoveSize.scale_solver(moves=['a', 'd'],

 

                                             target=0.2,

 

                                             trigger= hoomd.trigger.Periodic(10),

 

                                             max_translation_move=0.2,

 

                                             max_rotation_move=0.2)

 

 

 

#add tune operation to simulation

 

sim.operations.tuners.append(tune)

 

sim.run(1000)

 

shapemove = updater.shape_moves

 

print("shape_moves", shapemove)


vertex_sm= mc.shape['cube']

 

print (vertex_sm)

 

hoomd.write.GSD.write(state=sim.state, mode='wb', filename='simulation.gsd')  

#%%

from __future__ import division

 

from __future__ import print_function

 

import numpy as np

 

import copy

 

import math

 

import itertools

 

from collections import OrderedDict

 

import garnett

 

import freud

 

import gsd

 

import gsd.hoomd

 

import coxeter

 

import hoomd

 

from hoomd import hpmc

 

cpu = hoomd.device.CPU()

sim = hoomd.Simulation(device=cpu, seed=20)

mc = hoomd.hpmc.integrate.ConvexPolyhedron()

'''mc.shape['cube'] = dict(vertices=[       

    (-0.5, 0, 0),

    (0.5, 0, 0),

    (0, -0.5, 0),

    (0, 0.5, 0),

    (0, 0, -0.5),

    (0, 0, 0.5),

])'''// Is there a way to extract the current vertices from the code above

sim.operations.integrator = mc

sim.create_state_from_gsd(filename='simulation.gsd')

 

 

 


Brandon Butler

unread,
May 9, 2023, 3:02:33 PM5/9/23
to hoomd...@googlegroups.com

I am assuming that you have two files, and the second is the one you want to keep the shape from the first. This is not clear in your example and perhaps labeling them in the future would help. Given this information, however, I know your problem. You need to read the type_shape value from the GSD file (with the gsd package) and read the last frames 'particles/type_shapes' value which will be a JSON valid string in gsd.fl or a tuple of dictionaries in gsd.hoomd. You can use the vertices from that for your initial shape in the second file.

Best,

Brandon

oyin alabi

unread,
May 11, 2023, 5:00:09 AM5/11/23
to hoomd...@googlegroups.com
Hi,
Thanks for your suggestion, I have been able to read the vertices however I am wondering if there is a way to append the vertices to a list so that I can input them into the mc.shape['cube']=dict(vertices=vertices). Please find below the code.

Thanks,
Oyin

vertex_move = hoomd.hpmc.shape_move.Vertex(default_step_size= 0.01, vertex_move_probability = 1)

sim = hoomd.Simulation(device=cpu, seed=1)

sim.operations.integrator = mc

mc = hoomd.hpmc.integrate.ConvexPolyhedron()

sim.create_state_from_gsd('simulation.gsd')

traj = gsd.hoomd.open('simulation.gsd', 'rb')

#append vertices

vertices=[]

traj2=traj[-1].particles.type_shapes 

print(traj2)

#traj2.append(vertices) I am wondering if there is a way I can append the vertices as a list

mc.shape['cube'] = dict(vertices=vertices)




Brandon Butler

unread,
May 11, 2023, 10:20:59 AM5/11/23
to hoomd...@googlegroups.com

I think you mean access the vertices, not append them. Given your code mc.shape["cube"] = {"vertices": traj2[0]["vertices"]} should work. This isn't really a HOOMD question though. I would recommend one of many Python tutorials to help familiarize yourself with Python as a programming language.

Best,

Brandon

oyin alabi

unread,
May 12, 2023, 4:26:40 PM5/12/23
to hoomd...@googlegroups.com
Hi,
Thanks for your suggestions, I will search for some tutorials online. I tried mc.shape["cube"] = {"vertices": traj2[0]["vertices"]} but it didn't work. 

Thanks,
Oyin

oyin alabi

unread,
May 16, 2023, 8:04:06 PM5/16/23
to hoomd...@googlegroups.com
Hi Brandon,
Thank you so much for your suggestions, I found a tutorial online and realized that I had tampered with some of the hoomd source code, thus my code wasn't working. After re-editing the code, I was able to run it using the mc.shape["cube"] = {"vertices": traj2[0]["vertices"]} you suggested without further error.

Thanks again,
Oyin
Reply all
Reply to author
Forward
0 new messages