Ejemplo n.º 1
0
def main():
    #Read in XYZ file. Store all the coordinates.
    simulation_atoms = XYZ()
    simulation_atoms.load(structure_file) #simulation_atoms.rows contains the data
    print 'Structure file loaded successfully: '+structure_file
    
    #Read in connection table (ReaxFF fort.7 style, see ReaxFF manual for more info)
    connection_table = Connection_Table()
    connection_table.load(connection_table_file)
    print 'Connection table file loaded successfully: '+connection_table_file

    #The molecule helper class provides methods for working with both the XYZ
    #and connection table classes.
    molecule_helper = Molecule_Helper()
    molecule_helper.simulation_atoms_class = simulation_atoms
    molecule_helper.connection_table_class = connection_table
    molecule_helper.bondorder_cutoff = bondorder_cutoff
    
    print
    print 'List of molecules for the bond order: '+str(bondorder_cutoff)
    print
    
    for each_connection_table in connection_table:
        all_molecules = molecule_helper.get_all_molecules()
        molecules_dict = molecule_helper.molecule_list_to_frequency_dict(all_molecules)
        
        print 'Iteration: '+str(connection_table.iteration)
        print '------------------------------------------------------'
        for molecule_formula, molecule_freq in molecules_dict.iteritems():
            print str(molecule_freq)+' x '+molecule_formula
        print
Ejemplo n.º 2
0
def main():
    #Read in XYZ file. Store all the coordinates.
    simulation_atoms = XYZ()
    simulation_atoms.load(
        structure_file)  #simulation_atoms.rows contains the data
    print 'Structure file loaded successfully: ' + structure_file

    #Read in connection table (ReaxFF fort.7 style, see ReaxFF manual for more info)
    connection_table = Connection_Table()
    connection_table.load(connection_table_file)
    print 'Connection table file loaded successfully: ' + connection_table_file

    #The molecule helper class provides methods for working with both the XYZ
    #and connection table classes.
    molecule_helper = Molecule_Helper()
    molecule_helper.simulation_atoms_class = simulation_atoms
    molecule_helper.connection_table_class = connection_table
    molecule_helper.bondorder_cutoff = bondorder_cutoff

    print
    print 'List of molecules for the bond order: ' + str(bondorder_cutoff)
    print

    for each_connection_table in connection_table:
        all_molecules = molecule_helper.get_all_molecules()
        molecules_dict = molecule_helper.molecule_list_to_frequency_dict(
            all_molecules)

        print 'Iteration: ' + str(connection_table.iteration)
        print '------------------------------------------------------'
        for molecule_formula, molecule_freq in molecules_dict.iteritems():
            print str(molecule_freq) + ' x ' + molecule_formula
        print
Ejemplo n.º 3
0
 def XYZ(self):
     self.xyzpop = XYZ(df=self.model._df)
     try:
         self.xyzpop.Magic()
         self.xyzpop.show()
     except (KeyError):
         self.ErrorEvent()
Ejemplo n.º 4
0
def tests():
    # Currently assume some relative path stuff. This is apt to change once we
    # make this into a module.
    sys.path.insert(0, "..")  # Make this the first thing since we want to override
    from XYZ import XYZ  # XYZ class
    from reax_connection_table import Connection_Table

    # Test files location:
    structure_file = "tests/a10a_ph7.xyz"
    connection_table_file = "tests/a10a_ph7.connect"

    # Read in XYZ file. Store all the coordinates.
    simulation_atoms = XYZ()
    simulation_atoms.load(structure_file)  # simulation_atoms.rows contains the data
    print "Structure file loaded successfully: " + structure_file

    # Read in connection table (ReaxFF fort.7 style, see ReaxFF manual for more info)
    connection_table = Connection_Table()
    connection_table.load(connection_table_file)
    connection_table.next()
    print "Connection table file loaded successfully: " + connection_table_file

    molecule_helper = Molecule_Helper()
    molecule_helper.simulation_atoms_class = simulation_atoms
    molecule_helper.connection_table_class = connection_table
    molecule_helper.bondorder_cutoff = 0.6

    assert molecule_helper.atom_label_list_to_formula(["H", "O", "H"]) == "H2O"
    # print molecule_helper.atom_label_list_to_formula(['H', 'O', 'H'])
    assert molecule_helper.atom_label_list_to_formula(["H"]) == "H"
    assert molecule_helper.atom_label_list_to_formula(["H", "H", "Ti", "O", "Ti", "P"]) == "H2OPTi2"

    all_molecules = molecule_helper.get_all_molecules()
    # We compare this to molfra.out file generated by ReaxFF with bond order
    # cutoff of 0.6
    assert molecule_helper.molecule_list_to_frequency_dict(all_molecules) == {
        "HO20Ti10": 1,
        "H2O81Ti40": 1,
        "H3O41Ti20": 1,
        "H2O": 149,
        "O20Ti10": 6,
        "HO": 1,
        "H2O40Ti20": 1,
        "HO21Ti10": 3,
    }

    print "All tests completed successfully!"
    sys.exit(0)
Ejemplo n.º 5
0
def includeall_isolate_grouped_reaction(each_grouped_reaction):
    '''
    Given a grouped reaction, will isolate the atoms based on the 'includeall'
    critera (all molecules in this grouped reaction over the entire iteration
    range will be kept).

    NOTE: This function depends on grouped_reactions and molecule_helper being
          global.
    '''
    molecule_numbers = get_all_unique_molecule_numbers(each_grouped_reaction)
    iterations = get_all_iterations(each_grouped_reaction)

    #We will find the range of iterations we need to operate over:
    start_iteration = iterations[0]
    end_iteration = iterations[-1]

    #Get all the atom numbers in the molecules involved in this reaction
    #pathway.
    atom_numbers = get_all_unique_atoms_for_molecule_numbers(
        molecule_helper, molecule_numbers)
    atom_numbers = set(atom_numbers)  #Make into set so we can do quick lookups

    #Now we go through all the iterations in the appended XYZ file (xmolout)
    #and isolate these molecules. We do this by getting all the atoms in the
    #molecules we want to isolate. Then simply keep those atoms and delete
    #all other ones.
    xmolout = XYZ()
    xmolout.load(appendedxyz_file)

    new_xyz = XYZ()  #We will use this to write our isolated XYZ structure.

    for each_xyz in xmolout:
        print '.',

        #Check if we are in the range of iterations that are grouped reactions
        #are defined for:
        if xmolout.iteration < start_iteration or \
           xmolout.iteration > end_iteration:
            continue  #skip this iteration

        new_xyz.rows = []
        #Compare each atom to our atom numbers.
        for i, atom in enumerate(each_xyz):
            each_xyz_atom_number = i + 1  #Since atom numbers start at 1 not 0.
            if each_xyz_atom_number in atom_numbers:
                new_xyz.rows.append(atom)
        #Now append this new xyz to our output file:
        output_xyz_filename = appendedxyz_output_file.replace(
            '[grouped_reaction_number]',
            str(grouped_reactions.grouped_reaction_number))
        new_xyz.export(output_xyz_filename, append=True)
Ejemplo n.º 6
0
def tests():
    #Currently assume some relative path stuff. This is apt to change once we
    #make this into a module.
    sys.path.insert(0, "..") #Make this the first thing since we want to override
    from XYZ import XYZ #XYZ class
    from reax_connection_table import Connection_Table
   
    #Test files location:
    structure_file = 'tests/a10a_ph7.xyz'
    connection_table_file = 'tests/a10a_ph7.connect'

    #Read in XYZ file. Store all the coordinates.
    simulation_atoms = XYZ()
    simulation_atoms.load(structure_file) #simulation_atoms.rows contains the data
    print 'Structure file loaded successfully: '+structure_file
    
    #Read in connection table (ReaxFF fort.7 style, see ReaxFF manual for more info)
    connection_table = Connection_Table()
    connection_table.load(connection_table_file)
    connection_table.next()
    print 'Connection table file loaded successfully: '+connection_table_file

    molecule_helper = Molecule_Helper()
    molecule_helper.simulation_atoms_class = simulation_atoms
    molecule_helper.connection_table_class = connection_table
    molecule_helper.bondorder_cutoff = 0.6

    assert molecule_helper.atom_label_list_to_formula(['H', 'O', 'H']) == 'H2O'
    #print molecule_helper.atom_label_list_to_formula(['H', 'O', 'H'])
    assert molecule_helper.atom_label_list_to_formula(['H']) == 'H'
    assert molecule_helper.atom_label_list_to_formula(['H', 'H', 'Ti', 'O', 'Ti', 'P']) == 'H2OPTi2'

    all_molecules = molecule_helper.get_all_molecules()
    #We compare this to molfra.out file generated by ReaxFF with bond order
    #cutoff of 0.6
    assert molecule_helper.molecule_list_to_frequency_dict(all_molecules) == \
        {'HO20Ti10': 1, 'H2O81Ti40': 1, 'H3O41Ti20': 1, 'H2O': 149, 'O20Ti10': 6, 'HO': 1, 'H2O40Ti20': 1, 'HO21Ti10': 3}
    
    print 'All tests completed successfully!'
    sys.exit(0)
def includeall_isolate_grouped_reaction(each_grouped_reaction):
    '''
    Given a grouped reaction, will isolate the atoms based on the 'includeall'
    critera (all molecules in this grouped reaction over the entire iteration
    range will be kept).

    NOTE: This function depends on grouped_reactions and molecule_helper being
          global.
    '''
    molecule_numbers = get_all_unique_molecule_numbers(each_grouped_reaction)
    iterations = get_all_iterations(each_grouped_reaction)
    
    #We will find the range of iterations we need to operate over:
    start_iteration = iterations[0]
    end_iteration = iterations[-1]
    
    #Get all the atom numbers in the molecules involved in this reaction
    #pathway.
    atom_numbers = get_all_unique_atoms_for_molecule_numbers(
                    molecule_helper, molecule_numbers
                   )
    atom_numbers = set(atom_numbers) #Make into set so we can do quick lookups
    
    #Now we go through all the iterations in the appended XYZ file (xmolout)
    #and isolate these molecules. We do this by getting all the atoms in the
    #molecules we want to isolate. Then simply keep those atoms and delete
    #all other ones.
    xmolout = XYZ()
    xmolout.load(appendedxyz_file)
    
    new_xyz = XYZ() #We will use this to write our isolated XYZ structure.

    for each_xyz in xmolout:
        print '.',
        
        #Check if we are in the range of iterations that are grouped reactions
        #are defined for:
        if xmolout.iteration < start_iteration or \
           xmolout.iteration > end_iteration:
            continue #skip this iteration

        new_xyz.rows = []
        #Compare each atom to our atom numbers.
        for i, atom in enumerate(each_xyz):
            each_xyz_atom_number = i+1 #Since atom numbers start at 1 not 0.
            if each_xyz_atom_number in atom_numbers:
                new_xyz.rows.append(atom)
        #Now append this new xyz to our output file:
        output_xyz_filename = appendedxyz_output_file.replace(
                                '[grouped_reaction_number]',
                                str(grouped_reactions.grouped_reaction_number)
                              )
        new_xyz.export(output_xyz_filename, append=True)
