示例#1
0
    def set_structure_data(self, *args):
        "Called when the user presses [Get structure]."
        if not self.update_element():
            oops("Invalid element.")
            return
        z = ase.atomic_numbers[self.legal_element]
        ref = ase.data.reference_states[z]
        if ref is None:
            structure = None
        else:
            structure = ref['symmetry'].lower()

        if ref is None or not structure in self.list_of_structures:
            oops(
                "Unsupported or unknown structure",
                "Element = %s,  structure = %s" %
                (self.legal_element, structure))
            return
        for i, s in enumerate(self.list_of_structures):
            if structure == s:
                self.structure.set_active(i)
        a = ref['a']
        self.lattice_const_a.set_value(a)
        self.fourindex = self.needs_4index[structure]
        if self.fourindex:
            try:
                c = ref['c']
            except KeyError:
                c = ref['c/a'] * a
            self.lattice_const_c.set_value(c)
            self.lattice_label_c.show()
            self.lattice_box_c.show()
        else:
            self.lattice_label_c.hide()
            self.lattice_box_c.hide()
示例#2
0
 def set_structure_data(self, *args):
     "Called when the user presses [Get structure]."
     if not self.update_element():
         oops(_("Invalid element."))
         return
     z = ase.data.atomic_numbers[self.legal_element]
     ref = ase.data.reference_states[z]
     if ref is None:
         structure = None
     else:
         structure = ref['symmetry']
             
     if ref is None or not structure in self.list_of_structures:
         oops(_("Unsupported or unknown structure",
                "Element = %s,  structure = %s" % (self.legal_element,
                                                   structure)))
         return
     for i, s in enumerate(self.list_of_structures):
         if structure == s:
             self.structure.set_active(i)
     a = ref['a']
     self.lattice_const_a.set_value(a)
     self.fourindex = self.needs_4index[structure]
     if self.fourindex:
         try:
             c = ref['c']
         except KeyError:
             c = ref['c/a'] * a
         self.lattice_const_c.set_value(c)
         self.lattice_label_c.show()
         self.lattice_box_c.show()
     else:
         self.lattice_label_c.hide()
         self.lattice_box_c.hide()
示例#3
0
文件: render.py 项目: jboes/ase
 def material_from_selection(self,*args):
     box_selection = self.get_selection()
     selection = self.gui.images.selected.copy()
     if selection.any():
         Z = []
         for n in range(len(selection)):
             if selection[n]:
                 Z += [self.gui.images.Z[n]]
         name = formula(Z)
         if (box_selection == selection).all():
             name += ': ' + self.texture_selection.get_text()
         texture_button = gtk.combo_box_new_text()
         for t in self.finish_list:
             texture_button.append_text(t)
         texture_button.set_active(1)
         transparency = gtk.Adjustment(0,0.0,1.0,0.01)
         transparency_spin = gtk.SpinButton(transparency, 0, 0)
         transparency_spin.set_digits(2)
         delete_button = gtk.Button(stock=gtk.STOCK_DELETE)
         alignment = delete_button.get_children()[0]
         index = len(self.materials)
         delete_button.connect("clicked",self.delete_material,{"n":index})
         self.materials += [[True,selection,texture_button,
                             gtk.Label(_("  transparency: ")),transparency_spin,
                             gtk.Label("   "),delete_button,gtk.Label()]]
         self.materials[-1][-1].set_markup("    "+name)
         pack(self.tbox,[self.materials[-1][2],self.materials[-1][3],self.materials[-1][4],
                         self.materials[-1][5],self.materials[-1][6],self.materials[-1][7]])
     else:
         oops(_("Can not create new texture! Must have some atoms selected to create a new material!"))
