Пример #1
0
def Mods(Fracs, Beads, Denss):

    pre = 'results/snapshots/coordination_analysis/f_'

    for Frac in Fracs:

        f = int((1 - Frac) * 10 % 10)

        for Bead in Beads:

            #             os.makedirs('./'+str(pre)+str(f)+'/b_'+str(Bead))

            for Dens in Denss:

                data = import_file('./frac_' + str(Frac) + '/m_' + str(Bead) +
                                   '/d_' + str(Dens) + '/final_snapshot.xyz')

                co = ((Bead * 1000) / Dens)**(1 / 3)

                modifier = CoordinationAnalysisModifier(cutoff=co / 2,
                                                        partial=True,
                                                        number_of_bins=180)
                data.modifiers.append(modifier)

                export_file(
                    data,
                    str(pre) + str(f) + "/b_" + str(Bead) + "/d_" + str(Dens) +
                    ".txt", "txt/table")

    exit()
Пример #2
0
def vacancylabel_io(file_path, filename):
    orig_dir = os.getcwd()
    try:
        os.chdir(file_path)
    except:
        print('Couldn'
              't find that directory, check syntax (/mnt/d/UserName/...)')
        sys.exit(1)
    try:
        pipeline = import_file(filename)
    except:
        print('File not found (check the name and that you'
              're in the right directory)')
        sys.exit(1)
    wigmod = WignerSeitzAnalysisModifier(
        per_type_occupancies=True,
        affine_mapping=ReferenceConfigurationModifier.AffineMapping.ToReference
    )
    wigmod.reference = FileSource()
    try:
        wigmod.reference.load('FCCreference.lmp')
    except:
        print('FCCreference.lmp was not found!')
        sys.exit(1)
    pipeline.modifiers.append(wigmod)
    pipeline.modifiers.append(
        ComputePropertyModifier(output_property='Particle Type',
                                expressions='3'))
    # see custom modifier above
    pipeline.modifiers.append(modify)
    pipeline.modifiers.append(InvertSelectionModifier())
    pipeline.modifiers.append(DeleteSelectedModifier())
    # export a file with the vacancies only (type = 3)
    export_file(pipeline,
                filename.split('.')[0] + "vacancies.xyz",
                "xyz",
                columns=[
                    'Particle Identifier', 'Particle Type', 'Position.X',
                    'Position.Y', 'Position.Z'
                ],
                multiple_frames=True)
    # new pipeline to combine the vacancies with the original data (this will append the vacancies at the end of the Particle IDs and reassign new IDs accordingly)
    newpipeline = import_file(filename)
    mod = CombineDatasetsModifier()
    mod.source.load(filename.split('.')[0] + 'vacancies.xyz')
    newpipeline.modifiers.append(mod)
    # make a new file with the vacancies and all atoms included for visualization
    export_file(newpipeline,
                "new" + filename.split('.')[0] + ".xyz",
                "xyz",
                columns=[
                    'Particle Identifier', 'Particle Type', 'Position.X',
                    'Position.Y', 'Position.Z'
                ],
                multiple_frames=True)
    os.chdir(orig_dir)
Пример #3
0
def write_lammps_data(ftxt, atoms, **kwargs):
  # FAIL: use ase.io.write(ftxt, atoms, format='lammps-data', atom_style='charge')
  from ovito.io import export_file
  from ovito.pipeline import StaticSource, Pipeline
  from ovito.io.ase import ase_to_ovito
  atoms.set_initial_charges(atoms.get_initial_charges())
  dc = ase_to_ovito(atoms)
  #dc.particles.masses = np.ones(len(atoms))
  #dc.particles_.create_property('masses', data=atoms.get_masses())
  pl = Pipeline(source=StaticSource(data=dc))
  export_file(pl, ftxt, 'lammps/data', atom_style='charge')#**kwargs)