Ejemplo n.º 8
0
    def read_output(self, path):
        """Method to parse output file to an ORCA object
        RETURNS:
            An ORCA object with data from output file. Data could be retreived by the class methods."""
        if not os.path.isfile(path):
            raise FileNotFoundError("Supplide output file doesn't exist")

        self._file_path = path
        # reads molecule, energy, comp. time and convergence data
        with open(path, "r") as f:
            InputBlock = False
            input_str = ""
            for line in f.readlines():
                if "INPUT FILE" in line:
                    InputBlock = True
                if "====" in line:
                    continue
                if InputBlock:
                    if ">" in line:
                        t = line.split("> ")[-1]
                        if "END OF INPUT" in t:
                            InputBlock = False
                        else:
                            input_str += t
                if "FINAL SINGLE POINT ENERGY" in line:
                    self._energy = float(line.split()[-1])
                    continue
                if "*** OPTIMIZATION RUN DONE ***" in line:
                    self.geo_converged = True
                    continue
                if "****ORCA TERMINATED NORMALLY****" in line:
                    self.terminated_normally = True
                    continue
                if "SCF CONVERGED AFTER" in line:
                    self.scf_converged = True
                    continue
                if "TOTAL RUN TIME" in line:
                    v = [line.split()[2 * i + 3] for i in range(5)]
                    self._comp_time = 24 * 60 * 60 * v[0] + \
                                           60 * 60 * v[1] + \
                                                60 * v[2] + \
                                                     v[4] + \
                                             0.001 * v[5]
                    continue
            # parsing input string
            self.read_input_str(input_str)
            # checking for final geometry
            xyz_file = os.path.splitext(path)[0] + '.xyz'
            self.molecule = XYZ.read_file(xyz_file).get_mol()
Ejemplo n.º 9
0
def exact_isolate_grouped_reaction(each_grouped_reaction):
    '''
    Given a grouped reaction, will isolate the atoms based on the 'exact'
    critera (only specific iterations that are defined will be processed and
    only the molecules defined for that iteration will be processed).

    NOTE: This function depends on grouped_reactions and molecule_helper being
          global.
    '''
    iterations = get_all_iterations(each_grouped_reaction)
    iterations = set(iterations)

    #Now we go through all the iterations in the appended XYZ file (xmolout)
    xmolout = XYZ()
    xmolout.load(appendedxyz_file)

    new_xyz = XYZ()  #We will use this to write our isolated XYZ structure.

    for each_xyz in xmolout:
        print '.',

        #Check if we are at one of the iterations in our grouped reaction list.
        #If not, then we skip:
        if xmolout.iteration not in iterations:
            continue  #skip this iteration

        #Otherwise, process this iteration, keeping ONLY the molecules defined
        #in this iteration.

        new_xyz.rows = []
        #Compare each atom to our atom numbers.
        for i, atom in enumerate(each_xyz):
            each_xyz_atom_number = i + 1  #Since atom numbers start at 1 not 0.
            if each_xyz_atom_number in atom_numbers:
                new_xyz.rows.append(atom)
        #Now append this new xyz to our output file:
        output_xyz_filename = appendedxyz_output_file.replace(
            '[grouped_reaction_number]',
            str(grouped_reactions.grouped_reaction_number))
        new_xyz.export(output_xyz_filename, append=True)
def exact_isolate_grouped_reaction(each_grouped_reaction):
    '''
    Given a grouped reaction, will isolate the atoms based on the 'exact'
    critera (only specific iterations that are defined will be processed and
    only the molecules defined for that iteration will be processed).

    NOTE: This function depends on grouped_reactions and molecule_helper being
          global.
    '''
    iterations = get_all_iterations(each_grouped_reaction)
    iterations = set(iterations)

    #Now we go through all the iterations in the appended XYZ file (xmolout)
    xmolout = XYZ()
    xmolout.load(appendedxyz_file)
    
    new_xyz = XYZ() #We will use this to write our isolated XYZ structure.

    for each_xyz in xmolout:
        print '.',
        
        #Check if we are at one of the iterations in our grouped reaction list.
        #If not, then we skip:
        if xmolout.iteration not in iterations:
            continue #skip this iteration
       
        #Otherwise, process this iteration, keeping ONLY the molecules defined
        #in this iteration.

        new_xyz.rows = []
        #Compare each atom to our atom numbers.
        for i, atom in enumerate(each_xyz):
            each_xyz_atom_number = i+1 #Since atom numbers start at 1 not 0.
            if each_xyz_atom_number in atom_numbers:
                new_xyz.rows.append(atom)
        #Now append this new xyz to our output file:
        output_xyz_filename = appendedxyz_output_file.replace(
                                '[grouped_reaction_number]',
                                str(grouped_reactions.grouped_reaction_number)
                              )
        new_xyz.export(output_xyz_filename, append=True)
Ejemplo n.º 11
0
def main():
    #Read in XYZ file. Store all the coordinates.
    simulation_atoms = XYZ()
    simulation_atoms.load(structure_file) #simulation_atoms.rows contains the data
    print 'Structure file loaded successfully: '+structure_file
    
    #Read in connection table (ReaxFF fort.7 style, see ReaxFF manual for more info)
    connection_table = Connection_Table()
    connection_table.load(connection_table_file)
    print 'Connection table file loaded successfully: '+connection_table_file

    #The molecule helper class provides methods for working with both the XYZ
    #and connection table classes.
    molecule_helper = Molecule_Helper()
    molecule_helper.simulation_atoms_class = simulation_atoms
    molecule_helper.connection_table_class = connection_table
    molecule_helper.bondorder_cutoff = bondorder_cutoff

    #Open output file for writing:
    rxns_f = file(rxns_output_file, 'w')
    
    #Pretty/Instructional Output Stuff:
    rxns_f.write('#(NOTE: The molecule numbers are printed in parentheses. '+\
                 'ie. (3). The full table of molecules will be written to '+ 
                 'a binary file.)'+"\n\n")
    
    print 'Finding reactions',

    #Loop through all iterations. We are doing a do...while type loop here:
    connection_table_current = connection_table.next()
    for connection_table_next in connection_table:
        #We say that these are the reactions for the current iteration (and not
        #'from previous iteration to this iteration' just for simplicity.
        rxns_f.write('Reaction(s) for iteration: '+str(connection_table.iteration)+"\n")
        rxns_f.write('-------------------------------------------'+"\n\n")

        #Diff the two sets of molecules based on change in bond order. Figure out
        #which atoms have bond orders that were originally below the BO cutoff and
        #are now equal to or above the BO cutoff. This gives the atoms that have
        #changed connectivity.
        changed_atoms_entries = get_atoms_that_have_connection_changes(connection_table_current,
                            connection_table_next, bondorder_cutoff)
        #Then take these atoms that have changed, and get the molecule that
        #corresponds to it. First, let's transform the output we get into just a
        #list of changed atoms. Our approach is to put all the atoms into a list.
        #Then convert it into a set since that automatically eliminates all duplicate
        #elements.
        just_changed_atoms = []
        for each_changed_atom_entry in changed_atoms_entries:
            just_changed_atoms.append(each_changed_atom_entry[0])
            just_changed_atoms.append(each_changed_atom_entry[1])
        changed_atom_numbers = set(just_changed_atoms)

        #We want to connect reactants to products. See my notebook vol 2, p99 for
        #more explanation.
        #1. Get molecule from changed atoms. First, from reactants:
        reactant_molecules = []
        connection_table.rows = connection_table_current
        for each_changed_atom_number in changed_atom_numbers:
             reactant_molecules.append(
                 molecule_helper.get_molecule_for_atom(each_changed_atom_number)
             )
        #From products:
        product_molecules = []
        connection_table.rows = connection_table_next
        for each_changed_atom_number in changed_atom_numbers:
             product_molecules.append(
                 molecule_helper.get_molecule_for_atom(each_changed_atom_number)
             )
        #Now get rid of exact duplicates:
        reactant_molecules = remove_molecule_duplicates(reactant_molecules)
        product_molecules = remove_molecule_duplicates(product_molecules)
        
        #2. Now we relate the reactants and molecules with each other by finding 
        #   common atoms between them.
        reactants_to_products_mapping = group_reactants_and_products(
                                            reactant_molecules,
                                            product_molecules
                                        )

        #Suppress molecule rearrangement if needed. We define molecule rearragement
        #as when molecules on both sides of a reaction are the same!
        if suppress_molecule_rearrangment == True:
            new_reactants_to_products_mapping = []
            for each_mapping in reactants_to_products_mapping:
                if each_mapping['reactants'] != each_mapping['products']:
                    new_reactants_to_products_mapping.append(each_mapping)
            reactants_to_products_mapping = new_reactants_to_products_mapping

        #Output chemical formulas. This is a helper function for map:
        def molecule_to_chemical_formula_wrapper(molecule):
            '''
            Allows us to pass extra args when using map.
            '''
            return molecule_helper.molecule_to_chemical_formula(
                molecule, True
            )
        for each_reaction in reactants_to_products_mapping:
            #Get chemical formula. We include the molecule number next to each
            #formula:
            reactant_formulas = map(molecule_to_chemical_formula_wrapper,
                                    each_reaction['reactants'])
            product_formulas = map(molecule_to_chemical_formula_wrapper,
                                   each_reaction['products'])

            #List to string:
            reactant_formulas = ' + '.join(reactant_formulas)
            product_formulas = ' + '.join(product_formulas)
            rxns_f.write(reactant_formulas+' -> '+product_formulas+"\n\n")
    
        #Alright, let's move on to the next iteration,
        connection_table_current = connection_table_next
        #Give some indication of progress:
        print '.',
        rxns_f.write("\n")
    
    rxns_f.close()
    print
    print 'Successfully found reactions for every i to i+1 iteration: '+\
            rxns_output_file
    
    #Now that we generated all the reactions for i and i+1, let's output the
    #molecule dictionary as a pickled file.
    molecule_helper.save_molecule_list(molecules_output_file)
    print 'Successfully saved molecule list in binary format: '+molecules_output_file