示例#4
0
文件: colors.py 项目: lqcata/ase
 def apply(self, *args):
     #if self.colormode in ['atno', 'jmol', 'tags']:
     # Color atoms according to an integer value number
     if self.color_errors:
         oops(_("Incorrect color specification"),
              "%s: %s" % self.color_errors.values()[0])
         return False
     colordata = self.actual_colordata
     if self.colormode == 'force':
         # Use integers instead for border values
         colordata = [[i, x[1]] for i, x in enumerate(self.actual_colordata)]
         self.gui.colormode_force_data = self.colormode_force_data
     if self.colormode == 'velocity':
         # Use integers instead for border values
         colordata = [[i, x[1]] for i, x in enumerate(self.actual_colordata)]
         self.gui.colormode_velocity_data = self.colormode_velocity_data
     maxval = max([x for x, y in colordata])
     self.gui.colors = [None] * (maxval + 1)
     new = self.gui.drawing_area.window.new_gc
     alloc = self.gui.colormap.alloc_color
     for z, val in colordata:
         if isinstance(val, str):
             self.gui.colors[z] = new(alloc(val))
         else:
             clr = tuple([int(65535*x) for x in val])
             assert len(clr) == 3
             self.gui.colors[z] = new(alloc(*clr))
     self.gui.colormode = self.colormode
     self.gui.colordata = self.actual_colordata
     self.gui.draw()
     return True
示例#5
0
 def apply(self, *args):
     self.update()
     if self.atoms is not None:
         self.gui.new_atoms(self.atoms)
         return True
     else:
         oops(_("No valid atoms."), _("You have not (yet) specified " "a consistent set of parameters."))
         return False
示例#6
0
文件: scaling.py 项目: lqcata/ase
 def get_deformation_axes(self):
     """Return which axes the user wants to deform along."""
     for but, deform in self.deformtable:
         if but.get_active():
             return np.array(deform)
     # No deformation chosen!
     oops("No deformation chosen: Please choose a deformation mode.")
     return False
示例#7
0
 def get_deformation_axes(self):
     """Return which axes the user wants to deform along."""
     for but, deform in self.deformtable:
         if but.get_active():
             return np.array(deform)
     # No deformation chosen!
     oops("No deformation chosen: Please choose a deformation mode.")
     return False
示例#8
0
 def apply(self, *args):
     """ create gui atoms from currently active atoms"""
     self.update()
     if self.atoms is not None:
         self.gui.new_atoms(self.atoms)
         return True
     else:
         oops(_("No valid atoms.", "You have not (yet) specified a consistent set of " "parameters."))
         return False
示例#9
0
 def apply(self, *args):
     self.update()
     if self.atoms is not None:
         self.gui.new_atoms(self.atoms)
         return True
     else:
         oops("No valid atoms.",
              "You have not (yet) specified a consistent set of parameters.")
         return False
示例#10
0
 def run(self, *args):
     "The method called when the button is clicked."
     if self.python:
         now = time.ctime()
         win = PyWindow(self.title, now, self.python)
     else:
         oops(_("No Python code"),
              _("You have not (yet) specified a "
                "consistent set of parameters."))
示例#11
0
文件: pybutton.py 项目: lqcata/ase
 def run(self, *args):
     "The method called when the button is clicked."
     if self.python:
         now = time.ctime()
         win = PyWindow(self.title, now, self.python)
     else:
         oops(
             _("No Python code"),
             _("You have not (yet) specified a "
               "consistent set of parameters."))
示例#12
0
 def setup_atoms(self):
     self.atoms = self.get_atoms()
     if self.atoms is None:
         return False
     try:
         self.calculator = self.gui.simulation['calc']
     except KeyError:
         oops(_("No calculator: Use Calculate/Set Calculator on the menu."))
         return False
     self.atoms.set_calculator(self.calculator())
     return True
示例#13
0
 def setup_atoms(self):
     self.atoms = self.get_atoms()
     if self.atoms is None:
         return False
     try:
         self.calculator = self.gui.simulation['calc']
     except KeyError:
         oops(_("No calculator: Use Calculate/Set Calculator on the menu."))
         return False
     self.atoms.set_calculator(self.calculator())
     return True
示例#14
0
文件: crystal.py 项目: uu1477/MyAse
 def apply(self, *args):
     """ create gui atoms from currently active atoms"""
     self.update()
     if self.atoms is not None:
         self.gui.new_atoms(self.atoms)
         return True
     else:
         oops(
             _('No valid atoms.'),
             _('You have not (yet) specified a consistent set of '
               'parameters.'))
         return False