Пример #4
0
def Mods(Fracs, Beads, Denss, Inters):

    for Frac in Fracs:

        frac = int((1-Frac)*10%10)

        print(frac)
        print('')

        for Bead in Beads:

            print(Bead)
            print('')

            for Dens in Denss:
                print(Dens)
                print('')
                
                for Inter in Inters:
                    print(Inter)
                    print('')
        
                    File = f'centros_de_massas/{Inter}/f_{frac}-b_{Bead}-d_{Dens}.xyz'
                    path = f'centros_de_massas/{Inter}/rdfs/f-'

                    data = import_file(File)
                    
                    co = ((Bead*1000)/Dens)**(1/3)
                    
                    modifier = CoordinationAnalysisModifier(cutoff = co/2, number_of_bins = 60)
                    
                    data.modifiers.append(modifier)

                    export_file(data, path+str(frac)+"_b-"+str(Bead)+"_d-"+str(Dens)+".txt", "txt/table")
                    
                    print('Done. Next Inter')
                
                print('Done. Next Dens')

            print('Done. Next Bead')

        print('Done. Next Frac')
    
    print('')
    print('that\'s all, folks!')
            

    exit()
Пример #5
0
def write_lammps_dump(fout, fxyz, charge=False, columns=None):
  import os
  if os.path.isfile(fout):
    raise RuntimeError('%s exists' % fout)
  from ovito.io import import_file, export_file
  pl = import_file(fxyz)
  if columns is None:
    columns = ["Particle Identifier", "Particle Type",
      "Position.X", "Position.Y", "Position.Z"]
  if charge:
    cname = 'Charge'
    columns += [cname]
    def add_charge(frame, data):
      data.particles_.create_property(cname, data=data.particles['initial_charges'])
    pl.modifiers.append(add_charge)
  export_file(pl, fout, 'lammps/dump', columns=columns, multiple_frames=True)
Пример #6
0
def Mods(Fracs, Beads, Denss):

    pre = 'results/snapshots/coordination_analysis/f_'

    for Frac in Fracs:

        f = int((1-Frac)*10%10)

        for Bead in Beads:

            os.makedirs('./'+str(pre)+str(f)+'/b_'+str(Bead))

            for Dens in Denss:

                data = import_file('./frac_'+str(Frac)+'/m_'+str(Bead)+'/d_'+str(Dens)+'/final_snapshot.xyz')

                data.modifiers.append(modifier)

                export_file(data, str(pre)+str(f)+"/b_"+str(Bead)+"/d_"+str(Dens)+".txt", "txt/table")
    
    exit()
Пример #7
0
def to_lammps(trjfile: str, indices_per_atom: npt.NDArray[np.float64]) -> str:
    pipeline = import_file(trjfile, sort_particles=True)

    for frame, linde in enumerate(indices_per_atom):
        data = pipeline.compute(frame)
        data.particles_.create_property("lindemann", data=linde)
        export_file(
            data,
            f"lindemann_outputfile_X{frame}.dump",
            "lammps/dump",
            columns=[
                "Particle Identifier",
                "Particle Type",
                "Position.X",
                "Position.Y",
                "Position.Z",
                "lindemann",
            ],
            multiple_frames=True,
        )

    """
    This is section is weird and very hacky, I dont like it. Does someone have a idea how to do this in a better way?
    First I save the files with the ovito export_file, then I save them in a file, finally I remove the files... I know...
    """

    filenames = [f"lindemann_outputfile_X{frame}.dump" for frame in range(len(indices_per_atom))]

    file_name = "lindemann_per_atom.lammpstrj"
    with open(file_name, "w") as outfile:
        for fname in filenames:
            with open(fname) as infile:
                outfile.write(infile.read())
    for frame in range(len(indices_per_atom)):
        os.remove(f"lindemann_outputfile_X{frame}.dump")
    return "saved trajectory as lindemann_per_atom.lammpstrj"
Пример #8
0
import sys
if "ovito.modifiers.crystalanalysis" not in sys.modules: sys.exit()

from ovito.io import import_file, export_file
from ovito.data import SurfaceMesh
from ovito.modifiers import ConstructSurfaceModifier

# Load a particle set and construct the surface mesh:
pipeline = import_file("simulation.dump")
pipeline.modifiers.append(ConstructSurfaceModifier(radius=2.8))
mesh = pipeline.compute().expect(SurfaceMesh)

