Пример #1
0
def CreateCCbonds():
    create_CCbonds = CreateBondsModifier(
        mode=CreateBondsModifier.Mode.Pairwise, lower_cutoff=1.4)
    create_CCbonds.set_pairwise_cutoff('C', 'C', 1.6)
    create_CCbonds.bond_type = Bond1
    create_CCbonds.vis.use_particle_colors = False
    # create_CCbonds.vis.width=0.1

    return create_CCbonds
Пример #2
0
def CreateCHbonds():  #returns a modifier
    create_CHbonds = CreateBondsModifier(
        mode=CreateBondsModifier.Mode.Pairwise)
    create_CHbonds.set_pairwise_cutoff('C', 'H', 1.2)
    create_CHbonds.bond_type = Bond1
    create_CHbonds.vis.use_particle_colors = False
    # create_CHbonds.vis.width=0.1

    return create_CHbonds
Пример #3
0
def CreateDoublebonds():
    create_doublebonds = CreateBondsModifier(
        mode=CreateBondsModifier.Mode.Pairwise)
    create_doublebonds.set_pairwise_cutoff('C', 'O', 1.3)
    create_doublebonds.set_pairwise_cutoff('C', 'C', 1.4)
    create_doublebonds.bond_type = Bond2
    create_doublebonds.vis.use_particle_colors = False
    #create_bonds.set_pairwise_cutoff('C','C',1.6)
    # create_doublebonds.vis.width=0.3

    return create_doublebonds
Пример #4
0
def Frame_CNA(frame, R_Cut, Masterkey=None, filename=None):

    pipeline = import_file(filename)
    pipeline.modifiers.append(CreateBondsModifier(cutoff=R_Cut))

    pipeline.modifiers.append(
        CommonNeighborAnalysisModifier(
            mode=CommonNeighborAnalysisModifier.Mode.BondBased))
    data = pipeline.compute(frame)
    # The 'CNA Indices' bond property is a a two-dimensional array
    # containing the three CNA indices computed for each bond in the system.
    cna_indices = data.particles.bonds['CNA Indices']

    # This helper function takes a two-dimensional array and computes the frequency
    # histogram of the data rows using some NumPy magic.
    # It returns two arrays (of same length):
    #    1. The list of unique data rows from the input array
    #    2. The number of occurences of each unique row
    def row_histogram(a):
        ca = np.ascontiguousarray(a).view([('', a.dtype)] * a.shape[1])
        unique, indices, inverse = np.unique(ca,
                                             return_index=True,
                                             return_inverse=True)
        counts = np.bincount(inverse)
        return (a[indices], counts)

    # Used below for enumerating the bonds of each particle:
    bond_enumerator = BondsEnumerator(data.particles.bonds)
    # Loop over particles and print their CNA indices.
    all_cnas = {}
    for particle_index in range(data.particles.count):

        # Create local list with CNA indices of the bonds of the current particle.
        bond_index_list = list(
            bond_enumerator.bonds_of_particle(particle_index))
        local_cna_indices = cna_indices[bond_index_list]
        # Count how often each type of CNA triplet occurred.
        unique_triplets, triplet_counts = row_histogram(local_cna_indices)
        # Print list of triplets with their respective counts.

        for triplet, count in zip(unique_triplets, triplet_counts):
            try:
                all_cnas[tuple(triplet)] += count

            except KeyError:
                all_cnas[tuple(triplet)] = count
                if tuple(triplet) not in Masterkey:
                    Masterkey.append(tuple(triplet))
    return all_cnas, Masterkey
Пример #5
0
from ovito.io import import_file
from ovito.modifiers import CreateBondsModifier
from ovito.data import Bonds, SimulationCell

# Load a set of atoms and create bonds between pairs of atoms that are within
# a given cutoff distance of each other using the Create Bonds modifier.
pipeline = import_file('trajectory.dump')
pipeline.modifiers.append(CreateBondsModifier(cutoff=3.4))

# Evaluate pipeline and retrieve the Bonds data object.
bonds = pipeline.compute().expect(Bonds)
print("Number of generated bonds: ", len(bonds))

for i in range(len(bonds)):
    print('Bond %i from atom %i to atom %i' % (i, bonds[i, 0], bonds[i, 1]))

from ovito.vis import BondsDisplay
import numpy

# Configure visual appearance of bonds:
bonds.display.enabled = True
bonds.display.shading = BondsDisplay.Shading.Flat
bonds.display.width = 0.3

# Computing bond vectors.
data = pipeline.compute()
bonds = data.expect(Bonds)
particle_positions = data.particle_properties['Position']
bond_vectors = particle_positions[bonds[:, 1]] - particle_positions[bonds[:,
                                                                          0]]
cell = data.expect(SimulationCell)
Пример #6
0
parser.add_argument('--concentration', metavar="TMS Concentration", type=float, default=0.0,
                    help="The concentration of surafce TMS in C3H9Si/nm^2")

args = parser.parse_args()
node = import_file(args.filename)
print("... loading %s"%(args.filename) )
print("... %d files"%(node.source.num_frames))
print("... cutoff for core region %d A"%(args.coreCutoff))