示例#15
0
 def get_atoms(self):
     "Make an atoms object from the active image"
     images = self.gui.images
     if images.natoms < 1:
         oops(_("No atoms present"))
         return None
     n = self.getimagenumber()
     natoms = len(images.P[n]) // images.repeat.prod()
     constraint = None
     if not images.dynamic.all():
         constraint = FixAtoms(mask=1-images.dynamic)
     return Atoms(positions=images.P[n,:natoms],
                  symbols=images.Z[:natoms],
                  cell=images.A[n],
                  magmoms=images.M[n,:natoms],
                  tags=images.T[n,:natoms],
                  pbc=images.pbc,
                  constraint=constraint)
示例#16
0
 def get_atoms(self):
     "Make an atoms object from the active image"
     images = self.gui.images
     if images.natoms < 1:
         oops(_("No atoms present"))
         return None
     n = self.getimagenumber()
     natoms = len(images.P[n]) / images.repeat.prod()
     constraint = None
     if not images.dynamic.all():
         constraint = FixAtoms(mask=1-images.dynamic)
     return Atoms(positions=images.P[n,:natoms],
                  symbols=images.Z[:natoms],
                  cell=images.A[n],
                  magmoms=images.M[n,:natoms],
                  tags=images.T[n,:natoms],
                  pbc=images.pbc,
                  constraint=constraint)
示例#17
0
 def row_add(self, widget=None):
     "Add a row to the list of directions."
     if self.fourindex:
         n = 4
     else:
         n = 3
     idx = tuple([int(a.value) for a in self.newdir_index[:n]])
     if not np.array(idx).any():
         oops("At least one index must be non-zero")
         return
     if n == 4 and np.array(idx)[:3].sum() != 0:
         oops("Invalid hexagonal indices",
              "The sum of the first three numbers must be zero")
         return
     adj1 = gtk.Adjustment(self.newdir_layers.value, -100, 100, 1)
     adj2 = gtk.Adjustment(self.newdir_esurf.value, -1000.0, 1000.0, 0.1)
     adj1.connect("value-changed", self.update)
     adj2.connect("value-changed", self.update)
     self.direction_table.append([idx, adj1, adj2])
     self.update_direction_table()
示例#18
0
 def row_add(self, widget=None):
     "Add a row to the list of directions."
     if self.fourindex:
         n = 4
     else:
         n = 3
     idx = tuple( [int(a.value) for a in self.newdir_index[:n]] )
     if not np.array(idx).any():
         oops(_("At least one index must be non-zero"))
         return
     if n == 4 and np.array(idx)[:3].sum() != 0:
         oops(_("Invalid hexagonal indices",
              "The sum of the first three numbers must be zero"))
         return
     adj1 = gtk.Adjustment(self.newdir_layers.value, -100, 100, 1)
     adj2 = gtk.Adjustment(self.newdir_esurf.value, -1000.0, 1000.0, 0.1)
     adj1.connect("value-changed", self.update)
     adj2.connect("value-changed", self.update)
     self.direction_table.append([idx, adj1, adj2])
     self.update_direction_table()
示例#19
0
 def get_from_database(self, *args):
     element = self.elements[0][0].get_text()
     z = ase.data.atomic_numbers[self.legal_element]        
     ref = ase.data.reference_states[z]
     lattice = ref['symmetry']
     index = 0
     while index < len(crystal_definitions) and crystal_definitions[index][0] != lattice:
         index += 1
     if index == len(crystal_definitions) or not self.legal_element:
         oops(_("Can't find lattice definition!"))
         return False
     self.structinfo.set_active(index)
     self.lattice_lbuts[0].set_value(ref['a'])
     if lattice == 'hcp':
         self.lattice_lbuts[2].set_value(ref['c/a']*ref['a'])
     self.elements[0][0].set_text(element)
     if lattice in ['fcc', 'bcc', 'diamond']:
         self.elements[0][1].set_text('0')
         self.elements[0][2].set_text('0')
         self.elements[0][3].set_text('0')