# Export the mesh to a VTK file for visualization with ParaView.
export_file(mesh, 'surface_mesh.vtk', 'vtk/trimesh')
Пример #9
0
import argparse
from ovito.io import export_file, import_file
from ovito.modifiers import CommonNeighborAnalysisModifier

parser = argparse.ArgumentParser()
parser.add_argument('--input_file', '-i', help='Input grain boundary struct file to produce cumulative energy.')
args = parser.parse_args()

#initialize node and import file
node = import_file(args.input_file)
cna = CommonNeighborAnalysisModifier()
node.modifiers.append(cna)
node.compute()
export_file(node, "output.xyz", "xyz", columns = ["Particle Identifier", "Particle Type",
                                                                                                                                                                                                        "Position.X", "Position.Y", "Position.Z",
                                                  "Potential Energy", "Structure Type"])
from ovito.io import import_file, export_file
from ovito.modifiers import DislocationAnalysisModifier
from ovito.data import DislocationNetwork

pipeline = import_file("input/simulation.dump")

# Extract dislocation lines from a crystal with diamond structure:
modifier = DislocationAnalysisModifier()
modifier.input_crystal_structure = DislocationAnalysisModifier.Lattice.CubicDiamond
pipeline.modifiers.append(modifier)
data = pipeline.compute()

total_line_length = data.attributes['DislocationAnalysis.total_line_length']
cell_volume = data.attributes['DislocationAnalysis.cell_volume']
print("Dislocation density: %f" % (total_line_length / cell_volume))

# Print list of dislocation lines:
print("Found %i dislocation segments" % len(data.dislocations.segments))
for segment in data.dislocations.segments:
    print("Segment %i: length=%f, Burgers vector=%s" % (segment.id, segment.length, segment.true_burgers_vector))
    print(segment.points)

# Export dislocation lines to a CA file:
export_file(pipeline, "output/dislocations.ca", "ca")