Ejemplo n.º 12
0
def main():

    #Read in XYZ file. Store all the coordinates.
    global simulation_atoms, simulation_atoms_dict
    simulation_atoms = XYZ()
    simulation_atoms.load(
        structure_file)  #simulation_atoms.rows contains the data
    simulation_atoms_dict = simulation_atoms.return_sorted_by_atoms_dict()
    #NOTE: Now we have two tables, simulation_atoms and simulation_atoms_dict

    #Read in connection table (ReaxFF fort.7 style, see ReaxFF manual for more info)
    global connection_table  #So that other functions can access this
    connection_table = Connection_Table()
    connection_table.load(connection_table_file)

    #Testing
    #tests()

    #Go through each of the target molecules and do isolation stuff:
    for target_molecule in target_molecules:
        #Select an atom to work with. We just select the first one. Used for the 'exclude'
        #case so that we don't have to check every single atom in simulation_atoms:
        an_atom = target_molecule[0]
        #Loop through all the atoms matching the an_atom type:
        for atom_number, each_atom in enumerate(simulation_atoms.rows):
            #Correction to the atom_number since XYZ list starts at 0 but atom numbers
            #start at 1:
            atom_number += 1

            #Somewhat of a hack: Do a quick check here to see if this atom has been
            #nullified in the XYZ object. If so, we can just skip it since this atom
            #has been "deleted".
            if each_atom == None:
                continue  #skip this atom since it has been deleted

            #If the isolate_method is 'include' then we have to check all atoms because
            #there are cases of single atoms and/or atoms not connected to the target
            #molecule atoms that we defined which we won't catch unless we check every
            #atom. If the isolate method is 'exclude' then we just have to check atoms that
            #are connected to an atom in the defined target molecule.
            if isolate_method == 'exclude' and each_atom[0] != an_atom:
                #Skip this atom for now. If it's part of the target molecule, we'll
                #automatically come back to it later.
                continue

            #For the current atom, get the molecule that corresponds to it:
            molecule_parts = get_molecule_for_atom(atom_number)

            #Check this molecule against our isolation specification see if match exists:
            same_molecules_q = are_molecules_the_same( \
             list(target_molecule),
             molecule_parts_to_list(molecule_parts),
             isolate_criteria
             )

            #Get the molecule numbers so that we can feed it into the nullify atoms func.
            molecule_atom_numbers = molecule_parts.keys()
            #Now keep/remove depending on criteria:
            if isolate_method == 'include':
                if same_molecules_q != True:
                    #print molecule_parts
                    #The molecules are not the same so we need to delete it
                    nullify_atoms_in_XYZ(molecule_atom_numbers)
            elif isolate_method == 'exclude':
                if same_molecules_q == True:
                    #This molecule is in the excluded list so we need to delete it
                    nullify_atoms_in_XYZ(molecule_atom_numbers)
            else:
                print 'ERROR: isolate_method option invalid!'
                sys.exit(0)

    #Cool, we now ran through the whole XYZ file. Let's save the changed version:
    simulation_atoms.export(output_xyz_file)
    print 'Processed XYZ file exported: ' + output_xyz_file
Ejemplo n.º 13
0
def main():
    #Read in XYZ file. Store all the coordinates.
    simulation_atoms = XYZ()
    simulation_atoms.load(
        structure_file)  #simulation_atoms.rows contains the data

    #Pre-sort the atoms by atom type (into a dictionary). This way, we don't
    #have to loop through the whole file every time we calculate distances for
    #a given atom.
    simulation_atoms_dict = {}
    for atom_number, each_row in enumerate(simulation_atoms.rows):
        #Correction to the atom_number since it starts at 1 instead of 0:
        atom_number += 1

        #We want our new list to be in the format:
        #atom_number x y z
        temp_list = [atom_number]  #Put it in a list first. For some reason,
        temp_list.extend(each_row[1:])  #can't combine these two on same line.

        #Now save it:
        try:
            simulation_atoms_dict[each_row[0]].append(temp_list)
        except KeyError:
            #This means that the dictionary entry for this atom has not been
            #created yet. So we create it:
            simulation_atoms_dict[each_row[0]] = [temp_list]  #New list

    #Read in connection table (ReaxFF fort.7 style, see ReaxFF manual for more info)
    connection_table = Connection_Table()
    connection_table.load(connection_table_file)

    #Loop through each pair of atoms.
    distance_histogram = {
    }  #Dictionary instead of array so we can add entries at any element.
    #TODO: I should add a try to this outer loop too to catch if from_atom
    #      doesn't exist in the dictionary
    for from_atom_row in simulation_atoms_dict[from_atom]:
        #Calculate interatomic distances. Use the minimum image convention here to
        #take care of any periodic conditions. We start by checking through all the
        #other atoms to see if they match our to_atom:
        try:
            for to_atom_row in simulation_atoms_dict[to_atom]:
                #Make sure this isn't the same atom by comparing atom number:
                if from_atom_row[0] == to_atom_row[0]:
                    continue

                #Make sure this to_atom isn't part of the same molecule. We figure
                #this out by using the molecule column of the connection table:
                if exclude_atoms_from_same_molecule:
                    if connection_table.rows[from_atom_row[0]][-1] == \
                       connection_table.rows[to_atom_row[0]][-1]:
                        #We have the same molecule. Don't do anything for this to_atom.
                        continue
                        #pass

                #Otherwise, calculate the interatomic distance:
                from_atom_coord = (from_atom_row[1], from_atom_row[2],
                                   from_atom_row[3])
                to_atom_coord = (to_atom_row[1], to_atom_row[2],
                                 to_atom_row[3])
                interatomic_distance = calc_interatomic_distance(
                    from_atom_coord, to_atom_coord)
                #print interatomic_distance

                #Now figure out which bin this distance goes in. The algorithm in
                #Simulation of Liquids by Allen (p182) differs from the algorithm in
                #Understanding Molecular Simulation by Frenkel (p86) in that Allen rounds
                #up (by adding 1) while Frenkel doesn't round up. Adri's RDF script
                #follows Allen's method. I will take the middle road and round the number:
                #(NOTE: This method is used because FORTRAN only had arrays so the bins
                #       have to be integers. We do it in this case because floats can't
                #       be exactly represented in any prog. language. So this int method
                #       is actually not too bad.
                distance_bin = int(round(interatomic_distance / bin_size))
                try:
                    #We add two for the contribution of both atoms because we just want
                    #to find the number of atoms within a certain distance of each other
                    #(also see p86 of Frenkel).
                    distance_histogram[distance_bin] += 2
                except KeyError:
                    #This is the first entry for this key. So we'll create it:
                    distance_histogram[distance_bin] = 2
        except KeyError:
            #to_atom was not found in the atoms dictionary
            print 'ERROR: ' + to_atom + ' was not found in the structure file: ' + structure_file
            sys.exit(1)

    #print distance_histogram

    #Normalize the histrogram by comparing to ideal gas.
    #We want to compute (p184 Allen):
    # g(r + 1/2 * delta_r) = n(b)/n_id(b) , no clue what b is though
    #where according to p183 Allen and corroborated by p86 Frenkel and Adri's RDF script:
    # n(b) = n_his(b)/(N * t_run)
    #In our case, we are only calculating from one static frame, so t_run = 1. The reason
    #why we divide by N is to get the "average". It sort of doesn't make sense to me since
    #this would make n(b) always fractional. But if n_id(b) is also fractional, then it
    #would work out.
    #Also according to p184 Allen:
    # n_id(b) = (4 pi rho)/3 * [(r + dr)^3 - r^3]
    #which makes sense. NOTE: To convert from the bin index to length (in angstroms) we
    #reverse what we do by multiplying by the bin_size (aka delta_r).
    #Also, rho (the number density) is defined by wikipedia and MatDL wiki as:
    # rho = N/V ; (num of particles)/(volume of system)
    #where N is the number of particles we are considering.
    #But Adri's RDF script doesn't calculate rho this way. He does some sort of ratio
    #of the two atom populations...
    #total_number_atoms = len(simulation_atoms.rows)
    number_from_atoms = len(simulation_atoms_dict[from_atom])
    number_to_atoms = len(simulation_atoms_dict[to_atom])
    if from_atom == to_atom:
        total_number_analyzed_atoms = number_from_atoms
        #No combination correction factor:
        combination_correction_factor = 1
    else:
        total_number_analyzed_atoms = number_from_atoms + number_to_atoms
        #Calculate combination correction factor. This factor allows the ideal
        #gas approx to match the number of combinations that the n_his makes.
        #For more information, see p77 of Vol 2 of my notebook.
        heterogeneous_combinations = number_from_atoms * number_to_atoms
        homogeneous_combinations = \
         (total_number_analyzed_atoms * (total_number_analyzed_atoms-1)) / 2
        combination_correction_factor = \
         heterogeneous_combinations/float(homogeneous_combinations)
    total_number_molecules = connection_table.rows[-1][-1]
    total_volume = float(unit_cell[0]) * unit_cell[1] * unit_cell[2]
    rho = total_number_analyzed_atoms / total_volume
    g = {
    }  #This is our pair correlation function results. However, have to store as bins, not angstroms

    for distance_bin, n_his in distance_histogram.iteritems():
        n = float(n_his)  #/total_number_atoms
        #n = float(n_his)/total_number_molecules
        r = float(distance_bin
                  ) * bin_size  #convert from bin index to length (angstroms)
        n_id = ((4 * math.pi * rho) / 3) * ((r + bin_size)**3 - r**3)
        #Additional correction to n_id.
        n_id *= number_from_atoms + number_to_atoms
        n_id *= combination_correction_factor

        #print n, n_id
        g[distance_bin] = n / n_id

    #Now print it out with angstroms!
    #print "r \t g(r)"
    #for distance_bin, gr in g.iteritems():
    #   #The format syntax is that we have _____._____ (5 spots before the . and 5 spots
    #   #after). This will cover like 99.99% of all numbers we encounter.
    #   print "%10.5f \t %10.5f" % (float(distance_bin) * bin_size, gr)
    #   #pass

    #Output to file:
    try:
        output_f = file(output_file, 'w')
    except (NameError, IOError):
        print 'ERROR: Could not write output to ' + output_file
        sys.exit(1)

    #Alternative method for printing it out. We print only for r <= 1/2 L, where L is
    #the average length of all the sides of the box. According to Deserno's paper on
    #calculating g(r) in 3-D, once we assume minimum image convention, the n_id term
    #no longer increases like how we defined it above. So g(r) is only accurate to 1/2 L.
    average_L = (float(unit_cell[0]) + unit_cell[1] + unit_cell[2]) / 3
    max_bin = int(round((average_L / 2) / bin_size))  #Convert to integer bin
    #print "r \t g(r)"
    output_f.write("r \t g(r)\n")
    for distance_bin in xrange(0, max_bin):
        #The format syntax is that we have _____._____ (5 spots before the . and 5 spots
        #after). This will cover like 99.99% of all numbers we encounter.
        try:
            #print "%10.5f \t %10.5f" % (float(distance_bin) * bin_size, g[distance_bin])
            output_f.write("%10.5f \t %10.5f\n" %
                           (float(distance_bin) * bin_size, g[distance_bin]))
        except KeyError:
            #g doesn't have this distance_bin entry. No worries, since we know it is zero:
            #print "%10.5f \t %10.5f" % (float(distance_bin) * bin_size, 0.0)
            output_f.write("%10.5f \t %10.5f\n" %
                           (float(distance_bin) * bin_size, 0.0))

    output_f.close()
    print 'RDF as tab separated values written to: ' + output_file

    #Add in GNUPlot input file generation. Use below for smoothing:
    '''
    plot "[rdf_tsv_file]" u 1:2 with linespoints, \
         "[rdf_tsv_file]" u 1:2 smooth bezier
    '''
    gnuplot_template = '''
reset
set title "Radial Distribution Function"
set xlabel "r (angstrom)"
set ylabel "g(r)"
set nokey
plot "[rdf_tsv_file]" u 1:2 with linespoints
set term png
set output "[output_image_file]"
replot
'''
    try:
        gnuplot_template = gnuplot_template.replace('[rdf_tsv_file]',
                                                    output_file)
        output_image_file = os.path.splitext(gnuplot_file)[0] + '.png'
        gnuplot_template = gnuplot_template.replace('[output_image_file]',
                                                    output_image_file)
        #Write to file:
        gnuplot_f = open(gnuplot_file, 'w')
        gnuplot_f.write(gnuplot_template)
        gnuplot_f.close()
        print 'GNUPlot file written to: ' + gnuplot_file

        #Now generate the graphs
        os.system('gnuplot ' + gnuplot_file)
        print 'GNUPlot graph generated!'
        time.sleep(2)
        os.system('gqview')
    except IOError:
        print 'ERROR: Could not write gnuplot file to: ' + gnuplot_file
    except NameError:
        #Do nothing
        pass
