def test_aiida_roundtrip(self): cell = np.array([[4., 1., 0.], [0., 4., 0.], [0., 0., 4.]]) struc = StructureData(cell=cell) struc.append_atom(symbols='Ba', position=(0, 0, 0)) struc.append_atom(symbols='Ti', position=(1, 2, 3)) struc.append_atom(symbols='O', position=(-1, -2, -4)) struc.append_kind(Kind(name='Ba2', symbols="Ba", mass=100.)) struc.append_site(Site(kind_name='Ba2', position=[3, 2, 1])) struc.append_kind( Kind(name='Test', symbols=["Ba", "Ti"], weights=[0.2, 0.4], mass=120.)) struc.append_site(Site(kind_name='Test', position=[3, 5, 1])) struc_tuple, kind_info, kinds = seekpath.aiidawrappers._aiida_to_tuple( struc) roundtrip_struc = seekpath.aiidawrappers._tuple_to_aiida( struc_tuple, kind_info, kinds) self.assertAlmostEqual( np.sum( np.abs(np.array(struc.cell) - np.array(roundtrip_struc.cell))), 0.) self.assertEqual(struc.get_attr('kinds'), roundtrip_struc.get_attr('kinds')) self.assertEqual([_.kind_name for _ in struc.sites], [_.kind_name for _ in roundtrip_struc.sites]) self.assertEqual( np.sum( np.abs( np.array([_.position for _ in struc.sites]) - np.array([_.position for _ in roundtrip_struc.sites]))), 0.)
def test_from_aiida(self): cell = np.array([[4., 1., 0.], [0., 4., 0.], [0., 0., 4.]]) struc = StructureData(cell=cell) struc.append_atom(symbols='Ba', position=(0, 0, 0)) struc.append_atom(symbols='Ti', position=(1, 2, 3)) struc.append_atom(symbols='O', position=(-1, -2, -4)) struc.append_kind(Kind(name='Ba2', symbols="Ba", mass=100.)) struc.append_site(Site(kind_name='Ba2', position=[3, 2, 1])) struc.append_kind( Kind(name='Test', symbols=["Ba", "Ti"], weights=[0.2, 0.4], mass=120.)) struc.append_site(Site(kind_name='Test', position=[3, 5, 1])) struc_tuple, kind_info, kinds = seekpath.aiidawrappers._aiida_to_tuple( struc) abscoords = np.array([_.position for _ in struc.sites]) struc_relpos = np.dot(np.linalg.inv(cell.T), abscoords.T).T self.assertAlmostEqual( np.sum(np.abs(np.array(struc.cell) - np.array(struc_tuple[0]))), 0.) self.assertAlmostEqual( np.sum(np.abs(np.array(struc_tuple[1]) - struc_relpos)), 0.) expected_kind_info = [ kind_info[site.kind_name] for site in struc.sites ] self.assertEqual(struc_tuple[2], expected_kind_info)
def get_step_structure(self, index, custom_kinds=None): """ Return an AiiDA :py:class:`aiida.orm.data.structure.StructureData` node (not stored yet!) with the coordinates of the given step, identified by its index. If you know only the step value, use the :py:meth:`.get_index_from_stepid` method to get the corresponding index. .. note:: The periodic boundary conditions are always set to True. .. versionadded:: 0.7 Renamed from step_to_structure :param index: The index of the step that you want to retrieve, from 0 to ``self.numsteps- 1``. :param custom_kinds: (Optional) If passed must be a list of :py:class:`aiida.orm.data.structure.Kind` objects. There must be one kind object for each different string in the ``symbols`` array, with ``kind.name`` set to this string. If this parameter is omitted, the automatic kind generation of AiiDA :py:class:`aiida.orm.data.structure.StructureData` nodes is used, meaning that the strings in the ``symbols`` array must be valid chemical symbols. """ from aiida.orm.data.structure import StructureData, Kind, Site # ignore step, time, and velocities _, _, cell, symbols, positions, _ = self.get_step_data(index) if custom_kinds is not None: kind_names = [] for k in custom_kinds: if not isinstance(k, Kind): raise TypeError( "Each element of the custom_kinds list must " "be a aiida.orm.data.structure.Kind object") kind_names.append(k.name) if len(kind_names) != len(set(kind_names)): raise ValueError("Multiple kinds with the same name passed " "as custom_kinds") if set(kind_names) != set(symbols): raise ValueError("If you pass custom_kinds, you have to " "pass one Kind object for each symbol " "that is present in the trajectory. You " "passed {}, but the symbols are {}".format( sorted(kind_names), sorted(symbols))) struc = StructureData(cell=cell) if custom_kinds is not None: for k in custom_kinds: struc.append_kind(k) for s, p in zip(symbols, positions): struc.append_site(Site(kind_name=s, position=p)) else: for s, p in zip(symbols, positions): # Automatic species generation struc.append_atom(symbols=s, position=p) return struc
def sub_create_bands_data(cls, user=None): from aiida.orm.data.array.kpoints import KpointsData from aiida.orm import JobCalculation from aiida.orm.data.structure import StructureData from aiida.common.links import LinkType from aiida.orm.data.array.bands import BandsData import numpy s = StructureData(cell=((2., 0., 0.), (0., 2., 0.), (0., 0., 2.))) s.append_atom(position=(0., 0., 0.), symbols=['Ba', 'Ti'], weights=(1., 0.), name='mytype') if user is not None: s.dbnode.user = user._dbuser s.store() c = JobCalculation(computer=cls.computer, resources={ 'num_machines': 1, 'num_mpiprocs_per_machine': 1 }) if user is not None: c.dbnode.user = user._dbuser c.store() c.add_link_from(s, "S1", LinkType.INPUT) c._set_state(calc_states.RETRIEVING) # define a cell alat = 4. cell = numpy.array([ [alat, 0., 0.], [0., alat, 0.], [0., 0., alat], ]) k = KpointsData() k.set_cell(cell) k.set_kpoints_path() if user is not None: k.dbnode.user = user._dbuser k.store() b = BandsData() b.set_kpointsdata(k) input_bands = numpy.array( [numpy.ones(4) * i for i in range(k.get_kpoints().shape[0])]) b.set_bands(input_bands, units='eV') if user is not None: b.dbnode.user = user._dbuser b.store() b.add_link_from(c, link_type=LinkType.CREATE) return b
def scaled_structure(structure, scale): new_structure = StructureData(cell=numpy.array(structure.cell)*float(scale)) for site in structure.sites: new_structure.append_atom(position=numpy.array(site.position)*float(scale), \ symbols=structure.get_kind(site.kind_name).symbol,\ name=site.kind_name) new_structure.label = 'auxiliary structure for stress tensor' new_structure.description = "created from the original structure with PK=%i, "\ "lattice constant scaling: %f"%(structure.pk, float(scale)) return new_structure
def scaled_structure(structure, scale): new_structure = StructureData(cell=np.array(structure.cell)*scale) for site in structure.sites: new_structure.append_atom(position=np.array(site.position)*scale, \ symbols=structure.get_kind(site.kind_name).symbol,\ name=site.kind_name) new_structure.label = 'created inside stress tensor run' new_structure.description = "auxiliary structure for stress tensor "\ "created from the original structure with PK=%i, "\ "lattice constant scaling: %f"%(structure.pk, scale) return new_structure
def get_structure(self): """ Returns the structure used to calculate the NAC parameters :return: StructureData """ structure = StructureData(cell=self.get_attr('cell')) symbols = self.get_attr('symbols') positions = self.get_attr('positions') for symbol, position in zip(symbols, positions): structure.append_atom(position=position, symbols=symbol) return structure
def create_supercells_with_displacements_using_phonopy(structure, phonopy_input): """ Create the supercells with the displacements to use the finite displacements methodology to calculate the force constants :param structure: Aiida StructureData Object :param phonopy_input: Aiida Parametersdata object containing a dictionary with the data needed to run phonopy: supercells matrix, primitive matrix and displacement distance. :return: dictionary of Aiida StructureData Objects containing the cells with displacements """ from phonopy.structure.atoms import Atoms as PhonopyAtoms from phonopy import Phonopy import numpy as np # Generate phonopy phonon object bulk = PhonopyAtoms(symbols=[site.kind_name for site in structure.sites], positions=[site.position for site in structure.sites], cell=structure.cell) phonopy_input = phonopy_input.get_dict() phonon = Phonopy(bulk, phonopy_input['supercell'], primitive_matrix=phonopy_input['primitive']) phonon.generate_displacements(distance=phonopy_input['distance']) cells_with_disp = phonon.get_supercells_with_displacements() # Transform cells to StructureData and set them ready to return data_sets = phonon.get_displacement_dataset() data_sets_object = ArrayData() for i, first_atoms in enumerate(data_sets['first_atoms']): data_sets_array = np.array([ first_atoms['direction'], first_atoms['number'], first_atoms['displacement'] ]) data_sets_object.set_array('data_sets_{}'.format(i), data_sets_array) disp_cells = {'data_sets': data_sets_object} for i, phonopy_supercell in enumerate(cells_with_disp): supercell = StructureData(cell=phonopy_supercell.get_cell()) for symbol, position in zip(phonopy_supercell.get_chemical_symbols(), phonopy_supercell.get_positions()): supercell.append_atom(position=position, symbols=symbol) disp_cells["structure_{}".format(i)] = supercell return disp_cells
def get_supercell(structure, supercell_shape): import itertools symbols = np.array([site.kind_name for site in structure.sites]) positions = np.array([site.position for site in structure.sites]) cell = np.array(structure.cell) supercell_shape = np.array(supercell_shape.dict.shape) supercell_array = np.dot(cell, np.diag(supercell_shape)) supercell = StructureData(cell=supercell_array) for k in range(positions.shape[0]): for r in itertools.product(*[range(i) for i in supercell_shape[::-1]]): position = positions[k, :] + np.dot(np.array(r[::-1]), cell) symbol = symbols[k] supercell.append_atom(position=position, symbols=symbol) return supercell
def get_Lagrange_distorted_structure(structure_id, M_Lagrange_eps): import numpy as np s0 = load_node(structure_id) one = np.identity(3) deform = (np.dot(M_Lagrange_eps.T, M_Lagrange_eps) - one) / 2. #distorted_cell = np.dot((deform + one) , s0.cell) distorted_cell = np.dot(s0.cell, (deform + one)) s = StructureData(cell=distorted_cell) for site in s0.sites: kind_name = site.kind_name frac_coor = np.squeeze(np.asarray(list(np.matrix(s0.cell).T.I * np.matrix(site.position).T))) distorted_position = np.squeeze(np.asarray(list(np.matrix(s.cell).T * np.matrix(frac_coor).T))) s.append_atom(position=distorted_position, symbols=kind_name) s.store() return s
def create_structure_data(): from aiida.orm.data.structure import StructureData, Site, Kind from aiida.orm.group import Group alat = 4. # angstrom cell = [ [ alat, 0., 0., ], [ 0., alat, 0., ], [ 0., 0., alat, ], ] # BaTiO3 cubic structure struc = StructureData(cell=cell) struc.append_atom(position=(0., 0., 0.), symbols='Ba') struc.append_atom(position=(alat / 2., alat / 2., alat / 2.), symbols='Ti') struc.append_atom(position=(alat / 2., alat / 2., 0.), symbols='O') struc.append_atom(position=(alat / 2., 0., alat / 2.), symbols='O') struc.append_atom(position=(0., alat / 2., alat / 2.), symbols='O') struc.store() # Create 2 groups and add the data to one of them g_ne = Group(name='non_empty_group') g_ne.store() g_ne.add_nodes(struc) g_e = Group(name='empty_group') g_e.store() return { TestVerdiDataListable.NODE_ID_STR: struc.id, TestVerdiDataListable.NON_EMPTY_GROUP_ID_STR: g_ne.id, TestVerdiDataListable.EMPTY_GROUP_ID_STR: g_e.id }
def test_get_structuredata(self): """Test the get_structuredata method of PwInputFile""" # Create a reference StructureData object for the structure contained # in all the input files. ref_structure = StructureData() ref_structure.set_cell( ((2.456, 0., 0.), (-1.228, 2.12695, 0.), (0., 0., 6.69604))) ref_structure.append_atom(name='C', symbols='C', position=(0., 0., 0.), mass=12.) ref_structure.append_atom(name='C', symbols='C', position=(0., 1.41797, 0.), mass=12.) ref_structure.append_atom(name='C', symbols='C', position=(0., 0., 3.34802), mass=12.) ref_structure.append_atom(name='C', symbols='C', position=(1.228, 0.70899, 3.34802), mass=12.) # Check each input file for agreement with reference values. for input_file in INPUT_FILES: # Parse the input file and get the structuredata. pwinputfile = pwinputparser.PwInputFile(input_file) structure = pwinputfile.get_structuredata() # Check the name and the positions of each Kind. for ref_site, site in zip(ref_structure.sites, structure.sites): self.assertEqual(site.kind_name, ref_site.kind_name) for ref_q, q in zip(ref_site.position, site.position): self.assertAlmostEqual(ref_q, q, 4) # Check the cell. for ref_row, row in zip(ref_structure.cell, structure.cell): for ref_q, q in zip(ref_row, row): self.assertAlmostEqual(ref_q, q, 4) # Check the mass of each Kind. for ref_kind, kind in zip(ref_structure.kinds, structure.kinds): self.assertEqual(ref_kind.mass, kind.mass)
def create_structure_data(cls, cmd_to_nodeid_map, cmd_to_nodeid_map_for_groups, cmd_to_nodeid_map_for_nuser, group, new_user): from aiida.orm.data.structure import StructureData from aiida.cmdline.commands.data import _Structure s1 = StructureData(cell=((2., 0., 0.), (0., 2., 0.), (0., 0., 2.))) s1.append_atom(position=(0., 0., 0.), symbols=['Ba', 'Ti'], weights=(1., 0.), name='mytype') s1.store() s2 = StructureData(cell=((2., 0., 0.), (0., 2., 0.), (0., 0., 2.))) s2.append_atom(position=(0., 0., 0.), symbols=['Ba', 'Ti'], weights=(1., 0.), name='mytype') s2.store() # Keep track of the created objects cmd_to_nodeid_map[_Structure] = [s1.id, s2.id] # Add the second Kpoint & Bands data to the group group.add_nodes([s2]) # Keep track of the id of the node that you added to the group cmd_to_nodeid_map_for_groups[_Structure] = s2.id # Create a StructureData node belonging to another user s3 = StructureData(cell=((2., 0., 0.), (0., 2., 0.), (0., 0., 2.))) s3.append_atom(position=(0., 0., 0.), symbols=['Ba', 'Ti'], weights=(1., 0.), name='mytype') s3.dbnode.user = new_user._dbuser s3.store() # Put it is to the right map cmd_to_nodeid_map_for_nuser[_Structure] = [s3.id]
def execute(args): """ The main execution of the script, which will run some preliminary checks on the command line arguments before passing them to the workchain and running it """ try: code = Code.get_from_string(args.codename) except NotExistent as exception: print "Execution failed: could not retrieve the code '{}'".format( args.codename) print "Exception report: {}".format(exception) return try: vibra_code = Code.get_from_string(args.vibra_codename) except NotExistent as exception: print "Execution failed: could not retrieve the code '{}'".format( args.stm_codename) print "Exception report: {}".format(exception) return protocol = Str(args.protocol) # Structure. Bulk silicon SuperCell_1 = 1 SuperCell_2 = 1 SuperCell_3 = 1 scnumbers = np.array([SuperCell_1, SuperCell_2, SuperCell_3]) scarray = ArrayData() scarray.set_array('sca', scnumbers) alat = 5.43 # Angstrom. Not passed to the fdf file (only for internal use) cell = [[ 0., alat / 2, alat / 2, ], [ alat / 2, 0., alat / 2, ], [ alat / 2, alat / 2, 0., ]] pf = alat * 0.125 na = 2 x0 = [[pf, pf, pf], [-pf, -pf, -pf]] s1 = StructureData(cell=cell) for i in range(na): s1.append_atom(position=(x0[i][0], x0[i][1], x0[i][2]), symbols=['Si']) bandskpoints = KpointsData() kpp = [(1, 1., 1., 1.), (15, 0., 0.5, 0.5), (25, 0., 0., 0.), (20, 0.5, 0.5, 0.5), (20, 0., 0.5, 0.5), (15, 0.25, 0.5, 0.75), (20, 0.5, 0.5, 0.5)] lpp = [[0, '\Gamma'], [1, 'X'], [2, '\Gamma'], [3, 'L'], [4, 'X'], [5, 'W'], [6, 'L']] bandskpoints.set_cell(s1.cell, s1.pbc) bandskpoints.set_kpoints(kpp, labels=lpp) if args.structure > 0: structure = load_node(args.structure) else: structure = s1 run(SiestaVibraWorkChain, code=code, vibra_code=vibra_code, scarray=scarray, structure=structure, protocol=protocol, bandskpoints=bandskpoints)
cell = [[3.1900000, 0.0000000, 0.0000000], [-1.5950000, 2.7626210, 0.0000000], [0.0000000, 0.0000000, 5.1890000]] scaled_positions = [(0.6666669, 0.3333334, 0.0000000), (0.3333331, 0.6666663, 0.5000000), (0.6666669, 0.3333334, 0.3750000), (0.3333331, 0.6666663, 0.8750000)] symbols = ['Ga', 'Ga', 'N', 'N'] positions = np.dot(scaled_positions, cell) structure = StructureData(cell=cell) for i, scaled_position in enumerate(scaled_positions): structure.append_atom(position=np.dot(scaled_position, cell).tolist(), symbols=symbols[i]) # Machine machine_dict = { 'resources': { 'num_machines': 1, 'parallel_env': 'mpi*', 'tot_num_mpiprocs': 16 }, 'max_wallclock_seconds': 3600 * 10, } # PHONOPY settings ph_settings = ParameterData( dict={ 'supercell': [[3, 0, 0], [0, 3, 0], [0, 0, 3]],
def parse_with_retrieved(self, retrieved): """ Parses the datafolder, stores results. """ # suppose at the start that the job is successful successful = True # select the folder object # Check that the retrieved folder is there try: out_folder = retrieved[self._calc._get_linkname_retrieved()] except KeyError: self.logger.error("No retrieved folder found") return False, () # check what is inside the folder list_of_files = out_folder.get_folder_list() # OUTPUT file should exist if not self._calc._OUTPUT_FILE_NAME in list_of_files: successful = False self.logger.error("Output file not found") return successful, () # Get file and do the parsing outfile = out_folder.get_abs_path(self._calc._OUTPUT_FILE_NAME) ouput_trajectory = out_folder.get_abs_path( self._calc._OUTPUT_TRAJECTORY_FILE_NAME) output_data, cell, stress_tensor = read_log_file(outfile) positions, forces, symbols, cell2 = read_lammps_positions_and_forces( ouput_trajectory) # look at warnings warnings = [] with open(out_folder.get_abs_path(self._calc._SCHED_ERROR_FILE)) as f: errors = f.read() if errors: warnings = [errors] # ====================== prepare the output node ====================== # save the outputs new_nodes_list = [] # save optimized structure into node structure = StructureData(cell=cell) for i, position in enumerate(positions[-1]): structure.append_atom(position=position.tolist(), symbols=symbols[i]) new_nodes_list.append(('output_structure', structure)) # save forces into node array_data = ArrayData() array_data.set_array('forces', forces) array_data.set_array('stress', stress_tensor) new_nodes_list.append(('output_array', array_data)) # add the dictionary with warnings output_data.update({'warnings': warnings}) parameters_data = ParameterData(dict=output_data) new_nodes_list.append((self.get_linkname_outparams(), parameters_data)) # add the dictionary with warnings # new_nodes_list.append((self.get_linkname_outparams(), ParameterData(dict={'warnings': warnings}))) return successful, new_nodes_list
def test_export_trajectory(self): from aiida.orm.data.structure import StructureData from aiida.orm.data.array.trajectory import TrajectoryData from aiida.tools.dbexporters.tcod import export_values cells = [[[ 2., 0., 0., ], [ 0., 2., 0., ], [ 0., 0., 2., ]], [[ 3., 0., 0., ], [ 0., 3., 0., ], [ 0., 0., 3., ]]] symbols = [['H', 'O', 'C'], ['H', 'O', 'C']] positions = [[[0., 0., 0.], [0.5, 0.5, 0.5], [1.5, 1.5, 1.5]], [[0., 0., 0.], [0.75, 0.75, 0.75], [1.25, 1.25, 1.25]]] structurelist = [] for i in range(0, 2): struct = StructureData(cell=cells[i]) for j, symbol in enumerate(symbols[i]): struct.append_atom(symbols=symbol, position=positions[i][j]) structurelist.append(struct) td = TrajectoryData(structurelist=structurelist) with self.assertRaises(ValueError): # Trajectory index is not specified v = export_values(td) expected_tags = [ '_atom_site_fract_x', '_atom_site_fract_y', '_atom_site_fract_z', '_atom_site_label', '_atom_site_type_symbol', '_audit_conform_dict_location', '_audit_conform_dict_name', '_audit_conform_dict_version', '_audit_creation_method', '_cell_angle_alpha', '_cell_angle_beta', '_cell_angle_gamma', '_cell_length_a', '_cell_length_b', '_cell_length_c', '_chemical_formula_sum', '_symmetry_Int_Tables_number', '_symmetry_equiv_pos_as_xyz', '_symmetry_space_group_name_H-M', '_symmetry_space_group_name_Hall' ] tcod_file_tags = [ '_tcod_content_encoding_id', '_tcod_content_encoding_layer_id', '_tcod_content_encoding_layer_type', '_tcod_file_URI', '_tcod_file_content_encoding', '_tcod_file_contents', '_tcod_file_id', '_tcod_file_md5sum', '_tcod_file_name', '_tcod_file_role', '_tcod_file_sha1sum' ] # Not stored and not to be stored: v = export_values(td, trajectory_index=1) self.assertEqual(sorted(v['0'].keys()), expected_tags) # Stored, but not expected to be stored: td = TrajectoryData(structurelist=structurelist) td.store() v = export_values(td, trajectory_index=1) self.assertEqual(sorted(v['0'].keys()), expected_tags + tcod_file_tags) # Not stored, but expected to be stored: td = TrajectoryData(structurelist=structurelist) v = export_values(td, trajectory_index=1, store=True) self.assertEqual(sorted(v['0'].keys()), expected_tags + tcod_file_tags) # Both stored and expected to be stored: td = TrajectoryData(structurelist=structurelist) td.store() v = export_values(td, trajectory_index=1, store=True) self.assertEqual(sorted(v['0'].keys()), expected_tags + tcod_file_tags) # Stored, but asked not to include DB dump: td = TrajectoryData(structurelist=structurelist) td.store() v = export_values(td, trajectory_index=1, dump_aiida_database=False) self.assertEqual(sorted(v['0'].keys()), expected_tags)
def execute(args): """ The main execution of the script, which will run some preliminary checks on the command line arguments before passing them to the workchain and running it """ try: code = Code.get_from_string(args.codename) except NotExistent as exception: print "Execution failed: could not retrieve the code '{}'".format(args.codename) print "Exception report: {}".format(exception) return try: structure = load_node(args.structure) except: # # Slightly distorted structure # alat = 5.430 # angstrom cell = [[0.5*alat, 0.5*alat, 0.,], [0., 0.5*alat, 0.5*alat,], [0.5*alat, 0., 0.5*alat,], ] # Si # This was originally given in the "ScaledCartesian" format # structure = StructureData(cell=cell) structure.append_atom(position=(0.000*alat,0.000*alat,0.000*alat),symbols=['Si']) structure.append_atom(position=(0.250*alat,0.245*alat,0.250*alat),symbols=['Si']) #print "Execution failed: failed to load the node for the given structure pk '{}'".format(args.structure) #print "Exception report: {}".format(exception) #return if not isinstance(structure, StructureData): print "The provided pk {} for the structure does not correspond to StructureData, aborting...".format(args.parent_calc) return kpoints = KpointsData() kpoints.set_kpoints_mesh(args.kpoints) bandskpoints = KpointsData() bandskpoints.set_cell(structure.cell, structure.pbc) bandskpoints.set_kpoints_path(kpoint_distance = 0.05) parameters = { 'xc-functional': 'LDA', 'xc-authors': 'CA', 'spinpolarized': False, 'meshcutoff': '150.0 Ry', 'max-scfiterations': 50, 'dm-numberpulay': 4, 'dm-mixingweight': 0.3, 'dm-tolerance': 1.e-4, 'Solution-method': 'diagon', 'electronic-temperature': '25 meV', 'md-typeofrun': 'cg', 'md-numcgsteps': 10, 'md-maxcgdispl': '0.1 Ang', 'md-maxforcetol': '0.04 eV/Ang' } # default basis basis = { 'pao-energy-shift': '100 meV', '%block pao-basis-sizes': """ Si DZP """, } settings = {} options = { 'resources': { 'num_machines': 1 }, 'max_wallclock_seconds': args.max_wallclock_seconds, } run( SiestaBaseWorkChain, code=code, structure=structure, pseudo_family=Str(args.pseudo_family), kpoints=kpoints, bandskpoints=bandskpoints, parameters=ParameterData(dict=parameters), settings=ParameterData(dict=settings), options=ParameterData(dict=options), basis=ParameterData(dict=basis), max_iterations=Int(args.max_iterations), )
def get_structuredata(self): """ Return a StructureData object based on the data in the input file. This uses all of the data in the input file to do the necessary unit conversion, ect. and then creates an AiiDa StructureData object. All of the names corresponding of the Kind objects composing the StructureData object will match those found in the ATOMIC_SPECIES block, so the pseudopotentials can be linked to the calculation using the kind.name for each specific type of atom (in the event that you wish to use different pseudo's for two or more of the same atom). :return: StructureData object of the structure in the input file :rtype: aiida.orm.data.structure.StructureData :raises aiida.common.exceptions.ParsingError: if there are issues parsing the input. """ # CELL_PARAMETERS are present. if self.cell_parameters is None: raise ParsingError( 'CELL_PARAMETERS not found while parsing the input file. This ' 'card is needed for AiiDa.') # Figure out the factor needed to convert the lattice vectors # to Angstroms. # TODO: ***ASK GEORGE IF I SHOULD MULTIPLY OR DIVIDE BY ALAT*** cell_units = self.cell_parameters.get('units') if (cell_units == 'alat') or (cell_units is None): # Try to determine the value of alat from the namelist. celldm1 = self.namelists['SYSTEM'].get('celldm(1)') a = self.namelists['SYSTEM'].get('a') # Only one of 'celldm(1)' or 'a' can be set. if (celldm1 is not None) and (a is not None): raise ParsingError( "Both 'celldm(1)' and 'a' were set in the input file.") elif celldm1 is not None: cell_conv_factor = celldm1 * bohr_to_ang # celldm(1) in Bohr elif a is not None: cell_conv_factor = a # a is in Angstroms else: if cell_units is None: cell_conv_factor = bohr_to_ang # QE assumes Bohr else: raise ParsingError( "Unable to determine the units of the lattice vectors." ) elif cell_units == 'bohr': cell_conv_factor = bohr_to_ang elif cell_units == 'angstrom': cell_conv_factor = 1.0 else: raise ParsingError( "Unable to determine the units of the lattice vectors.") # Get the lattice vectors and convert them to units of Angstroms. cell = np.array(self.cell_parameters['cell']) * cell_conv_factor # Get the positions and convert them to [x, y, z] Angstrom vectors. pos_units = self.atomic_positions['units'] positions = np.array(self.atomic_positions['positions']) if pos_units in (None, 'alat'): # QE assumes alat alat = np.linalg.norm(cell[0]) # Cell in Ang, so alat in Ang positions *= alat elif pos_units == 'bohr': positions = positions * bohr_to_ang elif pos_units == 'angstrom': pass elif pos_units == 'crystal': positions = np.dot(positions, cell) # rotate into [x y z] basis else: raise ParsingError( 'Unable to determine to convert positions to [x y z] Angstrom.' ) # Get the atom names corresponding to positions. names = self.atomic_positions['names'] # Create a dictionary that maps an atom name to it's mass. mass_dict = dict( zip(self.atomic_species['names'], self.atomic_species['masses'])) # Use the names to figure out the atomic symbols. symbols = [] for name in names: candiates = [ s for s in _valid_symbols if name.lower().startswith(s.lower()) ] if len(candiates) == 0: raise ParsingError( 'Unable to figure out the element represented by the ' 'label, {}, in the input file.'.format(name)) # Choose the longest match, since, for example, S and Si match Si. symbols.append(max(candiates, key=lambda x: len(x))) # Now that we have the names and their corresponding symbol and mass, as # well as the positions and cell in units of Angstroms, we create the # StructureData object. structuredata = StructureData(cell=cell) for name, symbol, position in zip(names, symbols, positions): mass = mass_dict[name] structuredata.append_atom(name=name, symbols=symbol, position=position, mass=mass) return structuredata
def execute(args): """ The main execution of the script, which will run some preliminary checks on the command line arguments before passing them to the workchain and running it """ try: siesta_code = Code.get_from_string(args.siesta_codename) except NotExistent as exception: print "Execution failed: could not retrieve the code '{}'".format( args.siesta_codename) print "Exception report: {}".format(exception) return try: gollum_code = Code.get_from_string(args.gollum_codename) except NotExistent as exception: print "Execution failed: could not retrieve the code '{}'".format( args.gollum_codename) print "Exception report: {}".format(exception) return protocol = Str(args.protocol) ###### Siesta structures ############################## alat = 1.00 # Angstrom. Not passed to the fdf file # Leads cellle = [[ 20., 0., 0., ], [ 0., 20., 0., ], [ 0., 0., 5., ]] sle = StructureData(cell=cellle) for i in range(0, 2): sle.append_atom(position=(0., 0., i * 2.5), symbols=['Au']) if args.structure_em > 0: structure_le = load_node(args.structure_le) else: structure_le = sle # Extended molecule cellem = [[ 20., 0., 0., ], [ 0., 20., 0., ], [ 0., 0., 45., ]] sem = StructureData(cell=cellem) for i in range(0, 18): sem.append_atom(position=(0., 0., i * 2.5), symbols=['Au']) if args.structure_em > 0: structure_em = load_node(args.structure_em) else: structure_em = sem ###### Siesta k-ppoints ############################### kpoints_le = KpointsData() kpoints_le.set_kpoints_mesh([1, 1, 90]) kpoints_em = KpointsData() kpoints_em.set_kpoints_mesh([1, 1, 10]) ###### Gollum parameters ############################## # The "atom" block is definied independently pms = { 'NBlock leadp': """ 2 2 -1 2 2 1 """, 'atom': """ 1 2 2 0 0 10 2 2 2 """ } parameters = ParameterData(dict=pms) ###### run(GollumSiestaWorkChain, siesta_code=siesta_code, gollum_code=gollum_code, structure_le=structure_le, structure_em=structure_em, protocol=protocol, kpoints_le=kpoints_le, kpoints_em=kpoints_em, parameters=parameters)
def execute(args): """ The main execution of the script, which will run some preliminary checks on the command line arguments before passing them to the workchain and running it """ try: code = Code.get_from_string(args.codename) except NotExistent as exception: print "Execution failed: could not retrieve the code '{}'".format( args.codename) print "Exception report: {}".format(exception) return try: protocol = args.protocol except: print "Cannot seem to get protocol..." protocol = "standard" protocol = Str(protocol) try: structure = load_node(args.structure) except: # # Slightly distorted structure # alat = 5.430 # angstrom cell = [ [ 0.5 * alat, 0.5 * alat, 0., ], [ 0., 0.5 * alat, 0.5 * alat, ], [ 0.5 * alat, 0., 0.5 * alat, ], ] # Si # This was originally given in the "ScaledCartesian" format # structure = StructureData(cell=cell) structure.append_atom(position=(0.000 * alat, 0.000 * alat, 0.000 * alat), symbols=['Si']) structure.append_atom(position=(0.250 * alat, 0.245 * alat, 0.250 * alat), symbols=['Si']) #print "Execution failed: failed to load the node for the given structure pk '{}'".format(args.structure) #print "Exception report: {}".format(exception) #return if not isinstance(structure, StructureData): print "The provided pk {} for the structure does not correspond to StructureData, aborting...".format( args.parent_calc) return run(SiestaBandsWorkChain, code=code, structure=structure, protocol=protocol)
def execute(args): """ The main execution of the script, which will run some preliminary checks on the command line arguments before passing them to the workchain and running it """ try: code = Code.get_from_string(args.codename) except NotExistent as exception: print "Execution failed: could not retrieve the code '{}'".format(args.codename) print "Exception report: {}".format(exception) return alat = 10.0 # angstrom cell = [[alat, 0., 0.,], [0., alat, 0.,], [0., 0., alat,], ] # Water molecule # One of the H atoms is sligthy moved s = StructureData(cell=cell) s.append_atom(position=(0.000,0.000,0.00),symbols=['O']) s.append_atom(position=(0.757,0.586,0.00),symbols=['H']) s.append_atom(position=(-0.780,0.600,0.00),symbols=['H']) structure = s kpoints = KpointsData() kpoints.set_kpoints_mesh(args.kpoints) parameters = { 'meshcutoff': '80.000 Ry', 'dm:numberpulay': 4, 'dm:mixingweight': 0.2, 'dm:tolerance': 1.e-3, 'max-scfiterations': 30, 'scf-must-converge': True, 'geometry-must-converge': True, 'electronic-temperature': '25 meV', 'md-typeofrun': 'CG', 'md-numcgsteps': 6, 'md-maxcgdispl': '0.1 Ang', 'md-maxforcetol': '0.03 eV/Ang', 'xml:write': True } basis = { 'pao-energy-shift': '300 meV', 'pao-basis-size': 'DZP' } settings = {} options = { 'resources': { 'num_machines': 1 }, 'max_wallclock_seconds': args.max_wallclock_seconds, } run( SiestaBaseWorkChain, code=code, structure=structure, pseudo_family=Str(args.pseudo_family), kpoints=kpoints, parameters=ParameterData(dict=parameters), settings=ParameterData(dict=settings), options=ParameterData(dict=options), basis=ParameterData(dict=basis), max_iterations=Int(args.max_iterations), )
def execute(args): """ The main execution of the script, which will run some preliminary checks on the command line arguments before passing them to the workchain and running it """ try: code = Code.get_from_string(args.codename) except NotExistent as exception: print "Execution failed: could not retrieve the code '{}'".format( args.codename) print "Exception report: {}".format(exception) return try: stm_code = Code.get_from_string(args.stm_codename) except NotExistent as exception: print "Execution failed: could not retrieve the code '{}'".format( args.stm_codename) print "Exception report: {}".format(exception) return height = Float(args.height) e1 = Float(args.e1) e2 = Float(args.e2) protocol = Str(args.protocol) alat = 15. # angstrom cell = [ [ alat, 0., 0., ], [ 0., alat, 0., ], [ 0., 0., alat, ], ] # Benzene molecule # s = StructureData(cell=cell) def perm(x, y, z): return (z, y + 0.5 * alat, 0.5 * alat) s.append_atom(position=perm(0.000, 0.000, 0.468), symbols=['H']) s.append_atom(position=perm(0.000, 0.000, 1.620), symbols=['C']) s.append_atom(position=perm(0.000, -2.233, 1.754), symbols=['H']) s.append_atom(position=perm(0.000, 2.233, 1.754), symbols=['H']) s.append_atom(position=perm(0.000, -1.225, 2.327), symbols=['C']) s.append_atom(position=perm(0.000, 1.225, 2.327), symbols=['C']) s.append_atom(position=perm(0.000, -1.225, 3.737), symbols=['C']) s.append_atom(position=perm(0.000, 1.225, 3.737), symbols=['C']) s.append_atom(position=perm(0.000, -2.233, 4.311), symbols=['H']) s.append_atom(position=perm(0.000, 2.233, 4.311), symbols=['H']) s.append_atom(position=perm(0.000, 0.000, 4.442), symbols=['C']) s.append_atom(position=perm(0.000, 0.000, 5.604), symbols=['H']) if args.structure > 0: structure = load_node(args.structure) else: structure = s run(SiestaSTMWorkChain, code=code, stm_code=stm_code, structure=structure, protocol=protocol, height=height, e1=e1, e2=e2)
def test_parser_with_init_struct(new_database, new_workdir): """ Test the parser """ from aiida.parsers import ParserFactory from aiida.common.datastructures import calc_states from aiida.common.folders import SandboxFolder from aiida.orm import DataFactory code = get_main_code(new_workdir) calc = code.new_calc() calc.set_resources({"num_machines": 1, "num_mpiprocs_per_machine": 1}) from aiida.orm.data.structure import StructureData struct = StructureData() struct.append_atom(position=[0, 0, 0], symbols="Mg", name="Mgx") struct.append_atom(position=[0.5, 0.5, 0.5], symbols="O", name="Ox") calc.use_structure(struct) calc.store_all() calc._set_state(calc_states.PARSING) parser_cls = ParserFactory("crystal17.basic") parser = parser_cls(calc) with SandboxFolder() as folder: main_out_path = os.path.join(os.path.dirname(tests.__file__), "output_files", "mgo_sto3g_scf.crystal.out") with open(main_out_path) as f: folder.create_file_from_filelike(f, "main.out") fdata = DataFactory("folder")() fdata.replace_with_folder(folder.abspath) mock_retrieved = {calc._get_linkname_retrieved(): fdata} success, node_list = parser.parse_with_retrieved(mock_retrieved) assert success node_dict = dict(node_list) assert set(['output_parameters', 'output_settings']) == set(node_dict.keys()) expected_params = { 'parser_version': str(aiida_crystal17.__version__), 'ejplugins_version': str(ejplugins.__version__), 'parser_class': 'CryBasicParser', 'parser_warnings': [], 'errors': [], 'warnings': [], 'energy': -2.7121814374931E+02 * 27.21138602, 'energy_units': 'eV', # hartree to eV 'calculation_type': 'restricted closed shell', 'calculation_spin': False, 'wall_time_seconds': 3, 'number_of_atoms': 2, 'number_of_assymetric': 2, 'scf_iterations': 7, 'volume': 18.65461527264623, } assert edict.diff(node_dict['output_parameters'].get_dict(), expected_params, np_allclose=True) == {}
def create_structure_bands(): alat = 4. # angstrom cell = [ [ alat, 0., 0., ], [ 0., alat, 0., ], [ 0., 0., alat, ], ] s = StructureData(cell=cell) s.append_atom(position=(0., 0., 0.), symbols='Fe') s.append_atom(position=(alat / 2., alat / 2., alat / 2.), symbols='O') s.store() @wf def connect_structure_bands(structure): alat = 4. cell = np.array([ [alat, 0., 0.], [0., alat, 0.], [0., 0., alat], ]) k = KpointsData() k.set_cell(cell) k.set_kpoints_path([('G', 'M', 2)]) b = BandsData() b.set_kpointsdata(k) b.set_bands([[1.0, 2.0], [3.0, 4.0]]) k.store() b.store() return b b = connect_structure_bands(s) # Create 2 groups and add the data to one of them g_ne = Group(name='non_empty_group') g_ne.store() g_ne.add_nodes(b) g_e = Group(name='empty_group') g_e.store() return { TestVerdiDataListable.NODE_ID_STR: b.id, TestVerdiDataListable.NON_EMPTY_GROUP_ID_STR: g_ne.id, TestVerdiDataListable.EMPTY_GROUP_ID_STR: g_e.id }