# Or export dislocations to a ParaView VTK file:
export_file(pipeline, "output/dislocations.vtk", "vtk/disloc”)
Пример #11
0
from ovito.pipeline import StaticSource, Pipeline
from ovito.data import SimulationCell
from ovito.modifiers import CreateBondsModifier
from ovito.io import export_file

# Create a new Pipeline with a StaticSource as data source:
pipeline = Pipeline(source=StaticSource())

# Insert a new SimulationCell object into the StaticSource:
cell = SimulationCell(pbc=(False, False, False))
with cell.modify() as matrix:
    matrix[:, 0] = (4, 0, 0)
    matrix[:, 1] = (0, 2, 0)
    matrix[:, 2] = (0, 0, 2)
pipeline.source.objects.append(cell)

# Insert two particles into the StaticSource:
xyz = [[0, 0, 0], [2, 0, 0]]
pipeline.source.particle_properties.create('Position', data=xyz)

# Apply a modifier:
pipeline.modifiers.append(CreateBondsModifier(cutoff=3.0))

# Write pipeline results to an output file:
export_file(pipeline, 'output.data', 'lammps/data', atom_style='bond')
            # Compute the structure factor and find the height of the first peak
            sf = np.zeros(k_len)
            i = 0
            for k in k_list:
                sin_sum = np.sum(np.sin(k * x))
                cos_sum = np.sum(np.cos(k * x))
                sf[i] = (np.power(sin_sum, 2) + np.power(cos_sum, 2)) / N
                i = i + 1

            av_sf = av_sf + sf / k_len

        peak_h = av_sf[np.argmax(av_sf[60:120]) + 60]

        np.savetxt(output_file_av_sf, [av_sf])
        output_file_shear.write(shear_rate + " ")
        np.savetxt(output_file_peak, [peak_h])
        export_file(node,
                    output_filepath + '/config_check_' + str(shear_rate) +
                    '.dump',
                    'lammps/dump',
                    columns=["Position.X", "Position.Y", "Position.Z"],
                    multiple_frames=False)

    else:
        print("File: " + input_file_dir + str(shear_rate) + input_file +
              " not found")

output_file_shear.close()
output_file_av_sf.close()
output_file_peak.close()
Пример #13
0
# Calculate per-particle displacements with respect to initial simulation frame:
dmod = CalculateDisplacementsModifier()
dmod.reference.load("C:/work/test")
node.modifiers.append(dmod)


# Define the custom modifier function:
def modify(frame, input, output):

    # Access the per-particle displacement magnitudes computed by an existing
    # Displacement Vectors modifier that precedes this custom modifier in the
    # data pipeline:
    displacement_magnitudes = input.particle_properties.displacement_magnitude.array

    # Compute MSD:
    msd = numpy.sum(displacement_magnitudes**2) / len(displacement_magnitudes)

    # Output MSD value as a global attribute:
    output.attributes["MSD"] = msd


# Insert custom modifier into the data pipeline.
node.modifiers.append(PythonScriptModifier(function=modify))

# Export calculated MSD value to a text file and let OVITO's data pipeline do the rest:
export_file(node,
            "C:\work\msd_test.txt",
            format="txt",
            columns=["Timestep", "MSD"],
            multiple_frames=True)
Пример #14
0
# Create bonds.
pipeline.modifiers.append(CreateBondsModifier(cutoff=3.2))
# Identifying the Structure type and dislocations
pipeline.modifiers.append(DislocationAnalysisModifier())
# Used for detecting the shell of the simulation box
pipeline.modifiers.append(CentroSymmetryModifier())
# Get the type of stacking fault.
pipeline.modifiers.append(pair_analysis)

data = pipeline.compute()
output_name = 'pair.' + input_name

# Save the sanpshot with the Fault Type.
export_file(data, output_name, "lammps/dump",
            columns=["Particle Identifier", "Particle Type", "Structure Type",
                     "Position.X", "Position.Y", "Position.Z", 'Pair', 'Fault Type'])

# Delete all of the bulk particles but leave the outer surface.
pipeline.modifiers.append(ExpressionSelectionModifier(expression='FaultType == 0  && Centrosymmetry < 9'))
pipeline.modifiers.append(DeleteSelectedModifier())

# increase the transparency of the outer surface particles.
pipeline.modifiers.append(ExpressionSelectionModifier(expression='Centrosymmetry > 9 && Position.X >15'))
transparency = 0.9
pipeline.modifiers.append(ComputePropertyModifier(
    output_property='Transparency',
    expressions=[str(transparency)],
    only_selected=True))

dark = [0.6, 0.3]
Пример #15
0
from ovito.io import import_file, export_file
from ovito.modifiers import CombineParticleSetsModifier

# Load a first set of particles.
pipeline = import_file('first_file.dump')

# Insert the particles from a second file into the dataset.
modifier = CombineParticleSetsModifier()
modifier.source.load('second_file.dump')
pipeline.modifiers.append(modifier)

# Export combined dataset to a new file.
export_file(pipeline,
            'output.dump',
            'lammps/dump',
            columns=['Position.X', 'Position.Y', 'Position.Z'])
Пример #16
0
import sys
if "ovito.modifiers.crystalanalysis" not in sys.modules: sys.exit()

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

pipeline = import_file("simulation.dump")

# Extract dislocation lines from a crystal with diamond structure:
modifier = DislocationAnalysisModifier()
modifier.input_crystal_structure = DislocationAnalysisModifier.Lattice.CubicDiamond
pipeline.modifiers.append(modifier)
data = pipeline.compute()

total_line_length = data.attributes['DislocationAnalysis.total_line_length']
cell_volume = data.attributes['DislocationAnalysis.cell_volume']
print("Dislocation density: %f" % (total_line_length / cell_volume))

# Print list of dislocation lines:
network = data.dislocations
print("Found %i dislocation segments" % len(network.segments))
for segment in network.segments:
    print("Segment %i: length=%f, Burgers vector=%s" % (segment.id, segment.length, segment.true_burgers_vector))
    print(segment.points)

# Export dislocation lines to a CA file:
export_file(pipeline, "dislocations.ca", "ca")

# Or export dislocations to a ParaView file:
export_file(pipeline, "dislocations.vtk", "vtk/disloc")
Пример #17
0
    disp_awin = uf.calc_win_disps(num_atoms, ndump_avgw, A_window,
                                  input_dump_wc, pipeline)
    disp_bwin = uf.calc_win_disps(num_atoms, ndump_avgw, B_window,
                                  input_dump_wc, pipeline)

    avg_pos = 0 * pos_pbd
    tot_ndw = 2 * ndump_avgw + 1
    for ct1 in range(3):
        avg_disp = (
            (np.sum(disp_awin[ct1], axis=1) + np.sum(disp_bwin[ct1], axis=1)) /
            (tot_ndw))
        avg_pos[:, ct1] = (pos_pbd[:, ct1] - avg_disp)

    data.particles.create_property('Position', data=avg_pos)

    ##########################
    # dumping the adjusted files
    ###########################
    dname = avg_xcoor_dir + avg_fwc + str(tstep) + '.out'
    oio.export_file(data,
                    dname,
                    format="lammps_dump",
                    columns=[
                        "Particle Identifier", "Particle Type", "Position.X",
                        "Position.Y", "Position.Z", "c_csym"
                    ],
                    frame=tstep)
    pipeline = []

sys.path.remove(dir_path)
Пример #18
0
                                 output_property="Radius",
                                 only_selected=True))