Ejemplo n.º 14
0
def main():
    #Read in XYZ file. Store all the coordinates.
    simulation_atoms = XYZ()
    simulation_atoms.load(structure_file) #simulation_atoms.rows contains the data
    
    #Pre-sort the atoms by atom type (into a dictionary). This way, we don't
    #have to loop through the whole file every time we calculate distances for
    #a given atom.
    simulation_atoms_dict = {}
    for atom_number, each_row in enumerate(simulation_atoms.rows):
        #Correction to the atom_number since it starts at 1 instead of 0:
        atom_number += 1
        
        #We want our new list to be in the format:
        #atom_number x y z
        temp_list = [atom_number] #Put it in a list first. For some reason, 
        temp_list.extend(each_row[1:]) #can't combine these two on same line.
        
        #Now save it:
        try:
            simulation_atoms_dict[each_row[0]].append(temp_list)
        except KeyError:
            #This means that the dictionary entry for this atom has not been
            #created yet. So we create it:
            simulation_atoms_dict[each_row[0]] = [temp_list] #New list
    
    #Read in connection table (ReaxFF fort.7 style, see ReaxFF manual for more info)
    connection_table = Connection_Table()
    connection_table.load(connection_table_file)
    
    #Loop through each pair of atoms.
    distance_histogram = {} #Dictionary instead of array so we can add entries at any element.
    #TODO: I should add a try to this outer loop too to catch if from_atom
    #      doesn't exist in the dictionary
    for from_atom_row in simulation_atoms_dict[from_atom]:
        #Calculate interatomic distances. Use the minimum image convention here to
        #take care of any periodic conditions. We start by checking through all the
        #other atoms to see if they match our to_atom:
        try:
            for to_atom_row in simulation_atoms_dict[to_atom]:
                #Make sure this isn't the same atom by comparing atom number:
                if from_atom_row[0] == to_atom_row[0]:
                    continue
                
                #Make sure this to_atom isn't part of the same molecule. We figure
                #this out by using the molecule column of the connection table:
                if exclude_atoms_from_same_molecule:
                    if connection_table.rows[from_atom_row[0]][-1] == \
                       connection_table.rows[to_atom_row[0]][-1]:
                        #We have the same molecule. Don't do anything for this to_atom.
                        continue
                        #pass
                
                #Otherwise, calculate the interatomic distance:
                from_atom_coord = (from_atom_row[1], from_atom_row[2], from_atom_row[3])
                to_atom_coord = (to_atom_row[1], to_atom_row[2], to_atom_row[3])
                interatomic_distance = calc_interatomic_distance(from_atom_coord, to_atom_coord)
                #print interatomic_distance
                
                #Now figure out which bin this distance goes in. The algorithm in 
                #Simulation of Liquids by Allen (p182) differs from the algorithm in
                #Understanding Molecular Simulation by Frenkel (p86) in that Allen rounds
                #up (by adding 1) while Frenkel doesn't round up. Adri's RDF script
                #follows Allen's method. I will take the middle road and round the number:
                #(NOTE: This method is used because FORTRAN only had arrays so the bins
                #       have to be integers. We do it in this case because floats can't
                #       be exactly represented in any prog. language. So this int method
                #       is actually not too bad.
                distance_bin = int(round(interatomic_distance / bin_size))
                try:
                    #We add two for the contribution of both atoms because we just want
                    #to find the number of atoms within a certain distance of each other
                    #(also see p86 of Frenkel).
                    distance_histogram[distance_bin] += 2
                except KeyError:
                    #This is the first entry for this key. So we'll create it:
                    distance_histogram[distance_bin] = 2
        except KeyError:
            #to_atom was not found in the atoms dictionary
            print 'ERROR: '+to_atom+' was not found in the structure file: '+structure_file
            sys.exit(1)
    
    #print distance_histogram

    #Normalize the histrogram by comparing to ideal gas.
    #We want to compute (p184 Allen): 
    # g(r + 1/2 * delta_r) = n(b)/n_id(b) , no clue what b is though
    #where according to p183 Allen and corroborated by p86 Frenkel and Adri's RDF script:
    # n(b) = n_his(b)/(N * t_run)
    #In our case, we are only calculating from one static frame, so t_run = 1. The reason
    #why we divide by N is to get the "average". It sort of doesn't make sense to me since
    #this would make n(b) always fractional. But if n_id(b) is also fractional, then it
    #would work out.
    #Also according to p184 Allen:
    # n_id(b) = (4 pi rho)/3 * [(r + dr)^3 - r^3]
    #which makes sense. NOTE: To convert from the bin index to length (in angstroms) we 
    #reverse what we do by multiplying by the bin_size (aka delta_r).
    #Also, rho (the number density) is defined by wikipedia and MatDL wiki as:
    # rho = N/V ; (num of particles)/(volume of system)
    #where N is the number of particles we are considering.
    #But Adri's RDF script doesn't calculate rho this way. He does some sort of ratio
    #of the two atom populations...
    #total_number_atoms = len(simulation_atoms.rows)
    number_from_atoms = len(simulation_atoms_dict[from_atom])
    number_to_atoms = len(simulation_atoms_dict[to_atom])
    if from_atom == to_atom:
        total_number_analyzed_atoms = number_from_atoms
        #No combination correction factor:
        combination_correction_factor = 1
    else:
        total_number_analyzed_atoms = number_from_atoms + number_to_atoms
        #Calculate combination correction factor. This factor allows the ideal
        #gas approx to match the number of combinations that the n_his makes.
        #For more information, see p77 of Vol 2 of my notebook.
        heterogeneous_combinations = number_from_atoms * number_to_atoms
        homogeneous_combinations = \
         (total_number_analyzed_atoms * (total_number_analyzed_atoms-1)) / 2
        combination_correction_factor = \
         heterogeneous_combinations/float(homogeneous_combinations)
    total_number_molecules = connection_table.rows[-1][-1]
    total_volume = float(unit_cell[0]) * unit_cell[1] * unit_cell[2]
    rho = total_number_analyzed_atoms/total_volume
    g = {} #This is our pair correlation function results. However, have to store as bins, not angstroms
    
    for distance_bin, n_his in distance_histogram.iteritems():
        n = float(n_his)#/total_number_atoms
        #n = float(n_his)/total_number_molecules
        r = float(distance_bin) * bin_size #convert from bin index to length (angstroms)
        n_id = ((4 * math.pi * rho)/3) * ( (r + bin_size)**3 - r**3 )
        #Additional correction to n_id.
        n_id *= number_from_atoms + number_to_atoms
        n_id *= combination_correction_factor
        
        #print n, n_id
        g[distance_bin] = n/n_id
    
    #Now print it out with angstroms!
    #print "r \t g(r)"
    #for distance_bin, gr in g.iteritems():
    #   #The format syntax is that we have _____._____ (5 spots before the . and 5 spots
    #   #after). This will cover like 99.99% of all numbers we encounter.
    #   print "%10.5f \t %10.5f" % (float(distance_bin) * bin_size, gr)
    #   #pass

    #Output to file:
    try:
        output_f = file(output_file, 'w')
    except (NameError, IOError):
        print 'ERROR: Could not write output to '+output_file
        sys.exit(1)
    
    #Alternative method for printing it out. We print only for r <= 1/2 L, where L is
    #the average length of all the sides of the box. According to Deserno's paper on
    #calculating g(r) in 3-D, once we assume minimum image convention, the n_id term 
    #no longer increases like how we defined it above. So g(r) is only accurate to 1/2 L.
    average_L = (float(unit_cell[0]) + unit_cell[1] + unit_cell[2])/3
    max_bin = int(round((average_L/2) / bin_size)) #Convert to integer bin
    #print "r \t g(r)"
    output_f.write("r \t g(r)\n")
    for distance_bin in xrange(0, max_bin):
        #The format syntax is that we have _____._____ (5 spots before the . and 5 spots
        #after). This will cover like 99.99% of all numbers we encounter.
        try:
            #print "%10.5f \t %10.5f" % (float(distance_bin) * bin_size, g[distance_bin])
            output_f.write("%10.5f \t %10.5f\n" % (float(distance_bin) * bin_size, g[distance_bin]))
        except KeyError:
            #g doesn't have this distance_bin entry. No worries, since we know it is zero:
            #print "%10.5f \t %10.5f" % (float(distance_bin) * bin_size, 0.0)
            output_f.write("%10.5f \t %10.5f\n" % (float(distance_bin) * bin_size, 0.0))

    output_f.close()
    print 'RDF as tab separated values written to: '+output_file

    #Add in GNUPlot input file generation. Use below for smoothing:
    '''
    plot "[rdf_tsv_file]" u 1:2 with linespoints, \
         "[rdf_tsv_file]" u 1:2 smooth bezier
    '''
    gnuplot_template = '''
reset
set title "Radial Distribution Function"
set xlabel "r (angstrom)"
set ylabel "g(r)"
set nokey
plot "[rdf_tsv_file]" u 1:2 with linespoints
set term png
set output "[output_image_file]"
replot
'''
    try:
        gnuplot_template = gnuplot_template.replace('[rdf_tsv_file]', output_file)
        output_image_file = os.path.splitext(gnuplot_file)[0]+'.png'
        gnuplot_template = gnuplot_template.replace('[output_image_file]', output_image_file)
        #Write to file:
        gnuplot_f = open(gnuplot_file, 'w')
        gnuplot_f.write(gnuplot_template)
        gnuplot_f.close()
        print 'GNUPlot file written to: '+gnuplot_file

        #Now generate the graphs
        os.system('gnuplot '+gnuplot_file)
        print 'GNUPlot graph generated!'
        time.sleep(2)
        os.system('gqview')
    except IOError:
        print 'ERROR: Could not write gnuplot file to: '+gnuplot_file
    except NameError:
        #Do nothing
        pass