示例#20
0
 def get_from_database(self, *args):
     element = self.elements[0][0].get_text()
     z = ase.data.atomic_numbers[self.legal_element]
     ref = ase.data.reference_states[z]
     lattice = ref['symmetry']
     index = 0
     while index < len(crystal_definitions
                       ) and crystal_definitions[index][0] != lattice:
         index += 1
     if index == len(crystal_definitions) or not self.legal_element:
         oops(_("Can't find lattice definition!"))
         return False
     self.structinfo.set_active(index)
     self.lattice_lbuts[0].set_value(ref['a'])
     if lattice == 'hcp':
         self.lattice_lbuts[2].set_value(ref['c/a'] * ref['a'])
     self.elements[0][0].set_text(element)
     if lattice in ['fcc', 'bcc', 'diamond']:
         self.elements[0][1].set_text('0')
         self.elements[0][2].set_text('0')
         self.elements[0][3].set_text('0')
示例#21
0
 def get_lattice_const(self, *args):
     if not self.update_element():
         oops(_('Invalid element.'))
         return
     z = ase.data.atomic_numbers[self.legal_element]
     ref = ase.data.reference_states[z]
     surface = self.structchoice.get_active_text()
     if not surface:
         oops(_('No structure specified!'))
         return
     struct = self.surfinfo[surface][1]
     if ref is None or ref['symmetry'] != struct:
         from ase.data.alternatives import alternative_structures
         alt = alternative_structures[z]
         if alt and alt['symmetry'] == struct:
             ref = alt
         else:
             oops(_('%(struct)s lattice constant unknown for %(element)s.')
                  % dict(struct=struct.upper(), element=self.legal_element))
     
     a = ref['a']
     self.lattice_const.set_value(a)
     if struct == 'hcp':
         c = ref['c/a'] * a
         self.lattice_const_c.set_value(c)
示例#22
0
 def get_lattice_const(self, *args):
     if not self.update_element():
         oops("Invalid element.")
         return
     z = ase.atomic_numbers[self.legal_element]
     ref = ase.data.reference_states[z]
     surface = self.structchoice.get_active_text()
     if not surface:
         oops("No structure specified!")
         return
     struct = self.surfinfo[surface][1]
     if ref is None or ref['symmetry'].lower() != struct:
         from ase.data.alternatives import alternative_structures
         alt = alternative_structures[z]
         if alt and alt['symmetry'].lower() == struct:
             ref = alt
         else:
             oops(struct.upper() + " lattice constant unknown for "
                  + self.legal_element + ".")
             
     a = ref['a']
     self.lattice_const.set_value(a)
     if struct == 'hcp':
         c = ref['c/a'] * a
         self.lattice_const_c.set_value(c)
示例#23
0
文件: render.py 项目: adbX/ase
 def material_from_selection(self, *args):
     box_selection = self.get_selection()
     selection = self.gui.images.selected.copy()
     if selection.any():
         Z = []
         for n in range(len(selection)):
             if selection[n]:
                 Z += [self.gui.images.Z[n]]
         name = formula(Z)
         if (box_selection == selection).all():
             name += ': ' + self.texture_selection.get_text()
         texture_button = gtk.combo_box_new_text()
         for t in self.finish_list:
             texture_button.append_text(t)
         texture_button.set_active(1)
         transparency = gtk.Adjustment(0, 0.0, 1.0, 0.01)
         transparency_spin = gtk.SpinButton(transparency, 0, 0)
         transparency_spin.set_digits(2)
         delete_button = gtk.Button(stock=gtk.STOCK_DELETE)
         alignment = delete_button.get_children()[0]
         index = len(self.materials)
         delete_button.connect("clicked", self.delete_material,
                               {"n": index})
         self.materials += [[
             True, selection, texture_button,
             gtk.Label(_("  transparency: ")), transparency_spin,
             gtk.Label("   "), delete_button,
             gtk.Label()
         ]]
         self.materials[-1][-1].set_markup("    " + name)
         pack(self.tbox, [
             self.materials[-1][2], self.materials[-1][3],
             self.materials[-1][4], self.materials[-1][5],
             self.materials[-1][6], self.materials[-1][7]
         ])
     else:
         oops(
             _("Can not create new texture! Must have some atoms selected to create a new material!"
               ))