node.modifiers.append(
    mods.AssignColorModifier(color=(204 / 255, 255 / 255, 229 / 255)))
#node.modifiers.append(mods.ComputePropertyModifier(expressions=[monomer_bead_radius],output_property="Transparency",only_selected=False))
monomer_expression = " || ".join([
    "MoleculeIdentifier == {}".format(mol) for mol in args.mon_list.split(",")
])
print(monomer_expression)
node.modifiers.append(
    mods.SelectExpressionModifier(expression=monomer_expression))
#node.modifiers.append(mods.ComputePropertyModifier(expressions=[transparency],output_property="Transparency",only_selected=True))
#node.modifiers.append(mods.InvertSelectionModifier())
node.modifiers.append(mods.DeleteSelectedParticlesModifier())

io.export_file(node, 'output.data', format="lammps_data", atom_style="angle")

vp = vis.Viewport()
vp.type = vis.Viewport.Type.PERSPECTIVE
vp.camera_pos = (-20, 20, -20)
vp.camera_dir = (3, -2, 3)
vp.fov = math.radians(60.0)

settings = vis.RenderSettings()
settings.renderer = vis.TachyonRenderer()
settings.renderer.shadows = True
settings.filename = args.dest_folder + '/' + args.imagename
settings.size = (800, 600)

node.add_to_scene()
vp.render(settings)
Пример #19
0
#!/usr/bin/env python3
import sys
from ovito.io import import_file, export_file

if len(sys.argv) not in [2, 3] or sys.argv[1] == "-h":
    print("Syntax: lammps_last_frame.py lammps_dump [output]")
    sys.exit(1)

try:
    output = sys.argv[2]
except IndexError:
    output = "last_frame.xyz"

data = import_file(sys.argv[1])
last = data.compute(data.source.num_frames)
export_file(
    last,
    output,
    "xyz",
    columns=["Particle Type", "Position.X", "Position.Y", "Position.Z"],
)
Пример #20
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()
Пример #21
0
# Calculate per-particle displacements with respect to initial simulation frame:
dmod = CalculateDisplacementsModifier()
dmod.reference.load("simulation.dump")
node.modifiers.append(dmod)


# Define the custom modifier function:
def modify(frame, input, output):

    # Access the per-particle displacement magnitudes computed by an existing
    # Displacement Vectors modifier that precedes this custom modifier in the
    # data pipeline:
    displacement_magnitudes = input.particle_properties.displacement_magnitude.array

    # Compute MSD:
    msd = numpy.sum(displacement_magnitudes**2) / len(displacement_magnitudes)

    # Output MSD value as a global attribute:
    output.attributes["MSD"] = msd


# Insert custom modifier into the data pipeline.
node.modifiers.append(PythonScriptModifier(function=modify))