Ejemplo n.º 15
0
class Ui_MainWindow(QtWidgets.QMainWindow):
    # raw=0
    raw = pd.DataFrame(index=[],
                       columns=[])  # raw is initialized as a blank dataframe

    Language = ''

    app = QtWidgets.QApplication(sys.argv)
    myStyle = MyProxyStyle(
        'Fusion')  # The proxy style should be based on an existing style,
    # like 'Windows', 'Motif', 'Plastique', 'Fusion', ...
    app.setStyle(myStyle)

    trans = QtCore.QTranslator()

    talk = ''

    targetversion = '0'

    def __init__(self):

        super(Ui_MainWindow, self).__init__()
        self.setObjectName('MainWindow')
        self.resize(800, 600)

        _translate = QtCore.QCoreApplication.translate
        self.setWindowTitle(_translate('MainWindow', u'GeoPython'))
        self.setWindowIcon(QIcon(LocationOfMySelf + '/geopython.png'))
        self.talk = _translate(
            'MainWindow',
            'You are using GeoPython ') + version + '\n' + _translate(
                'MainWindow', 'released on ') + date

        self.model = PandasModel(self.raw)

        self.main_widget = QWidget(self)

        self.centralwidget = QtWidgets.QWidget()
        self.centralwidget.setObjectName('centralwidget')
        self.setCentralWidget(self.centralwidget)

        self.tableView = CustomQTableView(self.centralwidget)

        self.tableView.setObjectName('tableView')
        self.tableView.setSortingEnabled(True)

        self.pushButtonOpen = QtWidgets.QPushButton(self.centralwidget)
        self.pushButtonOpen.setObjectName('pushButtonOpen')

        self.pushButtonSave = QtWidgets.QPushButton(self.centralwidget)
        self.pushButtonSave.setObjectName('pushButtonSave')

        self.pushButtonSort = QtWidgets.QPushButton(self.centralwidget)
        self.pushButtonSort.setObjectName('pushButtonSort')

        self.pushButtonQuit = QtWidgets.QPushButton(self.centralwidget)
        self.pushButtonQuit.setObjectName('pushButtonQuit')

        self.pushButtonUpdate = QtWidgets.QPushButton(self.centralwidget)
        self.pushButtonUpdate.setObjectName('pushButtonUpdate')

        w = self.width()
        h = self.height()

        if h < 360:
            h = 360
            self.resize(w, h)

        if w < 640:
            w = 640
            self.resize(w, h)

        step = (w * 94 / 100) / 5
        foot = h * 3 / 48

        #if foot<=10: foot=10

        self.tableView.setGeometry(
            QtCore.QRect(w / 100, h / 48, w * 98 / 100, h * 38 / 48))

        self.pushButtonOpen.setGeometry(
            QtCore.QRect(w / 100, h * 40 / 48, step, foot))

        self.pushButtonSave.setGeometry(
            QtCore.QRect(2 * w / 100 + step, h * 40 / 48, step, foot))

        self.pushButtonSort.setGeometry(
            QtCore.QRect(3 * w / 100 + step * 2, h * 40 / 48, step, foot))

        self.pushButtonQuit.setGeometry(
            QtCore.QRect(4 * w / 100 + step * 3, h * 40 / 48, step, foot))

        self.pushButtonUpdate.setGeometry(
            QtCore.QRect(5 * w / 100 + step * 4, h * 40 / 48, step, foot))

        self.menubar = QtWidgets.QMenuBar(self)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 1000, 22))
        self.menubar.setNativeMenuBar(True)
        self.menubar.setObjectName('menubar')

        self.menuFile = QtWidgets.QMenu(self.menubar)
        self.menuFile.setObjectName('menuFile')

        self.menuGeoChem = QtWidgets.QMenu(self.menubar)
        self.menuGeoChem.setObjectName('menuGeoChem')

        self.menuStructure = QtWidgets.QMenu(self.menubar)
        self.menuStructure.setObjectName('menuStructure')

        self.menuCalc = QtWidgets.QMenu(self.menubar)
        self.menuCalc.setObjectName('menuCalc')

        self.menuStat = QtWidgets.QMenu(self.menubar)
        self.menuStat.setObjectName('menuStat')

        self.menuMore = QtWidgets.QMenu(self.menubar)
        self.menuMore.setObjectName('menuMore')

        self.menuHelp = QtWidgets.QMenu(self.menubar)
        self.menuHelp.setObjectName('menuHelp')

        self.menuLanguage = QtWidgets.QMenu(self.menubar)
        self.menuLanguage.setObjectName('menuLanguage')

        self.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(self)
        self.statusbar.setObjectName('statusbar')
        self.setStatusBar(self.statusbar)

        self.actionOpen = QtWidgets.QAction(
            QIcon(LocationOfMySelf + '/open.png'), u'Open', self)
        self.actionOpen.setObjectName('actionOpen')
        self.actionOpen.setShortcut('Ctrl+O')

        self.actionSave = QtWidgets.QAction(
            QIcon(LocationOfMySelf + '/save.png'), u'Save', self)
        self.actionSave.setObjectName('actionSave')
        self.actionSave.setShortcut('Ctrl+S')

        self.actionCnWeb = QtWidgets.QAction(
            QIcon(LocationOfMySelf + '/forum.png'), u'Chinese Forum', self)
        self.actionCnWeb.setObjectName('actionCnWeb')

        self.actionEnWeb = QtWidgets.QAction(
            QIcon(LocationOfMySelf + '/forum.png'), u'English Forum', self)
        self.actionEnWeb.setObjectName('actionEnWeb')

        self.actionGoGithub = QtWidgets.QAction(
            QIcon(LocationOfMySelf + '/github.png'), u'GitHub', self)
        self.actionGoGithub.setObjectName('actionGoGithub')

        self.actionVersionCheck = QtWidgets.QAction(
            QIcon(LocationOfMySelf + '/update.png'), u'Version', self)
        self.actionVersionCheck.setObjectName('actionVersionCheck')

        self.actionCnS = QtWidgets.QAction(
            QIcon(LocationOfMySelf + '/cns.png'), u'Simplified Chinese', self)
        self.actionCnS.setObjectName('actionCnS')

        self.actionCnT = QtWidgets.QAction(
            QIcon(LocationOfMySelf + '/cnt.png'), u'Traditional Chinese', self)
        self.actionCnT.setObjectName('actionCnT')

        self.actionEn = QtWidgets.QAction(QIcon(LocationOfMySelf + '/en.png'),
                                          u'English', self)
        self.actionEn.setObjectName('actionEn')

        self.actionLoadLanguage = QtWidgets.QAction(
            QIcon(LocationOfMySelf + '/lang.png'), u'Load Language', self)
        self.actionLoadLanguage.setObjectName('actionLoadLanguage')

        self.actionTAS = QtWidgets.QAction(QIcon(LocationOfMySelf + '/xy.png'),
                                           u'TAS', self)
        self.actionTAS.setObjectName('actionTAS')

        self.actionTrace = QtWidgets.QAction(
            QIcon(LocationOfMySelf + '/spider2.png'), u'Trace', self)
        self.actionTrace.setObjectName('actionTrace')

        self.actionRee = QtWidgets.QAction(
            QIcon(LocationOfMySelf + '/spider2.png'), u'Ree', self)
        self.actionRee.setObjectName('actionRee')

        self.actionPearce = QtWidgets.QAction(
            QIcon(LocationOfMySelf + '/spider.png'), u'Pearce', self)
        self.actionPearce.setObjectName('actionPearce')

        self.actionHarker = QtWidgets.QAction(
            QIcon(LocationOfMySelf + '/spider.png'), u'Harker', self)
        self.actionHarker.setObjectName('actionHarker')

        self.actionStereo = QtWidgets.QAction(
            QIcon(LocationOfMySelf + '/structure.png'), u'Stereo', self)
        self.actionStereo.setObjectName('actionStereo')

        self.actionRose = QtWidgets.QAction(
            QIcon(LocationOfMySelf + '/rose.png'), u'Rose', self)
        self.actionRose.setObjectName('actionRose')

        self.actionQFL = QtWidgets.QAction(
            QIcon(LocationOfMySelf + '/triangular.png'), u'QFL', self)
        self.actionQFL.setObjectName('actionQFL')

        self.actionQmFLt = QtWidgets.QAction(
            QIcon(LocationOfMySelf + '/triangular.png'), u'QmFLt', self)
        self.actionQmFLt.setObjectName('actionQmFLt')

        self.actionCIPW = QtWidgets.QAction(
            QIcon(LocationOfMySelf + '/calc.png'), u'CIPW', self)
        self.actionCIPW.setObjectName('actionCIPW')

        self.actionZirconCe = QtWidgets.QAction(
            QIcon(LocationOfMySelf + '/calc.png'), u'ZirconCe', self)
        self.actionZirconCe.setObjectName('actionZirconCe')

        self.actionZirconTiTemp = QtWidgets.QAction(
            QIcon(LocationOfMySelf + '/temperature.png'), u'ZirconTiTemp',
            self)
        self.actionZirconTiTemp.setObjectName('actionZirconTiTemp')

        self.actionRutileZrTemp = QtWidgets.QAction(
            QIcon(LocationOfMySelf + '/temperature.png'), u'RutileZrTemp',
            self)
        self.actionRutileZrTemp.setObjectName('actionRutileZrTemp')

        self.actionCluster = QtWidgets.QAction(
            QIcon(LocationOfMySelf + '/cluster.png'), u'Cluster', self)
        self.actionCluster.setObjectName('actionCluster')

        self.actionMultiDimention = QtWidgets.QAction(
            QIcon(LocationOfMySelf + '/multiple.png'), u'MultiDimention', self)
        self.actionMultiDimention.setObjectName('actionMultiDimention')

        self.actionQAPF = QtWidgets.QAction(
            QIcon(LocationOfMySelf + '/qapf.png'), u'QAPF', self)
        self.actionQAPF.setObjectName('actionQAPF')

        self.actionMudStone = QtWidgets.QAction(
            QIcon(LocationOfMySelf + '/triangular.png'), u'MudStone', self)
        self.actionMudStone.setObjectName('actionMudStone')

        self.actionXY = QtWidgets.QAction(QIcon(LocationOfMySelf + '/xy.png'),
                                          u'X-Y', self)
        self.actionXY.setObjectName('actionXY')

        self.actionXYZ = QtWidgets.QAction(
            QIcon(LocationOfMySelf + '/triangular.png'), u'Triangular', self)
        self.actionXYZ.setObjectName('actionXYZ')

        self.actionMagic = QtWidgets.QAction(
            QIcon(LocationOfMySelf + '/magic.png'), u'Magic', self)
        self.actionMagic.setObjectName('actionMagic')

        self.menuFile.addAction(self.actionOpen)
        self.menuFile.addAction(self.actionSave)

        self.menuGeoChem.addAction(self.actionTAS)
        self.menuGeoChem.addAction(self.actionTrace)
        self.menuGeoChem.addAction(self.actionRee)
        self.menuGeoChem.addAction(self.actionPearce)
        self.menuGeoChem.addAction(self.actionHarker)

        self.menuStructure.addAction(self.actionStereo)
        self.menuStructure.addAction(self.actionRose)
        self.menuStructure.addAction(self.actionQFL)
        self.menuStructure.addAction(self.actionQmFLt)

        self.menuCalc.addAction(self.actionCIPW)
        self.menuCalc.addAction(self.actionZirconCe)
        self.menuCalc.addAction(self.actionZirconTiTemp)
        self.menuCalc.addAction(self.actionRutileZrTemp)

        self.menuStat.addAction(self.actionCluster)
        self.menuStat.addAction(self.actionMultiDimention)

        self.menuMore.addAction(self.actionMudStone)
        self.menuMore.addAction(self.actionQAPF)

        self.menuMore.addAction(self.actionXY)
        self.menuMore.addAction(self.actionXYZ)
        self.menuMore.addAction(self.actionMagic)

        self.menuHelp.addAction(self.actionCnWeb)
        self.menuHelp.addAction(self.actionEnWeb)

        self.menuHelp.addAction(self.actionGoGithub)
        self.menuHelp.addAction(self.actionVersionCheck)

        self.menuLanguage.addAction(self.actionCnS)
        self.menuLanguage.addAction(self.actionCnT)
        self.menuLanguage.addAction(self.actionEn)
        self.menuLanguage.addAction(self.actionLoadLanguage)

        self.menubar.addAction(self.menuFile.menuAction())
        self.menubar.addSeparator()

        self.menubar.addAction(self.menuGeoChem.menuAction())
        self.menubar.addSeparator()

        self.menubar.addAction(self.menuStructure.menuAction())
        self.menubar.addSeparator()

        self.menubar.addAction(self.menuCalc.menuAction())
        self.menubar.addSeparator()

        self.menubar.addAction(self.menuStat.menuAction())
        self.menubar.addSeparator()

        self.menubar.addAction(self.menuMore.menuAction())
        self.menubar.addSeparator()

        self.menubar.addAction(self.menuHelp.menuAction())
        self.menubar.addSeparator()

        self.menubar.addAction(self.menuLanguage.menuAction())
        self.menubar.addSeparator()

        self.actionTAS.triggered.connect(self.TAS)
        self.actionTrace.triggered.connect(self.Trace)
        self.actionRee.triggered.connect(self.REE)
        self.actionPearce.triggered.connect(self.Pearce)
        self.actionHarker.triggered.connect(self.Harker)
        self.actionQAPF.triggered.connect(self.QAPF)

        self.actionStereo.triggered.connect(self.Stereo)
        self.actionRose.triggered.connect(self.Rose)
        self.actionQFL.triggered.connect(self.QFL)
        self.actionQmFLt.triggered.connect(self.QmFLt)

        self.actionCIPW.triggered.connect(self.CIPW)
        self.actionZirconCe.triggered.connect(self.ZirconCe)
        self.actionZirconTiTemp.triggered.connect(self.ZirconTiTemp)
        self.actionRutileZrTemp.triggered.connect(self.RutileZrTemp)
        self.actionCluster.triggered.connect(self.Cluster)
        self.actionMultiDimention.triggered.connect(self.MultiDimension)

        self.actionOpen.triggered.connect(self.getDataFile)
        self.actionSave.triggered.connect(self.saveDataFile)

        self.actionCnWeb.triggered.connect(self.goCnBBS)
        self.actionEnWeb.triggered.connect(self.goEnBBS)
        self.actionGoGithub.triggered.connect(self.goGitHub)
        self.actionVersionCheck.triggered.connect(self.checkVersion)

        self.actionCnS.triggered.connect(self.to_ChineseS)
        self.actionCnT.triggered.connect(self.to_ChineseT)
        self.actionEn.triggered.connect(self.to_English)
        self.actionLoadLanguage.triggered.connect(self.to_LoadLanguage)

        self.actionXY.triggered.connect(self.XY)
        self.actionXYZ.triggered.connect(self.XYZ)
        self.actionMagic.triggered.connect(self.Magic)
        self.actionMudStone.triggered.connect(self.Mud)

        self.pushButtonOpen.clicked.connect(self.getDataFile)
        self.pushButtonSave.clicked.connect(self.saveDataFile)
        self.pushButtonSort.clicked.connect(self.SetUpDataFile)
        self.pushButtonQuit.clicked.connect(qApp.quit)
        self.pushButtonUpdate.clicked.connect(self.checkVersion)

        self.actionQuit = QtWidgets.QAction('Quit', self)
        self.actionQuit.setShortcut('Ctrl+Q')
        self.actionQuit.setObjectName('actionQuit')
        self.actionQuit.triggered.connect(qApp.quit)

        self.pushButtonOpen.setText(_translate('MainWindow', u'Open Data'))
        self.pushButtonSave.setText(_translate('MainWindow', u'Save Data'))
        self.pushButtonSort.setText(_translate('MainWindow', u'Set Format'))
        self.pushButtonQuit.setText(_translate('MainWindow', u'Quit App'))
        self.pushButtonUpdate.setText(_translate('MainWindow',
                                                 u'Check Update'))

        self.pushButtonOpen.setIcon(QtGui.QIcon(LocationOfMySelf +
                                                '/open.png'))
        self.pushButtonSave.setIcon(QtGui.QIcon(LocationOfMySelf +
                                                '/save.png'))
        self.pushButtonSort.setIcon(QtGui.QIcon(LocationOfMySelf + '/set.png'))
        self.pushButtonQuit.setIcon(QtGui.QIcon(LocationOfMySelf +
                                                '/quit.png'))
        self.pushButtonUpdate.setIcon(
            QtGui.QIcon(LocationOfMySelf + '/update.png'))

        self.menuFile.setTitle(_translate('MainWindow', u'Data File'))

        self.menuGeoChem.setTitle(_translate('MainWindow', u'Geochemistry'))

        self.menuStructure.setTitle(_translate('MainWindow', u'Structure'))

        self.menuCalc.setTitle(_translate('MainWindow', u'Calculation'))

        self.menuStat.setTitle(_translate('MainWindow', u'Statistics'))

        self.menuMore.setTitle(_translate('MainWindow', u'Others'))

        self.menuHelp.setTitle(_translate('MainWindow', u'Help'))

        self.menuLanguage.setTitle(_translate('MainWindow', u'Language'))

        self.actionOpen.setText(_translate('MainWindow', u'Open Data'))
        self.actionSave.setText(_translate('MainWindow', u'Save Data'))

        self.actionTAS.setText(_translate('MainWindow', u'TAS'))
        self.actionTrace.setText(_translate('MainWindow', u'Trace'))
        self.actionRee.setText(_translate('MainWindow', u'REE'))
        self.actionPearce.setText(_translate('MainWindow', u'Pearce'))
        self.actionHarker.setText(_translate('MainWindow', u'Harker'))

        self.actionQAPF.setText(_translate('MainWindow', u'QAPF'))

        self.actionStereo.setText(_translate('MainWindow', u'Stereo'))
        self.actionRose.setText(_translate('MainWindow', u'Rose'))
        self.actionQFL.setText(_translate('MainWindow', u'QFL'))
        self.actionQmFLt.setText(_translate('MainWindow', u'QmFLt'))

        self.actionCIPW.setText(_translate('MainWindow', u'CIPW'))

        self.actionZirconCe.setText(_translate('MainWindow', u'ZirconCe'))
        self.actionZirconTiTemp.setText(
            _translate('MainWindow', u'ZirconTiTemp'))
        self.actionRutileZrTemp.setText(
            _translate('MainWindow', u'RutileZrTemp'))
        self.actionCluster.setText(_translate('MainWindow', u'Cluster'))
        self.actionMultiDimention.setText(
            _translate('MainWindow', u'MultiDimention'))

        self.actionXY.setText(_translate('MainWindow', u'X-Y plot'))
        self.actionXYZ.setText(_translate('MainWindow', u'X-Y-Z plot'))

        self.actionMagic.setText(_translate('MainWindow', u'Magic'))

        self.actionMudStone.setText(_translate('MainWindow', u'Sand-Silt-Mud'))

        self.actionVersionCheck.setText(_translate('MainWindow', u'Version'))
        self.actionCnWeb.setText(_translate('MainWindow', u'Chinese Forum'))
        self.actionEnWeb.setText(_translate('MainWindow', u'English Forum'))
        self.actionGoGithub.setText(_translate('MainWindow', u'Github'))

        self.actionCnS.setText(_translate('MainWindow', u'Simplified Chinese'))
        self.actionCnT.setText(_translate('MainWindow',
                                          u'Traditional Chinese'))
        self.actionEn.setText(_translate('MainWindow', u'English'))
        self.actionLoadLanguage.setText(
            _translate('MainWindow', u'Load Language'))

        self.ReadConfig()

        self.trans.load(LocationOfMySelf + '/' + self.Language)
        self.app.installTranslator(self.trans)
        self.retranslateUi()

    def retranslateUi(self):

        _translate = QtCore.QCoreApplication.translate

        self.talk = _translate(
            'MainWindow',
            'You are using GeoPython ') + version + '\n' + _translate(
                'MainWindow', 'released on ') + date + '\n'

        self.pushButtonOpen.setText(_translate('MainWindow', u'Open Data'))
        self.pushButtonSave.setText(_translate('MainWindow', u'Save Data'))
        self.pushButtonSort.setText(_translate('MainWindow', u'Set Format'))
        self.pushButtonQuit.setText(_translate('MainWindow', u'Quit App'))
        self.pushButtonUpdate.setText(_translate('MainWindow',
                                                 u'Check Update'))

        self.menuFile.setTitle(_translate('MainWindow', u'Data File'))

        self.menuGeoChem.setTitle(_translate('MainWindow', u'Geochemistry'))

        self.menuStructure.setTitle(_translate('MainWindow', u'Structure'))

        self.menuCalc.setTitle(_translate('MainWindow', u'Calculation'))

        self.menuStat.setTitle(_translate('MainWindow', u'Statistics'))

        self.menuMore.setTitle(_translate('MainWindow', u'Others'))

        self.menuHelp.setTitle(_translate('MainWindow', u'Help'))
        self.menuLanguage.setTitle(_translate('MainWindow', u'Language'))

        self.actionOpen.setText(_translate('MainWindow', u'Open Data'))
        self.actionSave.setText(_translate('MainWindow', u'Save Data'))

        self.actionTAS.setText(_translate('MainWindow', u'TAS'))
        self.actionTrace.setText(_translate('MainWindow', u'Trace'))
        self.actionRee.setText(_translate('MainWindow', u'REE'))
        self.actionPearce.setText(_translate('MainWindow', u'Pearce'))
        self.actionHarker.setText(_translate('MainWindow', u'Harker'))

        self.actionQAPF.setText(_translate('MainWindow', u'QAPF'))

        self.actionStereo.setText(_translate('MainWindow', u'Stereo'))
        self.actionRose.setText(_translate('MainWindow', u'Rose'))
        self.actionQFL.setText(_translate('MainWindow', u'QFL'))
        self.actionQmFLt.setText(_translate('MainWindow', u'QmFLt'))

        self.actionCIPW.setText(_translate('MainWindow', u'CIPW'))

        self.actionZirconCe.setText(_translate('MainWindow', u'ZirconCe'))
        self.actionZirconTiTemp.setText(
            _translate('MainWindow', u'ZirconTiTemp'))
        self.actionRutileZrTemp.setText(
            _translate('MainWindow', u'RutileZrTemp'))
        self.actionCluster.setText(_translate('MainWindow', u'Cluster'))
        self.actionMultiDimention.setText(
            _translate('MainWindow', u'MultiDimention'))

        self.actionXY.setText(_translate('MainWindow', u'X-Y plot'))
        self.actionXYZ.setText(_translate('MainWindow', u'X-Y-Z plot'))

        self.actionMagic.setText(_translate('MainWindow', u'Magic'))

        self.actionMudStone.setText(_translate('MainWindow', u'Sand-Silt-Mud'))

        self.actionVersionCheck.setText(
            _translate('MainWindow', u'Check Update'))
        self.actionCnWeb.setText(_translate('MainWindow', u'Chinese Forum'))
        self.actionEnWeb.setText(_translate('MainWindow', u'English Forum'))
        self.actionGoGithub.setText(_translate('MainWindow', u'Github'))

        self.actionCnS.setText(_translate('MainWindow', u'Simplified Chinese'))
        self.actionCnT.setText(_translate('MainWindow',
                                          u'Traditional Chinese'))
        self.actionEn.setText(_translate('MainWindow', u'English'))
        self.actionLoadLanguage.setText(
            _translate('MainWindow', u'Load Language'))

    def resizeEvent(self, evt=None):

        w = self.width()
        h = self.height()
        '''
        if h<=360:
            h=360
            self.resize(w,h)
        if w<=640:
            w = 640
            self.resize(w, h)
        '''

        step = (w * 94 / 100) / 5
        foot = h * 3 / 48

        #if foot<=10: foot=10

        self.tableView.setGeometry(
            QtCore.QRect(w / 100, h / 48, w * 98 / 100, h * 38 / 48))

        self.pushButtonOpen.setGeometry(
            QtCore.QRect(w / 100, h * 40 / 48, step, foot))

        self.pushButtonSave.setGeometry(
            QtCore.QRect(2 * w / 100 + step, h * 40 / 48, step, foot))

        self.pushButtonSort.setGeometry(
            QtCore.QRect(3 * w / 100 + step * 2, h * 40 / 48, step, foot))

        self.pushButtonUpdate.setGeometry(
            QtCore.QRect(4 * w / 100 + step * 3, h * 40 / 48, step, foot))

        self.pushButtonQuit.setGeometry(
            QtCore.QRect(5 * w / 100 + step * 4, h * 40 / 48, step, foot))

    def getfile(self):
        _translate = QtCore.QCoreApplication.translate
        fileName, filetype = QFileDialog.getOpenFileName(
            self, _translate('MainWindow', u'Choose Data File'), '~/',
            'All Files (*);;Text Files (*.txt)')  # 设置文件扩展名过滤,注意用双分号间隔

    def goGitHub(self):
        webbrowser.open('https://github.com/chinageology/GeoPython/wiki')

    def goCnBBS(self):
        webbrowser.open('http://bbs.geopython.com/-f2.html')

    def goEnBBS(self):
        webbrowser.open('http://bbs.geopython.com/English-Forum-f3.html')

    def checkVersion(self):

        #reply = QMessageBox.information(self, 'Version', self.talk)

        _translate = QtCore.QCoreApplication.translate

        url = 'https://raw.githubusercontent.com/chinageology/GeoPython/master/SourceCode/CustomClass.py'

        r = 0
        try:
            r = requests.get(url, allow_redirects=True)
            r.raise_for_status()
            NewVersion = 'self.target' + r.text.splitlines()[0]

        except requests.exceptions.ConnectionError as err:
            print(err)
            r = 0
            buttonReply = QMessageBox.information(
                self, _translate('MainWindow', u'NetWork Error'),
                _translate('MainWindow', u'Net work unavailable.'))
            NewVersion = "targetversion = '0'"

        except requests.exceptions.HTTPError as err:
            print(err)
            r = 0
            buttonReply = QMessageBox.information(
                self, _translate('MainWindow', u'NetWork Error'),
                _translate('MainWindow', u'Net work unavailable.'))
            NewVersion = "targetversion = '0'"

        exec(NewVersion)
        print('web is', self.targetversion)
        print(NewVersion)

        self.talk = _translate(
            'MainWindow',
            'Version Online is ') + self.targetversion + '\n' + _translate(
                'MainWindow',
                'You are using GeoPython ') + version + '\n' + _translate(
                    'MainWindow', 'released on ') + date + '\n'

        if r != 0:

            print('now is', version)
            if (version < self.targetversion):

                buttonReply = QMessageBox.question(
                    self, _translate('MainWindow', u'Version'),
                    self.talk + _translate(
                        'MainWindow',
                        'New version available.\n Download and update?'),
                    QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
                if buttonReply == QMessageBox.Yes:
                    print('Yes clicked.')
                    webbrowser.open(
                        'https://github.com/chinageology/GeoPython/blob/master/Download.md'
                    )
                else:
                    print('No clicked.')
            else:
                buttonReply = QMessageBox.information(
                    self, _translate('MainWindow', u'Version'), self.talk +
                    _translate('MainWindow', 'This is the latest version.'))

    def Update(self):
        webbrowser.open(
            'https://github.com/chinageology/GeoPython/wiki/Download')

    def ReadConfig(self):
        if (os.path.isfile('config.ini')):

            try:
                with open('config.ini', 'rt') as f:
                    try:
                        data = f.read()
                    except:
                        data = 'Language = \'en\''
                        pass

                    print(data)
                    try:
                        print("self." + data)
                        exec("self." + data)
                    except:
                        pass
                    print(self.Language)

            except ():
                pass

    def WriteConfig(self, text=LocationOfMySelf + '/en'):
        try:
            with open('config.ini', 'wt') as f:
                f.write(text)
        except ():
            pass

    def to_ChineseS(self):

        self.trans.load(LocationOfMySelf + '/cns')
        self.app.installTranslator(self.trans)
        self.retranslateUi()

        self.WriteConfig('Language = \'cns\'')

    def to_ChineseT(self):

        self.trans.load(LocationOfMySelf + '/cnt')
        self.app.installTranslator(self.trans)
        self.retranslateUi()

        self.WriteConfig('Language = \'cnt\'')

    def to_English(self):

        self.trans.load(LocationOfMySelf + '/en')
        self.app.installTranslator(self.trans)
        self.retranslateUi()
        self.WriteConfig('Language = \'en\'')

    def to_LoadLanguage(self):

        _translate = QtCore.QCoreApplication.translate
        fileName, filetype = QFileDialog.getOpenFileName(
            self, _translate('MainWindow', u'Choose Language File'), '~/',
            'Language Files (*.qm)')  # 设置文件扩展名过滤,注意用双分号间隔

        print(fileName)

        self.trans.load(fileName)
        self.app.installTranslator(self.trans)
        self.retranslateUi()

    def ErrorEvent(self):

        reply = QMessageBox.information(
            self, _translate('MainWindow', 'Warning'),
            _translate(
                'MainWindow',
                'Your Data mismatch this Plot.\n Some Items missing?\n Or maybe there are blanks in items names?\n Or there are nonnumerical value?'
            ))

    def SetUpDataFile(self):

        flag = 0
        ItemsAvalibale = self.model._df.columns.values.tolist()

        ItemsToTest = [
            'Label', 'Marker', 'Color', 'Size', 'Alpha', 'Style', 'Width'
        ]

        LabelList = []
        MarkerList = []
        ColorList = []
        SizeList = []
        AlphaList = []
        StyleList = []
        WidthList = []

        for i in range(len(self.model._df)):
            LabelList.append('Group1')
            MarkerList.append('o')
            ColorList.append('red')
            SizeList.append(10)
            AlphaList.append(0.6)
            StyleList.append('-')
            WidthList.append(1)

        data = {
            'Label': LabelList,
            'Marker': MarkerList,
            'Color': ColorList,
            'Size': SizeList,
            'Alpha': AlphaList,
            'Style': StyleList,
            'Width': WidthList
        }

        for i in ItemsToTest:
            if i not in ItemsAvalibale:
                # print(i)
                flag = flag + 1
                tmpdftoadd = pd.DataFrame({i: data[i]})

                self.model._df = pd.concat([tmpdftoadd, self.model._df],
                                           axis=1)

        self.model = PandasModel(self.model._df)

        self.tableView.setModel(self.model)

        if flag == 0:
            reply = QMessageBox.information(
                self, _translate('MainWindow', 'Ready'),
                _translate('MainWindow',
                           'Everything fine and no need to set up.'))

        else:
            reply = QMessageBox.information(
                self, _translate('MainWindow', 'Ready'),
                _translate(
                    'MainWindow',
                    'Items added, Modify in the Table to set up details.'))

    def getDataFile(self):
        _translate = QtCore.QCoreApplication.translate
        DataFileInput, filetype = QFileDialog.getOpenFileName(
            self, _translate('MainWindow', u'Choose Data File'), '~/',
            'Excel Files (*.xlsx);;Excel 2003 Files (*.xls);;CSV Files (*.csv)'
        )  # 设置文件扩展名过滤,注意用双分号间隔

        # #print(DataFileInput,filetype)

        if ('csv' in DataFileInput):
            self.raw = pd.read_csv(DataFileInput)
        elif ('xls' in DataFileInput):
            self.raw = pd.read_excel(DataFileInput)
        # #print(self.raw)

        self.model = PandasModel(self.raw)
        self.tableView.setModel(self.model)

    def saveDataFile(self):

        # if self.model._changed == True:
        # print('changed')
        # print(self.model._df)

        DataFileOutput, ok2 = QFileDialog.getSaveFileName(
            self, _translate('MainWindow', u'Save Data File'), 'C:/',
            'Excel Files (*.xlsx);;CSV Files (*.csv)')  # 数据文件保存输出

        if (DataFileOutput != ''):

            if ('csv' in DataFileOutput):
                self.model._df.to_csv(DataFileOutput,
                                      sep=',',
                                      encoding='utf-8')

            elif ('xls' in DataFileOutput):
                self.model._df.to_excel(DataFileOutput, encoding='utf-8')

    def CIPW(self):
        self.cipwpop = CIPW(df=self.model._df)
        try:
            self.cipwpop.CIPW()
            self.cipwpop.show()
        except (KeyError):
            self.ErrorEvent()

    def ZirconTiTemp(self):
        self.ztpop = ZirconTiTemp(df=self.model._df)
        try:
            self.ztpop.ZirconTiTemp()
            self.ztpop.show()
        except (KeyError):
            self.ErrorEvent()

    def RutileZrTemp(self):
        self.rzpop = RutileZrTemp(df=self.model._df)
        try:
            self.rzpop.RutileZrTemp()
            self.rzpop.show()
        except (KeyError):
            self.ErrorEvent()

    def Cluster(self):

        self.clusterpop = Cluster(df=self.model._df)
        self.clusterpop.Cluster()
        self.clusterpop.show()

        try:
            self.clusterpop.Cluster()
            self.clusterpop.show()
        except (KeyError):
            pass
            # self.ErrorEvent()

    def TAS(self):

        self.pop = TAS(df=self.model._df)
        try:
            self.pop.TAS()
            self.pop.show()
        except (KeyError):
            self.ErrorEvent()

    def REE(self):
        self.reepop = REE(df=self.model._df)
        try:
            self.reepop.REE()
            self.reepop.show()
        except (KeyError):
            self.ErrorEvent()

    def Trace(self):
        self.tracepop = Trace(df=self.model._df)
        try:
            self.tracepop.Trace()
            self.tracepop.show()
        except (KeyError):
            self.ErrorEvent()

    def Pearce(self):
        self.pearcepop = Pearce(df=self.model._df)

        try:
            self.pearcepop.Pearce()
            self.pearcepop.show()
        except (KeyError):
            self.ErrorEvent()

    def Harker(self):
        self.harkerpop = Harker(df=self.model._df)
        try:
            self.harkerpop.Harker()
            self.harkerpop.show()
        except (KeyError):
            self.ErrorEvent()

    def Stereo(self):
        self.stereopop = Stereo(df=self.model._df)
        try:
            self.stereopop.Stereo()
            self.stereopop.show()
        except (KeyError):
            self.ErrorEvent()

    def Rose(self):
        self.rosepop = Rose(df=self.model._df)
        try:
            self.rosepop.Rose()
            self.rosepop.show()
        except (KeyError):
            self.ErrorEvent()

    def QFL(self):
        self.qflpop = QFL(df=self.model._df)
        try:
            self.qflpop.Tri()
            self.qflpop.show()
        except (KeyError):
            self.ErrorEvent()

    def QmFLt(self):
        self.qmfltpop = QmFLt(df=self.model._df)
        try:
            self.qmfltpop.Tri()
            self.qmfltpop.show()
        except (KeyError):
            self.ErrorEvent()

    def QAPF(self):
        self.qapfpop = QAPF(df=self.model._df)
        try:
            self.qapfpop.QAPF()
            self.qapfpop.show()
        except (KeyError):
            self.ErrorEvent()

    def Mud(self):
        self.mudpop = MudStone(df=self.model._df)
        try:
            self.mudpop.Tri()
            self.mudpop.show()
        except (KeyError):
            self.ErrorEvent()

    def ZirconCe(self):
        # print('Opening a new popup window...')
        self.zirconpop = ZirconCe(df=self.model._df)
        try:
            self.zirconpop.MultiBallard()
            self.zirconpop.show()
        except (KeyError, ValueError):
            self.ErrorEvent()

    def XY(self):
        self.xypop = XY(df=self.model._df)
        try:
            self.xypop.Magic()
            self.xypop.show()
        except (KeyError):
            self.ErrorEvent()

    def XYZ(self):
        self.xyzpop = XYZ(df=self.model._df)
        try:
            self.xyzpop.Magic()
            self.xyzpop.show()
        except (KeyError):
            self.ErrorEvent()

    def Magic(self):
        self.magicpop = Magic(df=self.model._df)
        try:
            self.magicpop.Magic()
            self.magicpop.show()
        except (KeyError):
            self.ErrorEvent()

    def MultiDimension(self):
        self.mdpop = MultiDimension(df=self.model._df)
        try:
            self.mdpop.Magic()
            self.mdpop.show()
        except (KeyError):
            self.ErrorEvent()

    def Tri(self):
        pass

    def Auto(self):
        pass
Ejemplo n.º 16
0
def main():
	
	#Read in XYZ file. Store all the coordinates.
	global simulation_atoms, simulation_atoms_dict
	simulation_atoms = XYZ()
	simulation_atoms.load(structure_file) #simulation_atoms.rows contains the data
	simulation_atoms_dict = simulation_atoms.return_sorted_by_atoms_dict()
	#NOTE: Now we have two tables, simulation_atoms and simulation_atoms_dict

	#Read in connection table (ReaxFF fort.7 style, see ReaxFF manual for more info)
	global connection_table #So that other functions can access this
	connection_table = Connection_Table()
	connection_table.load(connection_table_file)

	#Testing
	#tests()

	#Go through each of the target molecules and do isolation stuff:
	for target_molecule in target_molecules:
		#Select an atom to work with. We just select the first one. Used for the 'exclude'
		#case so that we don't have to check every single atom in simulation_atoms:
		an_atom = target_molecule[0] 
		#Loop through all the atoms matching the an_atom type:
		for atom_number, each_atom in enumerate(simulation_atoms.rows):
			#Correction to the atom_number since XYZ list starts at 0 but atom numbers
			#start at 1:
			atom_number += 1

			#Somewhat of a hack: Do a quick check here to see if this atom has been
			#nullified in the XYZ object. If so, we can just skip it since this atom
			#has been "deleted".
			if each_atom == None:
				continue #skip this atom since it has been deleted
			
			#If the isolate_method is 'include' then we have to check all atoms because
			#there are cases of single atoms and/or atoms not connected to the target
			#molecule atoms that we defined which we won't catch unless we check every 
			#atom. If the isolate method is 'exclude' then we just have to check atoms that
			#are connected to an atom in the defined target molecule.
			if isolate_method == 'exclude' and each_atom[0] != an_atom:
				#Skip this atom for now. If it's part of the target molecule, we'll
				#automatically come back to it later.
				continue
			
			#For the current atom, get the molecule that corresponds to it:
			molecule_parts = get_molecule_for_atom(atom_number)
			
			#Check this molecule against our isolation specification see if match exists:
			same_molecules_q = are_molecules_the_same( \
				list(target_molecule),
				molecule_parts_to_list(molecule_parts),
				isolate_criteria
				)

			#Get the molecule numbers so that we can feed it into the nullify atoms func.
			molecule_atom_numbers = molecule_parts.keys()
			#Now keep/remove depending on criteria:
			if isolate_method == 'include':
				if same_molecules_q != True:
					#print molecule_parts
					#The molecules are not the same so we need to delete it	
					nullify_atoms_in_XYZ(molecule_atom_numbers)
			elif isolate_method == 'exclude':
				if same_molecules_q == True:
					#This molecule is in the excluded list so we need to delete it
					nullify_atoms_in_XYZ(molecule_atom_numbers)
			else:
				print 'ERROR: isolate_method option invalid!'
				sys.exit(0)

	#Cool, we now ran through the whole XYZ file. Let's save the changed version:
	simulation_atoms.export(output_xyz_file)
	print 'Processed XYZ file exported: '+output_xyz_file