示例#24
0
文件: save.py 项目: jboes/ase
    def save(self, dummy):
        "The user has pressed the SAVE button."
        filename = self.chooser.get_filename()
        if not filename or filename == "<<filename>>":
            oops("Please specify a file name")
            return

        # Check file type
        suffix = os.path.splitext(filename)[1][1:]
        if 'POSCAR' in filename or 'CONTCAR' in filename:
            suffix = 'POSCAR'
        if suffix == '':
            # No suffix chosen
            filt = self.chooser.get_filter().get_name()
            suffix = self.name_to_suffix[filt]
            if suffix is None:
                oops("Specify file type by giving a suffix or selecting a file type.")
                return
            else:
                filename = filename + '.' + suffix
        else:
            # Suffix given - check that it is not in conflict with selected file type.
            filt = self.chooser.get_filter().get_name()
            suffix2 = self.name_to_suffix[filt]
            if suffix2 is not None and suffix != suffix2:
                oops("Your filename suffix conflicts with the file type you have selected.")
                return
        if suffix not in self.name_to_suffix.values():
            oops("Unknown file suffix "+suffix)
            return
        
        # We now have a consistent file name with an allowed suffix.
        # Find out which images we want to save.
        if self.radio_thisconf.get_active():
            indices = [self.gui.frame]
        elif self.radio_allconf.get_active():
            indices = range(self.gui.images.nimages)
        elif self.radio_someconf.get_active():
            txt = self.whichconf.get_text()
            if not txt:
                oops("Please specify which images to save.")
                return
            try:
                slice = string2index(txt)
            except ValueError:
                oops("ERROR: Failed to parse image specification '%s'" % (txt,))
                return
            indices = range(self.gui.images.nimages)[slice]
            if isinstance(indices, int):
                indices = [indices]
        else:
            raise RuntimeError("No radio button selected - should not be possible!")

        # Now we are ready to write the file!
        extra = {}
        remove_hidden = False
        if self.is_graphics[suffix]:
            bbox = np.empty(4)
            size = np.array([self.gui.width, self.gui.height]) / self.gui.scale
            bbox[0:2] = np.dot(self.gui.center, self.gui.axes[:, :2]) - size / 2
            bbox[2:] = bbox[:2] + size
            extra['rotation'] = self.gui.axes
            extra['show_unit_cell'] = self.gui.ui.get_widget('/MenuBar/ViewMenu/ShowUnitCell').get_active()
            extra['bbox'] = bbox
            extra['colors'] = self.gui.get_colors(rgb=True)[self.gui.images.visible]
            remove_hidden = True
        if len(indices) == 1:
            # Saving a single configuration is always possible.
            write(filename, self.gui.images.get_atoms(indices[0],
                                                      remove_hidden=remove_hidden),
                  **extra)
        elif self.support_multi[suffix]:
            images = [self.gui.images.get_atoms(i, remove_hidden=remove_hidden)
                      for i in indices]
            write(filename, images, **extra)
        else:
            # We want to write multiple images, but the file format does not support it.
            # The solution is to write multiple files, inserting a number in the file name
            # before the suffix.
            filename = filename.replace('%', '%%') # Preserve % in filenames.
            suffixpos = filename.rfind('.')
            filename = filename[:suffixpos] + '%05d' + filename[suffixpos:]
            for i, idx in enumerate(indices):
                write(filename % (i,),
                      self.gui.images.get_atoms(idx, remove_hidden=remove_hidden),
                      **extra)
            oops("Wrote %d files" % (len(indices),),
                 (filename % (0,)) + ' .. ' + (filename % (len(indices)-1,)))
        self.destroy()