# Export calculated MSD value to a text file and let OVITO's data pipeline do the rest:
export_file(node,
            "msd_data.txt",
            format="txt",
            columns=["Timestep", "MSD"],
            multiple_frames=True)
Пример #22
0
import sys
#from ovito.vis import Viewport, TachyonRenderer
strFilename = str(
    sys.argv[1]
)  #assumes "ovitos PMStructure.py strFilename  fltRMSD "command line
fltRMSD = float(sys.argv[2])
pipeline = io.import_file(strFilename, multiple_frames=True)
n = pipeline.source.num_frames
pipeline.add_to_scene()
pipeline.modifiers.append(
    om.ElasticStrainModifier(calculate_strain_tensors=False,
                             lattice_constant=4.05))
pipeline.modifiers.append(
    om.PolyhedralTemplateMatchingModifier(rmsd_cutoff=fltRMSD,
                                          output_orientation=False)
)  #this needs to be last otherwise the structure types are not updated
pipeline.compute()
#vp = Viewport(type = Viewport.Type.Top)
#vp.zoom_all()
#vp.render_image(filename=strFilename + '.png', size=(320, 240),frame=n-1,  renderer=TachyonRenderer())
#print(pipeline.output) #debug information
io.export_file(pipeline,
               strFilename + 'PM',
               "lammps_dump",
               frame=n,
               columns=[
                   'Particle Identifier', 'Position.X', 'Position.Y',
                   'Position.Z', 'Velocity.X', 'Velocity.Y', 'Velocity.Z',
                   'c_pe1', 'c_v[1]', 'Structure Type', 'Volumetric Strain'
               ])
Пример #23
0
from ovito.io import import_file, export_file
from ovito.modifiers import DislocationAnalysisModifier

node = import_file("simulation.dump")

# Extract dislocation lines from a crystal with diamond structure:
modifier = DislocationAnalysisModifier()
modifier.input_crystal_structure = DislocationAnalysisModifier.Lattice.CubicDiamond
node.modifiers.append(modifier)
node.compute()

total_line_length = node.output.attributes[
    'DislocationAnalysis.total_line_length']
print("Dislocation density: %f" %
      (total_line_length / node.output.cell.volume))

# Print list of dislocation lines:
network = node.output.dislocations
print("Found %i dislocation segments" % len(network.segments))
for segment in network.segments:
    print("Segment %i: length=%f, Burgers vector=%s" %
          (segment.id, segment.length, segment.true_burgers_vector))
    print(segment.points)

# Export dislocation lines to a CA file:
export_file(node, "dislocations.ca", "ca")
Пример #24
0
    newtyp, newq, newpos = create_tms_molecule_planar(rp, rho / rhoNorm)
    s = 13 * iTMS + identif_array.size
    for j in range(newtyp.size):
        new_pos_prop.marray[s,:] = newpos[j,:]
        new_type_prop.marray[s] = newtyp[j]
        new_identifier_prop.marray[s] = s + 1
        new_charge_prop.marray[s] = newq[j]
        s = s + 1

new_data = DataCollection()
new_data.add(new_pos_prop)
new_data.add(new_identifier_prop)
new_data.add(new_type_prop)
new_data.add(new_charge_prop)
new_data.add(node.source.cell)
if "Timestep" in node.source.attributes:
    new_data.attributes['Timestep'] = node.source.attributes["Timestep"]

new_node = ovito.ObjectNode()
new_node.source = new_data
new_node.compute()
#new_node.add_to_scene()

print("... new number of particles  %d"%(new_node.output.particle_properties['Particle Type'].size))
print(new_node.output.particle_properties["Particle Type"].array)

export_file(new_node, sys.argv[3], "lammps_dump",
            columns=["Particle Identifier", "Particle Type", "Charge" ,"Position.X", "Position.Y", "Position.Z"])
print("... done writing LAMMPS data file %s"%(args.outfname))
Пример #25
0
#!/usr/bin/env python3