#### Create a bonds modifier (mod) and apply it to the system
###################################################################################
rcut = args.bondLength
modbonds = CreateBondsModifier(mode = CreateBondsModifier.Mode.Pairwise)
modbonds.set_pairwise_cutoff("Type 1", "Type 2", rcut)
modmesh = ConstructSurfaceModifier(radius=5.0)

modbondcount = PythonScriptModifier(function = create_bond_count_particle)
modbondnghbr = PythonScriptModifier(function = create_bond_neighbors_particle)

print("")
print("... adding modifiers")
print("      creating Si-O bonds using cutoff = %1.4f"%(rcut))
print("      calculating bond count")
print("      calculating nearest-neighbor bonded atoms")
node.modifiers.append(modmesh)
node.modifiers.append(modbonds)
node.modifiers.append(modbondcount)
node.modifiers.append(modbondnghbr)
Пример #7
0
def write(atoms,
          filename,
          bond_specs=None,
          atom_style="molecular",
          size=(640, 480),
          camera_dir=(2, 1, -1),
          viewport_type="perspective",
          atom_radii=None):
    """Write atoms to lammps data file

    :param atoms: The atoms object to write to file
    :type atoms: ase.Atoms
    :param filename: filename to write to. Can either have suffix `.data` or `.png`, in which case a Lammps data file or a png picture will be produced, respectively.
    :type filename: str
    :param bonds_spec: List of (element1, element2, cutoff)
    :type bonds_spec: List of tuples
    """
    import os
    suffix = os.path.splitext(filename)[1]

    if not suffix in [".data", ".png"]:
        raise ValueError(f"Invalid file format {suffix}")

    import tempfile
    import os
    from ase.formula import Formula
    # Using tempfile and write + read rather than ovito's ase_to_ovito and back because the
    # ordering of particle types for some (bug) reason becomes unpredictable
    with tempfile.TemporaryDirectory() as tmp_dir:
        symbols = list(Formula(atoms.get_chemical_formula()).count().keys())
        symbols_dict = {}
        for i, symbol in enumerate(symbols):
            symbols_dict[symbol] = i + 1
        atoms.write(os.path.join(tmp_dir, "tmp.data"),
                    format="lammps-data",
                    specorder=symbols)

        from ovito.io import import_file, export_file
        from ovito.modifiers import CreateBondsModifier

        pipeline = import_file(os.path.join(tmp_dir, "tmp.data"))

        types = pipeline.source.data.particles_.particle_types
        for symbol, i in symbols_dict.items():
            types.type_by_id(i).name = symbol
            types.type_by_id(i).load_defaults()

        if not atom_radii is None:
            types = pipeline.source.data.particles.particle_types
            for pair in atom_radii:
                types.type_by_id(symbols_dict[pair[0]]).radius = pair[1]

        # Accept a single tuple not contained in a list if there is only one bond type.
        if not bond_specs is None:
            bondsmodifier = CreateBondsModifier(
                mode=CreateBondsModifier.Mode.Pairwise)
            if not isinstance(bond_specs, list) and isinstance(
                    bond_specs, tuple):
                bond_specs = [bond_specs]
            for element in bond_specs:
                bondsmodifier.set_pairwise_cutoff(symbols_dict[element[0]],
                                                  symbols_dict[element[1]],
                                                  element[2])
            pipeline.modifiers.append(bondsmodifier)
        pipeline.compute()

        if suffix == ".data":
            export_file(pipeline,
                        filename,
                        "lammps/data",
                        atom_style=atom_style)

        elif suffix == ".png":

            from ovito.vis import Viewport, TachyonRenderer, OpenGLRenderer
            pipeline.add_to_scene()

            if viewport_type == "perspective":
                vp = Viewport(type=Viewport.Type.Perspective,
                              camera_dir=camera_dir)
            elif viewport_type == "orthogonal":
                vp = Viewport(type=Viewport.Type.Ortho, camera_dir=camera_dir)
            else:
                raise ValueError(
                    "viewport type has to be perspective or orthogonal")

            vp.zoom_all(size=size)
            vp.render_image(filename=filename,
                            size=size,
                            renderer=TachyonRenderer())
            pipeline.remove_from_scene()
Пример #8
0
                           "Particle Identifier", "Particle Type",
                           "Position.X", "Position.Y", "Position.Z"
                       ],
                       multiple_frames=True)
pipeline.add_to_scene()
setDefaultColorsAndRadii(pipeline.source)

data = np.loadtxt("cube.z.txt")


def tempModifierFunction(frame, input, output):
    print("Finding pressure for frame %d: %f" % (frame, data[frame * 100][1]))
    output.attributes['pressure'] = data[frame * 100][1]


bonds = CreateBondsModifier(mode=CreateBondsModifier.Mode.Pairwise)
bonds.bonds_display.width = 0.3
bonds.set_pairwise_cutoff("H", "O2", 2.0)
pipeline.modifiers.append(bonds)
pipeline.modifiers.append(PythonScriptModifier(function=tempModifierFunction))

# Create an overlay.
overlay = TextLabelOverlay(text='P=[pressure] MPa',
                           alignment=QtCore.Qt.AlignHCenter
                           ^ QtCore.Qt.AlignBottom,
                           offset_x=-0.3,
                           offset_y=-0.01,
                           font_size=0.05,
                           text_color=(1, 1, 1))

# Attach overlay to the active viewport.