示例#25
0
    def save(self, dummy):
        "The user has pressed the SAVE button."
        filename = self.chooser.get_filename()
        if not filename or filename == "<<filename>>":
            oops("Please specify a file name")
            return

        # Check file type
        suffix = os.path.splitext(filename)[1][1:]
        if 'POSCAR' in filename or 'CONTCAR' in filename:
            suffix = 'POSCAR'
        if suffix == '':
            # No suffix chosen
            filt = self.chooser.get_filter().get_name()
            suffix = self.name_to_suffix[filt]
            if suffix is None:
                oops(
                    "Specify file type by giving a suffix or selecting a file type."
                )
                return
            else:
                filename = filename + '.' + suffix
        else:
            # Suffix given - check that it is not in conflict with selected file type.
            filt = self.chooser.get_filter().get_name()
            suffix2 = self.name_to_suffix[filt]
            if suffix2 is not None and suffix != suffix2:
                oops(
                    "Your filename suffix conflicts with the file type you have selected."
                )
                return
        if suffix not in self.name_to_suffix.values():
            oops("Unknown file suffix " + suffix)
            return

        # We now have a consistent file name with an allowed suffix.
        # Find out which images we want to save.
        if self.radio_thisconf.get_active():
            indices = [self.gui.frame]
        elif self.radio_allconf.get_active():
            indices = range(self.gui.images.nimages)
        elif self.radio_someconf.get_active():
            txt = self.whichconf.get_text()
            if not txt:
                oops("Please specify which images to save.")
                return
            try:
                slice = string2index(txt)
            except ValueError:
                oops("ERROR: Failed to parse image specification '%s'" %
                     (txt, ))
                return
            indices = range(self.gui.images.nimages)[slice]
            if isinstance(indices, int):
                indices = [indices]
        else:
            raise RuntimeError(
                "No radio button selected - should not be possible!")

        # Now we are ready to write the file!
        extra = {}
        remove_hidden = False
        if self.is_graphics[suffix]:
            bbox = np.empty(4)
            size = np.array([self.gui.width, self.gui.height]) / self.gui.scale
            bbox[0:2] = np.dot(self.gui.center,
                               self.gui.axes[:, :2]) - size / 2
            bbox[2:] = bbox[:2] + size
            extra['rotation'] = self.gui.axes
            extra['show_unit_cell'] = self.gui.ui.get_widget(
                '/MenuBar/ViewMenu/ShowUnitCell').get_active()
            extra['bbox'] = bbox
            extra['colors'] = self.gui.get_colors(
                rgb=True)[self.gui.images.visible]
            remove_hidden = True
        if len(indices) == 1:
            # Saving a single configuration is always possible.
            write(
                filename,
                self.gui.images.get_atoms(indices[0],
                                          remove_hidden=remove_hidden),
                **extra)
        elif self.support_multi[suffix]:
            images = [
                self.gui.images.get_atoms(i, remove_hidden=remove_hidden)
                for i in indices
            ]
            write(filename, images, **extra)
        else:
            # We want to write multiple images, but the file format does not support it.
            # The solution is to write multiple files, inserting a number in the file name
            # before the suffix.
            filename = filename.replace('%', '%%')  # Preserve % in filenames.
            suffixpos = filename.rfind('.')
            filename = filename[:suffixpos] + '%05d' + filename[suffixpos:]
            for i, idx in enumerate(indices):
                write(
                    filename % (i, ),
                    self.gui.images.get_atoms(idx,
                                              remove_hidden=remove_hidden),
                    **extra)
            oops("Wrote %d files" % (len(indices), ), (filename % (0, )) +
                 ' .. ' + (filename % (len(indices) - 1, )))
        self.destroy()
示例#26
0
文件: gui.py 项目: rosswhitfield/ase
 def xxx(self,
         x=None,
         message1=_('Not implemented!'),
         message2=_('do you really need it?')):
     oops(message1, message2)