import sys
if not 2 <= len(sys.argv) <= 3:
    sys.exit("Uses Ovito to read in a datafile and write an xyz.\n"
             "Atom type labels must be present in the Masses section\n"
             "i.e. 7 12.011 # C3\n"
             "Syntax: datafile_to_wrapped_xyz.py input [output (optional)]")
from ovito.io import import_file, export_file
from ovito.modifiers import UnwrapTrajectoriesModifier

traj = sys.argv[1]
if len(sys.argv) == 2:
    output = traj.rsplit('.')[0] + '.wrapped.xyz'
else:
    output = sys.argv[2]

pipeline = import_file(traj, atom_style='full')
export_file(
    pipeline,
    output,
    'xyz',
    columns=["Particle Type", "Position.X", "Position.Y", "Position.Z"])
Пример #26
0
from ovito.io import import_file, export_file
from ovito.modifiers import (CoordinationNumberModifier,
                             FreezePropertyModifier,
                             ExpressionSelectionModifier)

# Load a input simulation sequence.
pl = import_file("simulation.*.dump")

# Add modifier for computing the coordination numbers of particles.
pl.modifiers.append(CoordinationNumberModifier(cutoff=2.9))

# Save the initial coordination numbers from frame 0 under a new name.
modifier = FreezePropertyModifier(source_property='Coordination',
                                  destination_property='Coord0',
                                  freeze_at=0)
pl.modifiers.append(modifier)

# Select all particles whose coordination number has changed since frame 0
# by comapring the dynamically computed coordination numbers with the frozen ones.
pl.modifiers.append(
    ExpressionSelectionModifier(expression='Coordination != Coord0'))

# Write out number of particles exhibiting a change in coordination number.
export_file(pl,
            'output.txt',
            'txt',
            columns=['Timestep', 'SelectExpression.num_selected'],
            multiple_frames=True)
Пример #27
0
def extractFrames(
        topology_file='datafile.lammps',  # lammps data file
        trajectory_file='trajectory.nc',  # netcdf trajectory
        frames=None,  # list of frame numbers
        outfile_name=None,  # list of outfiles, same length as frames
        outfile_pattern='frame_{:08d}.lammps',
        atom_style='full'):
    """Extracts selected or all frames from a NetCDF trajectory.

    Parameters
    ----------
    topology_file : str, optional
        LAMMPS data file, per default atom style 'full'
    trajectory_file: str, optional
        Trajectory file (atom positions) in NetCDF format
    frames: :obj:`list` of :obj:`int`, optional
        Arbitrary selection of frames. Per default, all frames extracted.
    outfile_name :obj:`dict` of :obj:`int` : :obj:`str`, optional
        Dictionary assigning output file name for every selected frame.
    outfile_pattern: str, optional
        If `outfile_name` not given, output file names are constructed from
        this pattern and frame number. Must conatin some {:d} integer
        placeholder, i.e. 'frame_{:08d}.lammps'
    atom_style: str, optional
        LAMMPS atom sytle as understood by ovitos
    """

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

    logger = logging.getLogger('netcdf2data.extractFrames')
    logger.info("Reading topology from '{:s}'".format(topology_file))
    # Load static topology data from a LAMMPS data file.
    node = import_file(topology_file, atom_style=atom_style)

    logger.info("Reading trajectory from '{:s}'".format(trajectory_file))
    # Load atom trajectories from separate LAMMPS dump file.
    traj_mod = LoadTrajectoryModifier()
    traj_mod.source.load(trajectory_file, multiple_frames=True)

    # Insert modifier into modification pipeline.
    node.modifiers.append(traj_mod)

    if frames is None: frames = range(traj_mod.source.num_frames)
    if outfile_name is None:
        outfile_name = {
            frame: outfile_pattern.format(frame)
            for frame in frames
        }

    for frame in frames:
        try:
            logger.info("Storing frame {:08d} to '{:s}'".format(
                frame, outfile_name[frame]))
        except IndexError:
            logger.error(
                "No outfile name specified for frame {:d}!".format(frame))
            pass  # out of range

        export_file(node,
                    outfile_name[frame],
                    'lammps_data',
                    atom_style=atom_style,
                    frame=frame)

    return