示例#27
0
    def run(self, *args):
        """Make the deformation."""
        self.output.set_text("")
        if not self.setup_atoms():
            return
        deform_axes = self.get_deformation_axes()
        if deform_axes is False:
            return  #Nothing to do!

        # Prepare progress bar
        if self.radio_relax_on.get_active():
            fmax = self.fmax.value
            mininame = self.minimizers[self.algo.get_active()]
            self.begin(mode="scale/min", algo=mininame, fmax=fmax,
                       steps=self.steps.value, scalesteps=self.nsteps.value)
        else:
            self.begin(mode="scale", scalesteps=self.nsteps.value)
        try:
            logger_func = self.gui.simulation['progress'].get_logger_stream
        except (KeyError, AttributeError):
            logger = None
        else:
            logger = logger_func()  # Don't catch errors in the function.

        # Display status message
        self.status_label.set_text(_("Running ..."))
        self.status_label.modify_fg(gtk.STATE_NORMAL,
                                    gtk.gdk.color_parse('#AA0000'))
        while gtk.events_pending():
            gtk.main_iteration()

        # Do the scaling
        scale = self.max_scale.value
        if self.pull.get_active():
            steps = np.linspace(0, scale, self.nsteps.value)
        else:
            steps = np.linspace(-scale, scale, self.nsteps.value)
            steps += self.scale_offset.value
        undef_cell = self.atoms.get_cell()
        results = []
        #txt = "Strain\t\tEnergy [eV]\n"
        txt = ""
        # If we load all configurations, prepare it.
        if self.radio_results_all.get_active():
            self.prepare_store_atoms()

        stored_atoms = False
        try:
            # Now, do the deformation
            for i, d in enumerate(steps):
                deformation = np.diag(1.0 + d * deform_axes)
                self.atoms.set_cell(np.dot(undef_cell, deformation),
                                    scale_atoms=True)
                if self.gui.simulation.has_key('progress'):
                    self.gui.simulation['progress'].set_scale_progress(i)
                if self.radio_relax_on.get_active():
                    algo = getattr(ase.optimize, mininame)
                    if mininame == "MDMin":
                        minimizer = algo(self.atoms, logfile=logger,
                                         dt=self.mdmin_dt.value)
                    else:
                        minimizer = algo(self.atoms, logfile=logger)
                    minimizer.run(fmax=fmax, steps=self.steps.value)
                e = self.atoms.get_potential_energy()
                results.append((d, e))
                txt = txt + ("%.5f\t\t%.5f\n" % (d, e))
                self.output.set_text(txt)
                if self.radio_results_all.get_active():
                    self.store_atoms()
                    stored_atoms = True
        except AseGuiCancelException:
            # Update display to reflect cancellation of simulation.
            self.status_label.set_text(_("Calculation CANCELLED."))
            self.status_label.modify_fg(gtk.STATE_NORMAL,
                                        gtk.gdk.color_parse('#AA4000'))
        except MemoryError:
            self.status_label.set_text(_("Out of memory, consider using "
                                         "LBFGS instead"))
            self.status_label.modify_fg(gtk.STATE_NORMAL,
                                        gtk.gdk.color_parse('#AA4000'))
            
        else:
            # Update display to reflect succesful end of simulation.
            self.status_label.set_text(_("Calculation completed."))
            self.status_label.modify_fg(gtk.STATE_NORMAL,
                                        gtk.gdk.color_parse('#007700'))
                     
        if results:
            self.do_fit(np.array(results))
            if self.radio_results_optimal.get_active():
                if self.minimum_ok:
                    deformation = np.diag(1.0 + self.x0 * deform_axes)
                    self.atoms.set_cell(np.dot(undef_cell, deformation),
                                        scale_atoms=True)
                    if self.radio_relax_on.get_active():
                        if self.gui.simulation.has_key('progress'):
                            self.gui.simulation['progress'].set_scale_progress(
                                len(steps))
                        algo = getattr(ase.optimize, mininame)
                        minimizer = algo(self.atoms, logfile=logger)
                        minimizer.run(fmax=fmax, steps=self.steps.value)
                    # Store the optimal configuration.
                    self.prepare_store_atoms()
                    self.store_atoms()
                    stored_atoms = True
                else:
                    oops(_("No trustworthy minimum: Old configuration kept."))
            self.activate_output()
            if stored_atoms:
                self.gui.notify_vulnerable()
        self.end()    
            
        # If we store all configurations: Open movie window and energy graph
        if stored_atoms and self.gui.images.nimages > 1:
            self.gui.movie()
            assert not np.isnan(self.gui.images.E[0])
            if not self.gui.plot_graphs_newatoms():
                expr = 'i, e - E[-1]'            
                self.gui.plot_graphs(expr=expr)
            # Continuations should use the best image
            nbest = np.argmin(np.array(results)[:,1])
            self.start_nth_adj.value = nbest
示例#28
0
文件: scaling.py 项目: lqcata/ase
    def run(self, *args):
        """Make the deformation."""
        self.output.set_text("")
        if not self.setup_atoms():
            return
        deform_axes = self.get_deformation_axes()
        if deform_axes is False:
            return  #Nothing to do!

        # Prepare progress bar
        if self.radio_relax_on.get_active():
            fmax = self.fmax.value
            mininame = self.minimizers[self.algo.get_active()]
            self.begin(mode="scale/min",
                       algo=mininame,
                       fmax=fmax,
                       steps=self.steps.value,
                       scalesteps=self.nsteps.value)
        else:
            self.begin(mode="scale", scalesteps=self.nsteps.value)
        try:
            logger_func = self.gui.simulation['progress'].get_logger_stream
        except (KeyError, AttributeError):
            logger = None
        else:
            logger = logger_func()  # Don't catch errors in the function.

        # Display status message
        self.status_label.set_text(_("Running ..."))
        self.status_label.modify_fg(gtk.STATE_NORMAL,
                                    gtk.gdk.color_parse('#AA0000'))
        while gtk.events_pending():
            gtk.main_iteration()

        # Do the scaling
        scale = self.max_scale.value
        if self.pull.get_active():
            steps = np.linspace(0, scale, self.nsteps.value)
        else:
            steps = np.linspace(-scale, scale, self.nsteps.value)
            steps += self.scale_offset.value
        undef_cell = self.atoms.get_cell()
        results = []
        #txt = "Strain\t\tEnergy [eV]\n"
        txt = ""
        # If we load all configurations, prepare it.
        if self.radio_results_all.get_active():
            self.prepare_store_atoms()

        stored_atoms = False
        try:
            # Now, do the deformation
            for i, d in enumerate(steps):
                deformation = np.diag(1.0 + d * deform_axes)
                self.atoms.set_cell(np.dot(undef_cell, deformation),
                                    scale_atoms=True)
                if self.gui.simulation.has_key('progress'):
                    self.gui.simulation['progress'].set_scale_progress(i)
                if self.radio_relax_on.get_active():
                    algo = getattr(ase.optimize, mininame)
                    if mininame == "MDMin":
                        minimizer = algo(self.atoms,
                                         logfile=logger,
                                         dt=self.mdmin_dt.value)
                    else:
                        minimizer = algo(self.atoms, logfile=logger)
                    minimizer.run(fmax=fmax, steps=self.steps.value)
                e = self.atoms.get_potential_energy()
                results.append((d, e))
                txt = txt + ("%.5f\t\t%.5f\n" % (d, e))
                self.output.set_text(txt)
                if self.radio_results_all.get_active():
                    self.store_atoms()
                    stored_atoms = True
        except AseGuiCancelException:
            # Update display to reflect cancellation of simulation.
            self.status_label.set_text(_("Calculation CANCELLED."))
            self.status_label.modify_fg(gtk.STATE_NORMAL,
                                        gtk.gdk.color_parse('#AA4000'))
        except MemoryError:
            self.status_label.set_text(
                _("Out of memory, consider using "
                  "LBFGS instead"))
            self.status_label.modify_fg(gtk.STATE_NORMAL,
                                        gtk.gdk.color_parse('#AA4000'))

        else:
            # Update display to reflect succesful end of simulation.
            self.status_label.set_text(_("Calculation completed."))
            self.status_label.modify_fg(gtk.STATE_NORMAL,
                                        gtk.gdk.color_parse('#007700'))

        if results:
            self.do_fit(np.array(results))
            if self.radio_results_optimal.get_active():
                if self.minimum_ok:
                    deformation = np.diag(1.0 + self.x0 * deform_axes)
                    self.atoms.set_cell(np.dot(undef_cell, deformation),
                                        scale_atoms=True)
                    if self.radio_relax_on.get_active():
                        if self.gui.simulation.has_key('progress'):
                            self.gui.simulation['progress'].set_scale_progress(
                                len(steps))
                        algo = getattr(ase.optimize, mininame)
                        minimizer = algo(self.atoms, logfile=logger)
                        minimizer.run(fmax=fmax, steps=self.steps.value)
                    # Store the optimal configuration.
                    self.prepare_store_atoms()
                    self.store_atoms()
                    stored_atoms = True
                else:
                    oops(_("No trustworthy minimum: Old configuration kept."))
            self.activate_output()
            if stored_atoms:
                self.gui.notify_vulnerable()
        self.end()

        # If we store all configurations: Open movie window and energy graph
        if stored_atoms and self.gui.images.nimages > 1:
            self.gui.movie()
            assert not np.isnan(self.gui.images.E[0])
            if not self.gui.plot_graphs_newatoms():
                expr = 'i, e - E[-1]'
                self.gui.plot_graphs(expr=expr)
            # Continuations should use the best image
            nbest = np.argmin(np.array(results)[:, 1])
            self.start_nth_adj.value = nbest