language
stringclasses
6 values
original_string
stringlengths
25
887k
text
stringlengths
25
887k
Python
def _MAD(array, weights=None): ''' Compute the mean absolute deviation of a 1-d array Args: array: A 1-d array or list weights: weights corresponding to each element of the array Returns: the weighted mean absolute deviation of the 1-d array ''' mean = np.mean(array) # mean absolute deviation return np.average(np.abs(np.subtract(array, mean)), weights=weights)
def _MAD(array, weights=None): ''' Compute the mean absolute deviation of a 1-d array Args: array: A 1-d array or list weights: weights corresponding to each element of the array Returns: the weighted mean absolute deviation of the 1-d array ''' mean = np.mean(array) # mean absolute deviation return np.average(np.abs(np.subtract(array, mean)), weights=weights)
Python
def _get_all_nearest_neighbors(method, crystal): ''' Get the nearest neighbor list of a structure Args: method: method used to compute nearest_neighbors crystal: pymatgen structure Returns: nearest neighbors ''' # check that the passed crystal is a pymatgen structure object if isinstance(crystal, Structure): # make the structure an immutable object crystal = IStructure.from_sites(crystal) # get the voronoi info of the crystal return method.get_all_nn_info(crystal)
def _get_all_nearest_neighbors(method, crystal): ''' Get the nearest neighbor list of a structure Args: method: method used to compute nearest_neighbors crystal: pymatgen structure Returns: nearest neighbors ''' # check that the passed crystal is a pymatgen structure object if isinstance(crystal, Structure): # make the structure an immutable object crystal = IStructure.from_sites(crystal) # get the voronoi info of the crystal return method.get_all_nn_info(crystal)
Python
def _get_chemical_descriptors_from_file(elm, weight): ''' Calls certain elemental properties from the Elements.json file to use as weighted chemical environment attributes Args: elm: a pymatgen element object weight: a numerical value to be used as a weight for these attributes Returns: an array of chemical environment attributes ''' # convert the element object to a string for indexing of the json file elm = str(elm) # compute the below elemental properties properties = ['nsvalence', 'npvalence', 'ndvalence', 'nfvalence', 'nsunfill', 'npunfill', 'ndunfill', 'nfunfill', 'first_ion_en'] # the current json file has only 82 elements, some are missing if elm in ['Pa', 'Ac', 'Pu', 'Np', 'Am', 'Bk', 'Cf', 'Cm', 'Es', 'Fm', 'Lr', 'Md', 'No']: elm = 'Th' elif elm in ['Eu', 'Pm']: elm = 'La' elif elm in ['Xe', 'Rn']: elm = 'Kr' elif elm in ['At']: elm = 'I' elif elm in ['Fr']: elm = 'Cs' elif elm in ['Ra']: elm = 'Ba' # call the elemental specfic dictionary data = ele_data[elm] # populate an empty list with the above elemental properties arr = [] for prop in properties: # gather the property and multiply by the weight arr.append(data[prop] * weight) # items 0-3 correspond to the occupancies of the valence structure arr += [np.sum(arr[0:4])] # total valence # items 4-7 correspond to the vacancies of the valence structure arr += [np.sum(arr[4:8])] # total unfilled return arr
def _get_chemical_descriptors_from_file(elm, weight): ''' Calls certain elemental properties from the Elements.json file to use as weighted chemical environment attributes Args: elm: a pymatgen element object weight: a numerical value to be used as a weight for these attributes Returns: an array of chemical environment attributes ''' # convert the element object to a string for indexing of the json file elm = str(elm) # compute the below elemental properties properties = ['nsvalence', 'npvalence', 'ndvalence', 'nfvalence', 'nsunfill', 'npunfill', 'ndunfill', 'nfunfill', 'first_ion_en'] # the current json file has only 82 elements, some are missing if elm in ['Pa', 'Ac', 'Pu', 'Np', 'Am', 'Bk', 'Cf', 'Cm', 'Es', 'Fm', 'Lr', 'Md', 'No']: elm = 'Th' elif elm in ['Eu', 'Pm']: elm = 'La' elif elm in ['Xe', 'Rn']: elm = 'Kr' elif elm in ['At']: elm = 'I' elif elm in ['Fr']: elm = 'Cs' elif elm in ['Ra']: elm = 'Ba' # call the elemental specfic dictionary data = ele_data[elm] # populate an empty list with the above elemental properties arr = [] for prop in properties: # gather the property and multiply by the weight arr.append(data[prop] * weight) # items 0-3 correspond to the occupancies of the valence structure arr += [np.sum(arr[0:4])] # total valence # items 4-7 correspond to the vacancies of the valence structure arr += [np.sum(arr[4:8])] # total unfilled return arr
Python
def _get_chemical_descriptors_from_pymatgen(elm, weight): ''' Calls certain elemental properties from Pymatgen to use as weighted chemical environment attributes Args: elm: a pymatgen element object weight: a numerical value to be used as a weight for these attributes Returns: an array of chemical environment attributes ''' element = elm.data properties = ['Atomic no', 'Atomic mass', 'row', 'col', 'Mendeleev no', 'Atomic radius'] arr = [] for prop in properties: if prop == 'row': arr.append(elm.row * weight) continue if prop == 'col': arr.append(elm.group * weight) continue else: arr.append(element[prop] * weight) return arr
def _get_chemical_descriptors_from_pymatgen(elm, weight): ''' Calls certain elemental properties from Pymatgen to use as weighted chemical environment attributes Args: elm: a pymatgen element object weight: a numerical value to be used as a weight for these attributes Returns: an array of chemical environment attributes ''' element = elm.data properties = ['Atomic no', 'Atomic mass', 'row', 'col', 'Mendeleev no', 'Atomic radius'] arr = [] for prop in properties: if prop == 'row': arr.append(elm.row * weight) continue if prop == 'col': arr.append(elm.group * weight) continue else: arr.append(element[prop] * weight) return arr
Python
def _get_descr(self, elm, weight): ''' Calls chemical attributes from pymatgen and a json file Args: elm: a pymatgen element object weight: a numerical value to be used as a weight for these attributes Returns: an array of weighted chemical envronment attributes ''' return (np.hstack((self._get_chemical_descriptors_from_file(elm, weight), self._get_chemical_descriptors_from_pymatgen(elm, weight))))
def _get_descr(self, elm, weight): ''' Calls chemical attributes from pymatgen and a json file Args: elm: a pymatgen element object weight: a numerical value to be used as a weight for these attributes Returns: an array of weighted chemical envronment attributes ''' return (np.hstack((self._get_chemical_descriptors_from_file(elm, weight), self._get_chemical_descriptors_from_pymatgen(elm, weight))))
Python
def _Get_stats(self, array, weights=None): ''' Compute the min, max, range, mean, and mean absolute deviation over a 1-d array Args: Array: a 1-d float array weights: a numerical value to be used as a weight for the chemical environment attributes Returns: the stats described above ''' return [np.amin(array), np.amax(array), np.ptp(array), self._weighted_average(array, weights), self._MAD(array, weights)]
def _Get_stats(self, array, weights=None): ''' Compute the min, max, range, mean, and mean absolute deviation over a 1-d array Args: Array: a 1-d float array weights: a numerical value to be used as a weight for the chemical environment attributes Returns: the stats described above ''' return [np.amin(array), np.amax(array), np.ptp(array), self._weighted_average(array, weights), self._MAD(array, weights)]
Python
def _compute_polyhedra(self): ''' Compute the voronoi polyhedron and specie of each atomic site, format as a tuple (polyhedron, specie), and store those tuples in a list as an attribute ''' # call the voronoi object voronoi = VoronoiNN() self._polyhedra = [] # declare polyhedra attribute # populate the attribute with the polyhedron associated with each # atomic site for i, _ in enumerate(self._crystal): self._polyhedra.append((voronoi.get_voronoi_polyhedra(self._crystal, i), self._crystal[i].specie))
def _compute_polyhedra(self): ''' Compute the voronoi polyhedron and specie of each atomic site, format as a tuple (polyhedron, specie), and store those tuples in a list as an attribute ''' # call the voronoi object voronoi = VoronoiNN() self._polyhedra = [] # declare polyhedra attribute # populate the attribute with the polyhedron associated with each # atomic site for i, _ in enumerate(self._crystal): self._polyhedra.append((voronoi.get_voronoi_polyhedra(self._crystal, i), self._crystal[i].specie))
Python
def _check_sanity(self, G_parameters, G_keywords): """ Check if any of the parameters in the keywords. """ for key, value in G_parameters.items(): if key in G_keywords: pass else: raise NotImplementedError( f"Unknown parameter: {key}. "\ f"The available parameters are {self.G5_keywords}.")
def _check_sanity(self, G_parameters, G_keywords): """ Check if any of the parameters in the keywords. """ for key, value in G_parameters.items(): if key in G_keywords: pass else: raise NotImplementedError( f"Unknown parameter: {key}. "\ f"The available parameters are {self.G5_keywords}.")
Python
def dcos_dRpq(a, b, c, Ra, Rb, Rc, p, q): """ Calculate the derivative of cosine dot product function with respect to the radius of an atom m in a particular direction l. Parameters ---------- a: int Index of the center atom. b: int Index of the first neighbor atom. c: int Index of the second neighbor atom. Ra: list of floats Position of the center atom. Rb: list of floats Position of the first atom. Rc: list of floats Postition of the second atom. p: int Atom that is experiencing force. q: int Direction of force. x = 0, y = 1, and z = 2. Returns ------- Derivative of cosine dot product w.r.t. the radius of an atom m in a particular direction l. """ Rab_vector = Rb - Ra Rac_vector = Rc - Ra Rab = np.linalg.norm(Rab_vector) Rac = np.linalg.norm(Rac_vector) f_term = 1 / (Rab * Rac) * \ np.dot(dRab_dRpq_vector(a, b, p, q), Rac_vector) s_term = 1 / (Rab * Rac) * \ np.dot(Rab_vector, dRab_dRpq_vector(a, c, p, q)) t_term = np.dot(Rab_vector, Rac_vector) / Rab ** 2 / Rac * \ dRab_dRpq(a, b, Ra, Rb, p, q) fo_term = np.dot(Rab_vector, Rac_vector) / Rab / Rac ** 2 * \ dRab_dRpq(a, c, Ra, Rc, p, q) return (f_term + s_term - t_term - fo_term)
def dcos_dRpq(a, b, c, Ra, Rb, Rc, p, q): """ Calculate the derivative of cosine dot product function with respect to the radius of an atom m in a particular direction l. Parameters ---------- a: int Index of the center atom. b: int Index of the first neighbor atom. c: int Index of the second neighbor atom. Ra: list of floats Position of the center atom. Rb: list of floats Position of the first atom. Rc: list of floats Postition of the second atom. p: int Atom that is experiencing force. q: int Direction of force. x = 0, y = 1, and z = 2. Returns ------- Derivative of cosine dot product w.r.t. the radius of an atom m in a particular direction l. """ Rab_vector = Rb - Ra Rac_vector = Rc - Ra Rab = np.linalg.norm(Rab_vector) Rac = np.linalg.norm(Rac_vector) f_term = 1 / (Rab * Rac) * \ np.dot(dRab_dRpq_vector(a, b, p, q), Rac_vector) s_term = 1 / (Rab * Rac) * \ np.dot(Rab_vector, dRab_dRpq_vector(a, c, p, q)) t_term = np.dot(Rab_vector, Rac_vector) / Rab ** 2 / Rac * \ dRab_dRpq(a, b, Ra, Rb, p, q) fo_term = np.dot(Rab_vector, Rac_vector) / Rab / Rac ** 2 * \ dRab_dRpq(a, c, Ra, Rc, p, q) return (f_term + s_term - t_term - fo_term)
Python
def derivative(self, Rij): """ Calculate derivative (dF/dRij) of the Cosine functional with respect to Rij. Args: Rij(float): distance between pair atoms. Returns: The derivative (float) of the Cosine functional. """ if Rij > self.Rc: return 0.0 else: return (-0.5 * np.pi / self.Rc * np.sin(np.pi * Rij / self.Rc))
def derivative(self, Rij): """ Calculate derivative (dF/dRij) of the Cosine functional with respect to Rij. Args: Rij(float): distance between pair atoms. Returns: The derivative (float) of the Cosine functional. """ if Rij > self.Rc: return 0.0 else: return (-0.5 * np.pi / self.Rc * np.sin(np.pi * Rij / self.Rc))
Python
def derivative(self, Rij): """ Derivative (dF/dRij) of the Polynomial functional with respect to Rij. Args: Rij(float): distance between pair atoms. Returns: The derivative (float) of the cutoff functional. """ if Rij > self.Rc: return 0.0 else: ratio = Rij / self.Rc value = (self.gamma * (self.gamma + 1) / self.Rc) * \ (ratio ** self.gamma - ratio ** (self.gamma - 1)) return value
def derivative(self, Rij): """ Derivative (dF/dRij) of the Polynomial functional with respect to Rij. Args: Rij(float): distance between pair atoms. Returns: The derivative (float) of the cutoff functional. """ if Rij > self.Rc: return 0.0 else: ratio = Rij / self.Rc value = (self.gamma * (self.gamma + 1) / self.Rc) * \ (ratio ** self.gamma - ratio ** (self.gamma - 1)) return value
Python
def derivative(self, Rij): """ Calculate derivative (dF/dRij) of the hyperbolic Tangent functional with respect to Rij. Args: Rij(float): distance between pair atoms. Returns: The derivative (float) of the hyberbolic tangent functional. """ if Rij > self.Rc: return 0.0 else: return (-3.0 / self.Rc * ((np.tanh(1.0 - (Rij / self.Rc))) ** 2 - \ (np.tanh(1.0 - (Rij / self.Rc))) ** 4))
def derivative(self, Rij): """ Calculate derivative (dF/dRij) of the hyperbolic Tangent functional with respect to Rij. Args: Rij(float): distance between pair atoms. Returns: The derivative (float) of the hyberbolic tangent functional. """ if Rij > self.Rc: return 0.0 else: return (-3.0 / self.Rc * ((np.tanh(1.0 - (Rij / self.Rc))) ** 2 - \ (np.tanh(1.0 - (Rij / self.Rc))) ** 4))
Python
def G1_prime(crystal, i, e_type, ni, functional='Cosine', Rc=6.5, p=1, q=0): """ Calculate the derivative of the G1 symmetry function. Parameters ---------- crystal: object Pymatgen crystal structure object. i: int The index of core element. e_types: str The allowed element presents in the symmetry function calculation. ni: array of neighbors information Neighbors information of the core element. functional: str Cutoff functional. Default is Cosine functional. Rc: float Cutoff radius which the symmetry function will be calculated. Default value is 6.5 as suggested by Behler. p: int The atom that the force is acting on. q: int Direction of force. Returns ------- G1p: float The derivative of G1 symmetry value. """ # Cutoff functional if functional == 'Cosine': func = Cosine(Rc=Rc) elif functional == 'Polynomial': func = Polynomial(Rc=Rc) elif functional == 'TangentH': func = TangentH(Rc=Rc) else: raise NotImplementedError('Unknown cutoff functional: %s' %functional) # Get core atoms information Ri = crystal.cart_coords[i] G1p = 0 for count in range(len(ni)): symbol = ni[count][0].species_string Rj = ni[count][0]._coords j = ni[count][2] if e_type == symbol: Rij = np.linalg.norm(Rj - Ri) G1p += func.derivative(Rij) * \ dRab_dRpq(i, j, Ri, Rj, p, q) return G1p
def G1_prime(crystal, i, e_type, ni, functional='Cosine', Rc=6.5, p=1, q=0): """ Calculate the derivative of the G1 symmetry function. Parameters ---------- crystal: object Pymatgen crystal structure object. i: int The index of core element. e_types: str The allowed element presents in the symmetry function calculation. ni: array of neighbors information Neighbors information of the core element. functional: str Cutoff functional. Default is Cosine functional. Rc: float Cutoff radius which the symmetry function will be calculated. Default value is 6.5 as suggested by Behler. p: int The atom that the force is acting on. q: int Direction of force. Returns ------- G1p: float The derivative of G1 symmetry value. """ # Cutoff functional if functional == 'Cosine': func = Cosine(Rc=Rc) elif functional == 'Polynomial': func = Polynomial(Rc=Rc) elif functional == 'TangentH': func = TangentH(Rc=Rc) else: raise NotImplementedError('Unknown cutoff functional: %s' %functional) # Get core atoms information Ri = crystal.cart_coords[i] G1p = 0 for count in range(len(ni)): symbol = ni[count][0].species_string Rj = ni[count][0]._coords j = ni[count][2] if e_type == symbol: Rij = np.linalg.norm(Rj - Ri) G1p += func.derivative(Rij) * \ dRab_dRpq(i, j, Ri, Rj, p, q) return G1p
Python
def G2_prime(crystal, i, e_type, ni, functional='Cosine', Rc=6.5, eta=2, Rs=0.0, p=1, q=0): """ Calculate the derivative of the G2 symmetry function. Parameters ---------- crystal: object Pymatgen crystal structure object. i: int The index of core element. e_types: str The allowed element presents in the symmetry function calculation. ni: array of neighbors information Neighbors information of the core element. functional: str Cutoff functional. Default is Cosine functional. Rc: float Cutoff radius which the symmetry function will be calculated. Default value is 6.5 as suggested by Behler. eta: float The parameter of G2 symmetry function. Rs: float Determine the shift from the center of the Gaussian. Default value is zero. p: int The atom that the force is acting on. q: int Direction of force. Returns ------- G2p: float The derivative of G2 symmetry value. """ # Cutoff functional if functional == 'Cosine': func = Cosine(Rc=Rc) elif functional == 'Polynomial': func = Polynomial(Rc=Rc) elif functional == 'TangentH': func = TangentH(Rc=Rc) else: raise NotImplementedError('Unknown cutoff functional: %s' %functional) # Get positions of core atoms Ri = crystal.cart_coords[i] G2p = 0 for count in range(len(ni)): symbol = ni[count][0].species_string Rj = ni[count][0]._coords j = ni[count][2] if e_type == symbol: dRabdRpq = dRab_dRpq(i, j, Ri, Rj, p, q) if dRabdRpq != 0: Rij = np.linalg.norm(Rj - Ri) G2p += np.exp(-eta * (Rij - Rs)**2. / Rc**2.) * \ dRabdRpq * \ (-2. * eta * (Rij - Rs) * func(Rij) / Rc**2. + func.derivative(Rij)) return G2p
def G2_prime(crystal, i, e_type, ni, functional='Cosine', Rc=6.5, eta=2, Rs=0.0, p=1, q=0): """ Calculate the derivative of the G2 symmetry function. Parameters ---------- crystal: object Pymatgen crystal structure object. i: int The index of core element. e_types: str The allowed element presents in the symmetry function calculation. ni: array of neighbors information Neighbors information of the core element. functional: str Cutoff functional. Default is Cosine functional. Rc: float Cutoff radius which the symmetry function will be calculated. Default value is 6.5 as suggested by Behler. eta: float The parameter of G2 symmetry function. Rs: float Determine the shift from the center of the Gaussian. Default value is zero. p: int The atom that the force is acting on. q: int Direction of force. Returns ------- G2p: float The derivative of G2 symmetry value. """ # Cutoff functional if functional == 'Cosine': func = Cosine(Rc=Rc) elif functional == 'Polynomial': func = Polynomial(Rc=Rc) elif functional == 'TangentH': func = TangentH(Rc=Rc) else: raise NotImplementedError('Unknown cutoff functional: %s' %functional) # Get positions of core atoms Ri = crystal.cart_coords[i] G2p = 0 for count in range(len(ni)): symbol = ni[count][0].species_string Rj = ni[count][0]._coords j = ni[count][2] if e_type == symbol: dRabdRpq = dRab_dRpq(i, j, Ri, Rj, p, q) if dRabdRpq != 0: Rij = np.linalg.norm(Rj - Ri) G2p += np.exp(-eta * (Rij - Rs)**2. / Rc**2.) * \ dRabdRpq * \ (-2. * eta * (Rij - Rs) * func(Rij) / Rc**2. + func.derivative(Rij)) return G2p
Python
def G3(crystal, i, e_type, functional='Cosine', Rc=6.5, k=10): """ Calculate G3 symmetry function. G3 function is a damped cosine functions with a period length described by K. For example, a Fourier series expansion a suitable description of the radial atomic environment can be obtained by comibning several G3 functions with different values for K. Note: due to the distances of atoms, G3 can cancel each other out depending on the positive and negative value. One can refer to equation 7 in: Behler, J. (2011). Atom-centered symmetry functions for constructing high-dimensional neural network potentials. The Journal of chemical physics, 134(7), 074106. Parameters ---------- crystal: object Pymatgen crystal structure object. i: int The index of core element. e_type: str The allowed element presents in the symmetry function calculation. functional: str Cutoff functional. Default is Cosine functional. Rc: float Cutoff radius which the symmetry function will be calculated. Default value is 6.5 as suggested by Behler. k: float The Kappa value as G3 parameter. Returns ------- G3: float G3 symmetry value. """ if functional == 'Cosine': func = Cosine(Rc=Rc) elif functional == 'Polynomial': func = Polynomial(Rc=Rc) elif functional == 'TangentH': func = TangentH(Rc=Rc) else: raise NotImplementedError('Unknown cutoff functional: %s' %functional) # Get positions of core atoms Ri = crystal.cart_coords[i] # Get neighbors information neighbors = crystal.get_all_neighbors(Rc) G3 = 0 for j in range(len(neighbors[i])): if e_type == neighbors[i][j][0].species_string: Rj = neighbors[i][j][0]._coords Rij = np.linalg.norm(Ri - Rj) G3 += np.cos(k * Rij / Rc) * func(Rij) return G3
def G3(crystal, i, e_type, functional='Cosine', Rc=6.5, k=10): """ Calculate G3 symmetry function. G3 function is a damped cosine functions with a period length described by K. For example, a Fourier series expansion a suitable description of the radial atomic environment can be obtained by comibning several G3 functions with different values for K. Note: due to the distances of atoms, G3 can cancel each other out depending on the positive and negative value. One can refer to equation 7 in: Behler, J. (2011). Atom-centered symmetry functions for constructing high-dimensional neural network potentials. The Journal of chemical physics, 134(7), 074106. Parameters ---------- crystal: object Pymatgen crystal structure object. i: int The index of core element. e_type: str The allowed element presents in the symmetry function calculation. functional: str Cutoff functional. Default is Cosine functional. Rc: float Cutoff radius which the symmetry function will be calculated. Default value is 6.5 as suggested by Behler. k: float The Kappa value as G3 parameter. Returns ------- G3: float G3 symmetry value. """ if functional == 'Cosine': func = Cosine(Rc=Rc) elif functional == 'Polynomial': func = Polynomial(Rc=Rc) elif functional == 'TangentH': func = TangentH(Rc=Rc) else: raise NotImplementedError('Unknown cutoff functional: %s' %functional) # Get positions of core atoms Ri = crystal.cart_coords[i] # Get neighbors information neighbors = crystal.get_all_neighbors(Rc) G3 = 0 for j in range(len(neighbors[i])): if e_type == neighbors[i][j][0].species_string: Rj = neighbors[i][j][0]._coords Rij = np.linalg.norm(Ri - Rj) G3 += np.cos(k * Rij / Rc) * func(Rij) return G3
Python
def G3_prime(crystal, i, e_type, ni, functional='Cosine', Rc=6.5, k=10, p=1, q=0): """ Calculate derivative of the G3 symmetry function. Parameters ---------- crystal: object Pymatgen crystal structure object. i: int The index of core element. e_types: str The allowed element presents in the symmetry function calculation. ni: array of neighbors information Neighbors information of the core element. functional: str Cutoff functional. Default is Cosine functional. Rc: float Cutoff radius which the symmetry function will be calculated. Default value is 6.5 as suggested by Behler. k: float The Kappa value as G3 parameter. p: int The atom that the force is acting on. q: int Direction of force. Returns ------- G3p : float The derivative of G3 symmetry value. """ if functional == 'Cosine': func = Cosine(Rc=Rc) elif functional == 'Polynomial': func = Polynomial(Rc=Rc) elif functional == 'TangentH': func = TangentH(Rc=Rc) else: raise NotImplementedError('Unknown cutoff functional: %s' %functional) # Get positions of core atoms Ri = crystal.cart_coords[i] G3p = 0 for count in range(len(ni)): Rj = ni[count][0]._coords symbol = ni[count][0].species_string j = ni[count][2] if e_type == symbol: dRabdRpq = dRab_dRpq(i, j, Ri, Rj, p, q) if dRabdRpq != 0: Rij = np.linalg.norm(Rj - Ri) G3p += (np.cos(k * Rij) * func.derivative(Rij) - \ k * np.sin(k * Rij) * func(Rij)) * \ dRab_dRpq(i, j, Ri, Rj, p, q) return G3p
def G3_prime(crystal, i, e_type, ni, functional='Cosine', Rc=6.5, k=10, p=1, q=0): """ Calculate derivative of the G3 symmetry function. Parameters ---------- crystal: object Pymatgen crystal structure object. i: int The index of core element. e_types: str The allowed element presents in the symmetry function calculation. ni: array of neighbors information Neighbors information of the core element. functional: str Cutoff functional. Default is Cosine functional. Rc: float Cutoff radius which the symmetry function will be calculated. Default value is 6.5 as suggested by Behler. k: float The Kappa value as G3 parameter. p: int The atom that the force is acting on. q: int Direction of force. Returns ------- G3p : float The derivative of G3 symmetry value. """ if functional == 'Cosine': func = Cosine(Rc=Rc) elif functional == 'Polynomial': func = Polynomial(Rc=Rc) elif functional == 'TangentH': func = TangentH(Rc=Rc) else: raise NotImplementedError('Unknown cutoff functional: %s' %functional) # Get positions of core atoms Ri = crystal.cart_coords[i] G3p = 0 for count in range(len(ni)): Rj = ni[count][0]._coords symbol = ni[count][0].species_string j = ni[count][2] if e_type == symbol: dRabdRpq = dRab_dRpq(i, j, Ri, Rj, p, q) if dRabdRpq != 0: Rij = np.linalg.norm(Rj - Ri) G3p += (np.cos(k * Rij) * func.derivative(Rij) - \ k * np.sin(k * Rij) * func(Rij)) * \ dRab_dRpq(i, j, Ri, Rj, p, q) return G3p
Python
def G4(crystal, i, ep_type, functional='Cosine', Rc=6.5, eta=2, lamBda=1, zeta=1): """ Calculate G4 symmetry function. G4 function is an angular function utilizing the cosine funtion of the angle theta_ijk centered at atom i. One can refer to equation 8 in: Behler, J. (2011). Atom-centered symmetry functions for constructing high-dimensional neural network potentials. The Journal of chemical physics, 134(7), 074106. Parameters ---------- crystal: object Pymatgen crystal structure object. i: int The index of core element. ep_types: str The allowed element pair presents in the symmetry function calculation. functional: str Cutoff functional. Default is Cosine functional. Rc: float Cutoff radius which the symmetry function will be calculated. Default value is 6.5 as suggested by Behler. eta: float The parameter of G4 symmetry function. lamBda: float LamBda take values from -1 to +1 shifting the maxima of the cosine function to 0 to 180 degree. zeta: float The angular resolution. Zeta with high values give a narrower range of the nonzero G4 values. Different zeta values is preferrable for distribution of angles centered at each reference atom. In some sense, zeta is illustrated as the eta value. Returns ------- G4: float G4 symmetry value. """ # Cutoff functional if functional == 'Cosine': func = Cosine(Rc=Rc) elif functional == 'Polynomial': func = Polynomial(Rc=Rc) elif functional == 'TangentH': func = TangentH(Rc=Rc) else: raise NotImplementedError('Unknown cutoff functional: %s' %functional) # Get core atoms information Ri = crystal.cart_coords[i] # Get neighbors information neighbors = crystal.get_all_neighbors(Rc) G4 = 0.0 for j in range(len(neighbors[i])-1): for k in range(j+1, len(neighbors[i])): n1 = neighbors[i][j][0].species_string n2 = neighbors[i][k][0].species_string if (ep_type[0] == n1 and ep_type[1] == n2) or \ (ep_type[1] == n1 and ep_type[0] == n2): Rj = neighbors[i][j][0].coords Rk = neighbors[i][k][0].coords Rij_vector = Rj - Ri Rij = np.linalg.norm(Rij_vector) Rik_vector = Rk - Ri Rik = np.linalg.norm(Rik_vector) Rjk_vector = Rk - Rj Rjk = np.linalg.norm(Rjk_vector) cos_ijk = np.dot(Rij_vector, Rik_vector)/ Rij / Rik term = (1. + lamBda * cos_ijk) ** zeta term *= np.exp(-eta * (Rij ** 2. + Rik ** 2. + Rjk ** 2.) / Rc ** 2.) term *= func(Rij) * func(Rik) * func(Rjk) G4 += term G4 *= 2. ** (1. - zeta) return G4
def G4(crystal, i, ep_type, functional='Cosine', Rc=6.5, eta=2, lamBda=1, zeta=1): """ Calculate G4 symmetry function. G4 function is an angular function utilizing the cosine funtion of the angle theta_ijk centered at atom i. One can refer to equation 8 in: Behler, J. (2011). Atom-centered symmetry functions for constructing high-dimensional neural network potentials. The Journal of chemical physics, 134(7), 074106. Parameters ---------- crystal: object Pymatgen crystal structure object. i: int The index of core element. ep_types: str The allowed element pair presents in the symmetry function calculation. functional: str Cutoff functional. Default is Cosine functional. Rc: float Cutoff radius which the symmetry function will be calculated. Default value is 6.5 as suggested by Behler. eta: float The parameter of G4 symmetry function. lamBda: float LamBda take values from -1 to +1 shifting the maxima of the cosine function to 0 to 180 degree. zeta: float The angular resolution. Zeta with high values give a narrower range of the nonzero G4 values. Different zeta values is preferrable for distribution of angles centered at each reference atom. In some sense, zeta is illustrated as the eta value. Returns ------- G4: float G4 symmetry value. """ # Cutoff functional if functional == 'Cosine': func = Cosine(Rc=Rc) elif functional == 'Polynomial': func = Polynomial(Rc=Rc) elif functional == 'TangentH': func = TangentH(Rc=Rc) else: raise NotImplementedError('Unknown cutoff functional: %s' %functional) # Get core atoms information Ri = crystal.cart_coords[i] # Get neighbors information neighbors = crystal.get_all_neighbors(Rc) G4 = 0.0 for j in range(len(neighbors[i])-1): for k in range(j+1, len(neighbors[i])): n1 = neighbors[i][j][0].species_string n2 = neighbors[i][k][0].species_string if (ep_type[0] == n1 and ep_type[1] == n2) or \ (ep_type[1] == n1 and ep_type[0] == n2): Rj = neighbors[i][j][0].coords Rk = neighbors[i][k][0].coords Rij_vector = Rj - Ri Rij = np.linalg.norm(Rij_vector) Rik_vector = Rk - Ri Rik = np.linalg.norm(Rik_vector) Rjk_vector = Rk - Rj Rjk = np.linalg.norm(Rjk_vector) cos_ijk = np.dot(Rij_vector, Rik_vector)/ Rij / Rik term = (1. + lamBda * cos_ijk) ** zeta term *= np.exp(-eta * (Rij ** 2. + Rik ** 2. + Rjk ** 2.) / Rc ** 2.) term *= func(Rij) * func(Rik) * func(Rjk) G4 += term G4 *= 2. ** (1. - zeta) return G4
Python
def G4_prime(crystal, i, ep_type, ni, functional='Cosine', Rc=6.5, eta=2, lamBda=1, zeta=1, p=1, q=0): """ Calculate the derivative of the G4 symmetry function. Parameters ---------- crystal: object Pymatgen crystal structure object. i: int The index of core element. ep_types: str The allowed element pair presents in the symmetry function calculation. ni: array of neighbors information Neighbors information of the core element. functional: str Cutoff functional. Default is Cosine functional. Rc: float Cutoff radius which the symmetry function will be calculated. Default value is 6.5 as suggested by Behler. eta: float The parameter of G4 symmetry function. lamBda: float LamBda take values from -1 to +1 shifting the maxima of the cosine function to 0 to 180 degree. zeta: float The angular resolution. Zeta with high values give a narrower range of the nonzero G4 values. Different zeta values is preferrable for distribution of angles centered at each reference atom. In some sense, zeta is illustrated as the eta value. p: int The atom that the force is acting on. q: int Direction of force. Returns ------- G4p: float The derivative of G4 symmetry function. """ # Cutoff functional if functional == 'Cosine': func = Cosine(Rc=Rc) elif functional == 'Polynomial': func = Polynomial(Rc=Rc) elif functional == 'TangentH': func = TangentH(Rc=Rc) else: raise NotImplementedError('Unknown cutoff functional: %s' %functional) # Get positions of core atoms Ri = crystal.cart_coords[i] counts = range(len(ni)) G4p = 0 for j in counts: for k in counts[(j+1):]: n1 = ni[j][0].species_string n2 = ni[k][0].species_string if (ep_type[0] == n1 and ep_type[1] == n2) or \ (ep_type[1] == n1 and ep_type[0] == n2): Rj = ni[j][0].coords Rk = ni[k][0].coords Rij_vector = Rj - Ri Rij = np.linalg.norm(Rij_vector) Rik_vector = Rk - Ri Rik = np.linalg.norm(Rik_vector) Rjk_vector = Rk - Rj Rjk = np.linalg.norm(Rjk_vector) cos_ijk = np.dot(Rij_vector, Rik_vector)/ Rij / Rik dcos_ijk = dcos_dRpq(i, ni[j][2], ni[k][2], Ri, Rj, Rk, p, q) cutoff = func(Rij) * func(Rik) * func(Rjk) cutoff_Rik_Rjk = func(Rik) * func(Rjk) cutoff_Rij_Rjk = func(Rij) * func(Rjk) cutoff_Rij_Rik = func(Rij) * func(Rik) dRij = dRab_dRpq(i, ni[j][2], Ri, Rj, p, q) dRik = dRab_dRpq(i, ni[k][2], Ri, Rk, p, q) dRjk = dRab_dRpq(ni[j][2], ni[k][2], Rj, Rk, p, q) cutoff_Rij_derivative = func.derivative(Rij) * dRij cutoff_Rik_derivative = func.derivative(Rik) * dRik cutoff_Rjk_derivative = func.derivative(Rjk) * dRjk lamBda_term = 1. + lamBda * cos_ijk first_term = lamBda * zeta * dcos_ijk first_term += (-2. * eta * lamBda_term / (Rc ** 2)) * \ (Rij * dRij + Rik * dRik + Rjk * dRjk) first_term *= cutoff second_term = cutoff_Rij_derivative * cutoff_Rik_Rjk + \ cutoff_Rik_derivative * cutoff_Rij_Rjk + \ cutoff_Rjk_derivative * cutoff_Rij_Rik second_term *= lamBda_term term = first_term + second_term term *= lamBda_term ** (zeta - 1.) term *= np.exp(-eta * (Rij ** 2. + Rik ** 2. + Rjk ** 2.) / Rc ** 2.) G4p += term G4p *= 2. ** (1. - zeta) return G4p
def G4_prime(crystal, i, ep_type, ni, functional='Cosine', Rc=6.5, eta=2, lamBda=1, zeta=1, p=1, q=0): """ Calculate the derivative of the G4 symmetry function. Parameters ---------- crystal: object Pymatgen crystal structure object. i: int The index of core element. ep_types: str The allowed element pair presents in the symmetry function calculation. ni: array of neighbors information Neighbors information of the core element. functional: str Cutoff functional. Default is Cosine functional. Rc: float Cutoff radius which the symmetry function will be calculated. Default value is 6.5 as suggested by Behler. eta: float The parameter of G4 symmetry function. lamBda: float LamBda take values from -1 to +1 shifting the maxima of the cosine function to 0 to 180 degree. zeta: float The angular resolution. Zeta with high values give a narrower range of the nonzero G4 values. Different zeta values is preferrable for distribution of angles centered at each reference atom. In some sense, zeta is illustrated as the eta value. p: int The atom that the force is acting on. q: int Direction of force. Returns ------- G4p: float The derivative of G4 symmetry function. """ # Cutoff functional if functional == 'Cosine': func = Cosine(Rc=Rc) elif functional == 'Polynomial': func = Polynomial(Rc=Rc) elif functional == 'TangentH': func = TangentH(Rc=Rc) else: raise NotImplementedError('Unknown cutoff functional: %s' %functional) # Get positions of core atoms Ri = crystal.cart_coords[i] counts = range(len(ni)) G4p = 0 for j in counts: for k in counts[(j+1):]: n1 = ni[j][0].species_string n2 = ni[k][0].species_string if (ep_type[0] == n1 and ep_type[1] == n2) or \ (ep_type[1] == n1 and ep_type[0] == n2): Rj = ni[j][0].coords Rk = ni[k][0].coords Rij_vector = Rj - Ri Rij = np.linalg.norm(Rij_vector) Rik_vector = Rk - Ri Rik = np.linalg.norm(Rik_vector) Rjk_vector = Rk - Rj Rjk = np.linalg.norm(Rjk_vector) cos_ijk = np.dot(Rij_vector, Rik_vector)/ Rij / Rik dcos_ijk = dcos_dRpq(i, ni[j][2], ni[k][2], Ri, Rj, Rk, p, q) cutoff = func(Rij) * func(Rik) * func(Rjk) cutoff_Rik_Rjk = func(Rik) * func(Rjk) cutoff_Rij_Rjk = func(Rij) * func(Rjk) cutoff_Rij_Rik = func(Rij) * func(Rik) dRij = dRab_dRpq(i, ni[j][2], Ri, Rj, p, q) dRik = dRab_dRpq(i, ni[k][2], Ri, Rk, p, q) dRjk = dRab_dRpq(ni[j][2], ni[k][2], Rj, Rk, p, q) cutoff_Rij_derivative = func.derivative(Rij) * dRij cutoff_Rik_derivative = func.derivative(Rik) * dRik cutoff_Rjk_derivative = func.derivative(Rjk) * dRjk lamBda_term = 1. + lamBda * cos_ijk first_term = lamBda * zeta * dcos_ijk first_term += (-2. * eta * lamBda_term / (Rc ** 2)) * \ (Rij * dRij + Rik * dRik + Rjk * dRjk) first_term *= cutoff second_term = cutoff_Rij_derivative * cutoff_Rik_Rjk + \ cutoff_Rik_derivative * cutoff_Rij_Rjk + \ cutoff_Rjk_derivative * cutoff_Rij_Rik second_term *= lamBda_term term = first_term + second_term term *= lamBda_term ** (zeta - 1.) term *= np.exp(-eta * (Rij ** 2. + Rik ** 2. + Rjk ** 2.) / Rc ** 2.) G4p += term G4p *= 2. ** (1. - zeta) return G4p
Python
def G5(crystal, i, ep_type, functional='Cosine', Rc=6.5, eta=2, lamBda=1, zeta=1): """ Calculate G5 symmetry function. G5 function is also an angular function utilizing the cosine funtion of the angle theta_ijk centered at atom i. The difference between G5 and G4 is that G5 does not depend on the Rjk value. Hence, the G5 will generate a greater value after the summation compared to G4. One can refer to equation 9 in: Behler, J. (2011). Atom-centered symmetry functions for constructing high-dimensional neural network potentials. The Journal of chemical physics, 134(7), 074106. Parameters ---------- crystal: object Pymatgen crystal structure object. i: int The index of core element. ep_types: str The allowed element pair presents in the symmetry function calculation. functional: str Cutoff functional. Default is Cosine functional. Rc: float Cutoff radius which the symmetry function will be calculated. Default value is 6.5 as suggested by Behler. eta: float The parameter of G4 symmetry function. lamBda: float LamBda take values from -1 to +1 shifting the maxima of the cosine function to 0 to 180 degree. zeta: float The angular resolution. Zeta with high values give a narrower range of the nonzero G4 values. Different zeta values is preferrable for distribution of angles centered at each reference atom. In some sense, zeta is illustrated as the eta value. Returns ------- G5: float G5 symmetry value. """ # Cutoff functional if functional == 'Cosine': func = Cosine(Rc=Rc) elif functional == 'Polynomial': func = Polynomial(Rc=Rc) elif functional == 'TangentH': func = TangentH(Rc=Rc) else: raise NotImplementedError('Unknown cutoff functional: %s' %functional) # Get core atoms information Ri = crystal.cart_coords[i] # Get neighbors information neighbors = crystal.get_all_neighbors(Rc) G5 = 0.0 for j in range(len(neighbors[i])-1): for k in range(j+1, len(neighbors[i])): n1 = neighbors[i][j][0] n2 = neighbors[i][k][0] if (ep_type[0] == n1.species_string \ and ep_type[1] == n2.species_string) or \ (ep_type[1] == n1.species_string and \ ep_type[0] == n2.species_string): Rij_vector = Ri - n1.coords Rij = np.linalg.norm(Rij_vector) Rik_vector = Ri - n2.coords Rik = np.linalg.norm(Rik_vector) cos_ijk = np.dot(Rij_vector, Rik_vector)/ Rij / Rik term = (1. + lamBda * cos_ijk) ** zeta term *= np.exp(-eta * (Rij ** 2. + Rik ** 2.) / Rc ** 2.) term *= func(Rij) * func(Rik) G5 += term G5 *= 2. ** (1. - zeta) return G5
def G5(crystal, i, ep_type, functional='Cosine', Rc=6.5, eta=2, lamBda=1, zeta=1): """ Calculate G5 symmetry function. G5 function is also an angular function utilizing the cosine funtion of the angle theta_ijk centered at atom i. The difference between G5 and G4 is that G5 does not depend on the Rjk value. Hence, the G5 will generate a greater value after the summation compared to G4. One can refer to equation 9 in: Behler, J. (2011). Atom-centered symmetry functions for constructing high-dimensional neural network potentials. The Journal of chemical physics, 134(7), 074106. Parameters ---------- crystal: object Pymatgen crystal structure object. i: int The index of core element. ep_types: str The allowed element pair presents in the symmetry function calculation. functional: str Cutoff functional. Default is Cosine functional. Rc: float Cutoff radius which the symmetry function will be calculated. Default value is 6.5 as suggested by Behler. eta: float The parameter of G4 symmetry function. lamBda: float LamBda take values from -1 to +1 shifting the maxima of the cosine function to 0 to 180 degree. zeta: float The angular resolution. Zeta with high values give a narrower range of the nonzero G4 values. Different zeta values is preferrable for distribution of angles centered at each reference atom. In some sense, zeta is illustrated as the eta value. Returns ------- G5: float G5 symmetry value. """ # Cutoff functional if functional == 'Cosine': func = Cosine(Rc=Rc) elif functional == 'Polynomial': func = Polynomial(Rc=Rc) elif functional == 'TangentH': func = TangentH(Rc=Rc) else: raise NotImplementedError('Unknown cutoff functional: %s' %functional) # Get core atoms information Ri = crystal.cart_coords[i] # Get neighbors information neighbors = crystal.get_all_neighbors(Rc) G5 = 0.0 for j in range(len(neighbors[i])-1): for k in range(j+1, len(neighbors[i])): n1 = neighbors[i][j][0] n2 = neighbors[i][k][0] if (ep_type[0] == n1.species_string \ and ep_type[1] == n2.species_string) or \ (ep_type[1] == n1.species_string and \ ep_type[0] == n2.species_string): Rij_vector = Ri - n1.coords Rij = np.linalg.norm(Rij_vector) Rik_vector = Ri - n2.coords Rik = np.linalg.norm(Rik_vector) cos_ijk = np.dot(Rij_vector, Rik_vector)/ Rij / Rik term = (1. + lamBda * cos_ijk) ** zeta term *= np.exp(-eta * (Rij ** 2. + Rik ** 2.) / Rc ** 2.) term *= func(Rij) * func(Rik) G5 += term G5 *= 2. ** (1. - zeta) return G5
Python
def G5_prime(crystal, i, ep_type, ni, functional='Cosine', Rc=6.5, eta=2, lamBda=1, zeta=1, p=1, q=0): """ Calculate the derivative of the G5 symmetry function. Parameters ---------- crystal: object Pymatgen crystal structure object. i: int The index of core element. ep_types: str The allowed element pair presents in the symmetry function calculation. ni: array of neighbors information Neighbors information of the core element. functional: str Cutoff functional. Default is Cosine functional. Rc: float Cutoff radius which the symmetry function will be calculated. Default value is 6.5 as suggested by Behler. eta: float The parameter of G4 symmetry function. lamBda: float LamBda take values from -1 to +1 shifting the maxima of the cosine function to 0 to 180 degree. zeta: float The angular resolution. Zeta with high values give a narrower range of the nonzero G4 values. Different zeta values is preferrable for distribution of angles centered at each reference atom. In some sense, zeta is illustrated as the eta value. p: int The atom that the force is acting on. q: int Direction of force. Returns ------- G5p: float The derivative of G5 symmetry function. """ if functional == 'Cosine': func = Cosine(Rc=Rc) elif functional == 'Polynomial': func = Polynomial(Rc=Rc) elif functional == 'TangentH': func = TangentH(Rc=Rc) else: raise NotImplementedError('Unknown cutoff functional: %s' %functional) # Get positions of core atoms Ri = crystal.cart_coords[i] counts = range(len(ni)) G5p = 0 for j in counts: for k in counts[(j+1):]: n1 = ni[j][0].species_string n2 = ni[k][0].species_string if (ep_type[0] == n1 and ep_type[1] == n2) or \ (ep_type[1] == n1 and ep_type[0] == n2): Rj = ni[j][0].coords Rk = ni[k][0].coords Rij_vector = Rj - Ri Rik_vector = Rk - Ri Rij = np.linalg.norm(Rij_vector) Rik = np.linalg.norm(Rik_vector) cos_ijk = np.dot(Rij_vector, Rik_vector) / Rij / Rik dcos_ijk = dcos_dRpq(i, ni[j][2], ni[k][2], Ri, Rj, Rk, p, q) cutoff = func(Rij) * func(Rik) cutoff_Rij_derivative = func.derivative(Rij) * \ dRab_dRpq(i, ni[j][2], Ri, Rj, p, q) cutoff_Rik_derivative = func.derivative(Rik) * \ dRab_dRpq(i, ni[k][2], Ri, Rk, p, q) lamBda_term = 1. + lamBda * cos_ijk first_term = -2 * eta / Rc ** 2 * lamBda_term * \ (Rij * dRab_dRpq(i, ni[j][2], Ri, Rj, p, q) + Rik * dRab_dRpq(i, ni[k][2], Ri, Rk, p, q)) first_term += lamBda * zeta * dcos_ijk first_term *= cutoff second_term = lamBda_term * \ (cutoff_Rij_derivative * func(Rik) + cutoff_Rik_derivative * func(Rij)) term = first_term + second_term term *= lamBda_term ** (zeta - 1.) term *= np.exp(-eta * (Rij ** 2. + Rik ** 2.) / Rc ** 2.) G5p += term G5p *= 2. ** (1. - zeta) return G5p
def G5_prime(crystal, i, ep_type, ni, functional='Cosine', Rc=6.5, eta=2, lamBda=1, zeta=1, p=1, q=0): """ Calculate the derivative of the G5 symmetry function. Parameters ---------- crystal: object Pymatgen crystal structure object. i: int The index of core element. ep_types: str The allowed element pair presents in the symmetry function calculation. ni: array of neighbors information Neighbors information of the core element. functional: str Cutoff functional. Default is Cosine functional. Rc: float Cutoff radius which the symmetry function will be calculated. Default value is 6.5 as suggested by Behler. eta: float The parameter of G4 symmetry function. lamBda: float LamBda take values from -1 to +1 shifting the maxima of the cosine function to 0 to 180 degree. zeta: float The angular resolution. Zeta with high values give a narrower range of the nonzero G4 values. Different zeta values is preferrable for distribution of angles centered at each reference atom. In some sense, zeta is illustrated as the eta value. p: int The atom that the force is acting on. q: int Direction of force. Returns ------- G5p: float The derivative of G5 symmetry function. """ if functional == 'Cosine': func = Cosine(Rc=Rc) elif functional == 'Polynomial': func = Polynomial(Rc=Rc) elif functional == 'TangentH': func = TangentH(Rc=Rc) else: raise NotImplementedError('Unknown cutoff functional: %s' %functional) # Get positions of core atoms Ri = crystal.cart_coords[i] counts = range(len(ni)) G5p = 0 for j in counts: for k in counts[(j+1):]: n1 = ni[j][0].species_string n2 = ni[k][0].species_string if (ep_type[0] == n1 and ep_type[1] == n2) or \ (ep_type[1] == n1 and ep_type[0] == n2): Rj = ni[j][0].coords Rk = ni[k][0].coords Rij_vector = Rj - Ri Rik_vector = Rk - Ri Rij = np.linalg.norm(Rij_vector) Rik = np.linalg.norm(Rik_vector) cos_ijk = np.dot(Rij_vector, Rik_vector) / Rij / Rik dcos_ijk = dcos_dRpq(i, ni[j][2], ni[k][2], Ri, Rj, Rk, p, q) cutoff = func(Rij) * func(Rik) cutoff_Rij_derivative = func.derivative(Rij) * \ dRab_dRpq(i, ni[j][2], Ri, Rj, p, q) cutoff_Rik_derivative = func.derivative(Rik) * \ dRab_dRpq(i, ni[k][2], Ri, Rk, p, q) lamBda_term = 1. + lamBda * cos_ijk first_term = -2 * eta / Rc ** 2 * lamBda_term * \ (Rij * dRab_dRpq(i, ni[j][2], Ri, Rj, p, q) + Rik * dRab_dRpq(i, ni[k][2], Ri, Rk, p, q)) first_term += lamBda * zeta * dcos_ijk first_term *= cutoff second_term = lamBda_term * \ (cutoff_Rij_derivative * func(Rik) + cutoff_Rik_derivative * func(Rij)) term = first_term + second_term term *= lamBda_term ** (zeta - 1.) term *= np.exp(-eta * (Rij ** 2. + Rik ** 2.) / Rc ** 2.) G5p += term G5p *= 2. ** (1. - zeta) return G5p
Python
def angle_from_ijkl(p1, p2, p3, p4): """ compute dihedral angle from four points, we consider only -90 to 90 for simplicity """ if angle_from_ijk(p1, p2, p3) == 180 or angle_from_ijk(p2, p3, p4) == 180: return 0.0 else: v1, v2, v3 = p3-p4, p2-p3, p1-p2 v23 = np.cross(v2, v3) v12 = np.cross(v1, v2) angle = np.degrees(math.atan(np.linalg.norm(v2) * np.dot(v1, v23)/np.dot(v12, v23))) #if angle < 0: print(np.linalg.norm(v2) * np.dot(v1, v23)/np.dot(v12, v23), angle) if abs(angle+90.0) < 5e-1: angle = 90 return angle
def angle_from_ijkl(p1, p2, p3, p4): """ compute dihedral angle from four points, we consider only -90 to 90 for simplicity """ if angle_from_ijk(p1, p2, p3) == 180 or angle_from_ijk(p2, p3, p4) == 180: return 0.0 else: v1, v2, v3 = p3-p4, p2-p3, p1-p2 v23 = np.cross(v2, v3) v12 = np.cross(v1, v2) angle = np.degrees(math.atan(np.linalg.norm(v2) * np.dot(v1, v23)/np.dot(v12, v23))) #if angle < 0: print(np.linalg.norm(v2) * np.dot(v1, v23)/np.dot(v12, v23), angle) if abs(angle+90.0) < 5e-1: angle = 90 return angle
Python
def read_chunk(f, start, count): """ move around inside gigantor file and return the gzip'd embed """ #print("read_chunk start,count= ",start,count) f.seek(start+256) # offset plus header ## SKIP: nothing of value in header? chunk = BytesIO(f.read(count-256)) return gzip.GzipFile(fileobj=chunk)
def read_chunk(f, start, count): """ move around inside gigantor file and return the gzip'd embed """ #print("read_chunk start,count= ",start,count) f.seek(start+256) # offset plus header ## SKIP: nothing of value in header? chunk = BytesIO(f.read(count-256)) return gzip.GzipFile(fileobj=chunk)
Python
def all_pdn_moves(): """ returns a list with all possible moves that can occur in a game situation. the notation is like pdn, the start and the destination square are separated by a minus for normal moves and by a x for a capture. capture sequences are not considered in this list. only one capture step is defined. if multiple captures are possible they are executed until the player needs to make a new decision. this is a special game state where the player needs to make two moves in a row. :return: """ # create the board with the move notation on it board = np.zeros((8, 8)) count = 1 for row in range(7, -1, -1): for col in range(7, -1, -1): if row % 2 == 0 and col % 2 == 1: board[row][col] = count count += 1 if row % 2 == 1 and col % 2 == 0: board[row][col] = count count += 1 # find all moves with no captures moves = [] for row in range(7, -1, -1): for col in range(7, -1, -1): # skip squares that are not part of the state space if board[row][col] < 1: continue for direction in directions: # create the new index from_pos = (row, col) to_pos = add_tuples(from_pos, direction) if not is_valid_index(to_pos): continue moves.append("{}-{}".format(int(board[from_pos]), int(board[to_pos]))) # all capture moves for row in range(7, -1, -1): for col in range(7, -1, -1): # skip squares that are not part of the state space if board[row][col] < 1: continue for direction in capture_dirs: # create the new index from_pos = (row, col) to_pos = add_tuples(from_pos, direction) if not is_valid_index(to_pos): continue moves.append("{}x{}".format(int(board[from_pos]), int(board[to_pos]))) return moves
def all_pdn_moves(): """ returns a list with all possible moves that can occur in a game situation. the notation is like pdn, the start and the destination square are separated by a minus for normal moves and by a x for a capture. capture sequences are not considered in this list. only one capture step is defined. if multiple captures are possible they are executed until the player needs to make a new decision. this is a special game state where the player needs to make two moves in a row. :return: """ # create the board with the move notation on it board = np.zeros((8, 8)) count = 1 for row in range(7, -1, -1): for col in range(7, -1, -1): if row % 2 == 0 and col % 2 == 1: board[row][col] = count count += 1 if row % 2 == 1 and col % 2 == 0: board[row][col] = count count += 1 # find all moves with no captures moves = [] for row in range(7, -1, -1): for col in range(7, -1, -1): # skip squares that are not part of the state space if board[row][col] < 1: continue for direction in directions: # create the new index from_pos = (row, col) to_pos = add_tuples(from_pos, direction) if not is_valid_index(to_pos): continue moves.append("{}-{}".format(int(board[from_pos]), int(board[to_pos]))) # all capture moves for row in range(7, -1, -1): for col in range(7, -1, -1): # skip squares that are not part of the state space if board[row][col] < 1: continue for direction in capture_dirs: # create the new index from_pos = (row, col) to_pos = add_tuples(from_pos, direction) if not is_valid_index(to_pos): continue moves.append("{}x{}".format(int(board[from_pos]), int(board[to_pos]))) return moves
Python
def all_moves(pdn_moves): """ returns a list of moves in the bit board representation. a move is defined by an integer that has two bits turned on, the start and the end square. if it is a backwards move (from the white perspective) the backwards bit is set as well in order to have a unique move definition :param pdn_moves: list of all pdn moves :return: """ moves = [] for pdn_move in pdn_moves: # convert normal moves to the integer representation if "-" in pdn_move: pos_str = pdn_move.split("-") from_square = int(pos_str[0]) - 1 from_square = from_square + from_square // 8 to_square = int(pos_str[1]) - 1 to_square = to_square + to_square // 8 move = (1 << from_square) + (1 << to_square) if from_square > to_square: move += BAKWARDS_BIT moves.append(move) # convert capture moves to the integer representation if "x" in pdn_move: pos_str = pdn_move.split("x") from_square = int(pos_str[0]) - 1 from_square = from_square + from_square // 8 to_square = int(pos_str[1]) - 1 to_square = to_square + to_square // 8 move = (1 << from_square) + (1 << to_square) if from_square > to_square: move += BAKWARDS_BIT move *= -1 moves.append(move) return moves
def all_moves(pdn_moves): """ returns a list of moves in the bit board representation. a move is defined by an integer that has two bits turned on, the start and the end square. if it is a backwards move (from the white perspective) the backwards bit is set as well in order to have a unique move definition :param pdn_moves: list of all pdn moves :return: """ moves = [] for pdn_move in pdn_moves: # convert normal moves to the integer representation if "-" in pdn_move: pos_str = pdn_move.split("-") from_square = int(pos_str[0]) - 1 from_square = from_square + from_square // 8 to_square = int(pos_str[1]) - 1 to_square = to_square + to_square // 8 move = (1 << from_square) + (1 << to_square) if from_square > to_square: move += BAKWARDS_BIT moves.append(move) # convert capture moves to the integer representation if "x" in pdn_move: pos_str = pdn_move.split("x") from_square = int(pos_str[0]) - 1 from_square = from_square + from_square // 8 to_square = int(pos_str[1]) - 1 to_square = to_square + to_square // 8 move = (1 << from_square) + (1 << to_square) if from_square > to_square: move += BAKWARDS_BIT move *= -1 moves.append(move) return moves
Python
def create_move_dicts(pdn_moves, moves): """ creates two dictionaries to convert pdn_moves to moves. the pdn_moves and the moves need to have the same order :param pdn_moves: a list of pdn-moves :param moves: a list of moves :return: """ pdn_dict = {} move_dict = {} for pdn_move, move in zip(pdn_moves, moves): pdn_dict[pdn_move] = move move_dict[move] = pdn_move return pdn_dict, move_dict
def create_move_dicts(pdn_moves, moves): """ creates two dictionaries to convert pdn_moves to moves. the pdn_moves and the moves need to have the same order :param pdn_moves: a list of pdn-moves :param moves: a list of moves :return: """ pdn_dict = {} move_dict = {} for pdn_move, move in zip(pdn_moves, moves): pdn_dict[pdn_move] = move move_dict[move] = pdn_move return pdn_dict, move_dict
Python
def move_action_dict(moves): """ returns a lookup table with the move as key and the policy index as value :param moves: all possible moves :return: """ lookup_table = {} for i, label in enumerate(moves): lookup_table[label] = i return lookup_table
def move_action_dict(moves): """ returns a lookup table with the move as key and the policy index as value :param moves: all possible moves :return: """ lookup_table = {} for i, label in enumerate(moves): lookup_table[label] = i return lookup_table
Python
def reverse_bits(n, bit_count): """ reversed the order of the bits in the passed number :param n: number of which the bits are reversed :param bit_count: the number of bits that are used for the passed number :return: """ rev = 0 # traversing bits of 'n' from the right for _ in range(bit_count): rev <<= 1 if n & 1: rev = rev ^ 1 n >>= 1 return rev
def reverse_bits(n, bit_count): """ reversed the order of the bits in the passed number :param n: number of which the bits are reversed :param bit_count: the number of bits that are used for the passed number :return: """ rev = 0 # traversing bits of 'n' from the right for _ in range(bit_count): rev <<= 1 if n & 1: rev = rev ^ 1 n >>= 1 return rev
Python
def mirror_move(move): """ converts a move for one player to a move for the other player :param move: the move to convert :return: """ # change the sign to a positive sign is_capture = move < 0 if is_capture: move *= -1 # remove the backwards bit is_backwards = move & BAKWARDS_BIT move &= ALL_BITS # reverse the bits of the move reversed_move = reverse_bits(move, 35) # forward move become backwards move and vice versa if not is_backwards: reversed_move += BAKWARDS_BIT # set the capture information if is_capture: reversed_move *= -1 return reversed_move
def mirror_move(move): """ converts a move for one player to a move for the other player :param move: the move to convert :return: """ # change the sign to a positive sign is_capture = move < 0 if is_capture: move *= -1 # remove the backwards bit is_backwards = move & BAKWARDS_BIT move &= ALL_BITS # reverse the bits of the move reversed_move = reverse_bits(move, 35) # forward move become backwards move and vice versa if not is_backwards: reversed_move += BAKWARDS_BIT # set the capture information if is_capture: reversed_move *= -1 return reversed_move
Python
def action_to_move(action, player): """ converts the passed action to a checkers move. as the action is always defined from the white perspective it needs to be mirrored for the black player :param action: move policy vector :param player: the current player :return: move that can be played on the board """ # convert the action to a checkers move move = MOVES[action] # mirror the move for the black player if player == CONST.BLACK: move = mirror_move(move) return move
def action_to_move(action, player): """ converts the passed action to a checkers move. as the action is always defined from the white perspective it needs to be mirrored for the black player :param action: move policy vector :param player: the current player :return: move that can be played on the board """ # convert the action to a checkers move move = MOVES[action] # mirror the move for the black player if player == CONST.BLACK: move = mirror_move(move) return move
Python
def move_to_action(move, player): """ returns the action that corresponds to the passed move to play :param move: checkers move :param player: current player :return: """ # mirror the the moves for the black player since the board is always viewed from the white perspective if player == CONST.BLACK: move = mirror_move(move) action = MOVE_ACTION_DICT[move] return action
def move_to_action(move, player): """ returns the action that corresponds to the passed move to play :param move: checkers move :param player: current player :return: """ # mirror the the moves for the black player since the board is always viewed from the white perspective if player == CONST.BLACK: move = mirror_move(move) action = MOVE_ACTION_DICT[move] return action
Python
def execute_action(self, action): """ executes the passed move on the baord, a move is represented by an integer that has the start and the end bit turned on :param action: the action to play on the checkers board """ # create a move from the passed action move = action_to_move(action, self.player) # increment the no progress count, it will be set to 0 later on if either a man moved or a piece as captured self.no_progress_count += 1 # execute the capture if move < 0: self.no_progress_count = 0 # reset the no progress count as a piece was captured is_capture = True # remove the backwards bit move *= -1 move &= ALL_BITS # the average of the bit position is the captured piece captured_disk = int(1 << sum(i for (i, b) in enumerate(bin(move)[::-1]) if b == '1')//2) if self.player == CONST.WHITE: # remove the captured opponent disk if self.black_disks & captured_disk: self.black_disks ^= captured_disk if self.black_kings & captured_disk: self.black_kings ^= captured_disk else: # remove the captured opponent disk if self.white_disks & captured_disk: self.white_disks ^= captured_disk if self.white_kings & captured_disk: self.white_kings ^= captured_disk else: is_capture = False move &= ALL_BITS # remove the backwards bit # execute the move if self.player == CONST.WHITE: # set the disk at the new position if self.white_disks & move: self.white_disks ^= move if self.white_kings & move: self.white_kings ^= move # reset the no progress count if a man moved if (self.white_disks ^ self.white_kings) & move: self.no_progress_count = 0 # check if white made a king to_square = move & self.white_disks if to_square & BLACK_BACKRANK_BITS: self.white_kings |= to_square else: # set the disk at the new position if self.black_disks & move: self.black_disks ^= move if self.black_kings & move: self.black_kings ^= move # reset the no progress count if a man moved if (self.black_disks ^ self.black_kings) & move: self.no_progress_count = 0 # check if black made a king to_square = move & self.black_disks if to_square & WHITE_BACKRANK_BITS: self.black_kings |= to_square # update the empty squares self.empty = SKIP_BITS ^ ALL_BITS ^ (self.white_disks | self.black_disks) # check if there are still possible capture moves if is_capture: self.mandatory_captures = self.captures_from_position(to_square) capture_count = len(self.mandatory_captures) # only one mandatory capture, execute it if capture_count == 1: capture_action = move_to_action(self.mandatory_captures[0], self.player) self.execute_action(capture_action) return # more than one capture, the same player needs to decide which capture to execute elif capture_count > 1: return # no mandatory captures, change the player self.move_count += 1 self.player = self.move_count % 2 # find the new capture moves self.mandatory_captures = self.all_captures() # check if the game has ended self.check_terminal()
def execute_action(self, action): """ executes the passed move on the baord, a move is represented by an integer that has the start and the end bit turned on :param action: the action to play on the checkers board """ # create a move from the passed action move = action_to_move(action, self.player) # increment the no progress count, it will be set to 0 later on if either a man moved or a piece as captured self.no_progress_count += 1 # execute the capture if move < 0: self.no_progress_count = 0 # reset the no progress count as a piece was captured is_capture = True # remove the backwards bit move *= -1 move &= ALL_BITS # the average of the bit position is the captured piece captured_disk = int(1 << sum(i for (i, b) in enumerate(bin(move)[::-1]) if b == '1')//2) if self.player == CONST.WHITE: # remove the captured opponent disk if self.black_disks & captured_disk: self.black_disks ^= captured_disk if self.black_kings & captured_disk: self.black_kings ^= captured_disk else: # remove the captured opponent disk if self.white_disks & captured_disk: self.white_disks ^= captured_disk if self.white_kings & captured_disk: self.white_kings ^= captured_disk else: is_capture = False move &= ALL_BITS # remove the backwards bit # execute the move if self.player == CONST.WHITE: # set the disk at the new position if self.white_disks & move: self.white_disks ^= move if self.white_kings & move: self.white_kings ^= move # reset the no progress count if a man moved if (self.white_disks ^ self.white_kings) & move: self.no_progress_count = 0 # check if white made a king to_square = move & self.white_disks if to_square & BLACK_BACKRANK_BITS: self.white_kings |= to_square else: # set the disk at the new position if self.black_disks & move: self.black_disks ^= move if self.black_kings & move: self.black_kings ^= move # reset the no progress count if a man moved if (self.black_disks ^ self.black_kings) & move: self.no_progress_count = 0 # check if black made a king to_square = move & self.black_disks if to_square & WHITE_BACKRANK_BITS: self.black_kings |= to_square # update the empty squares self.empty = SKIP_BITS ^ ALL_BITS ^ (self.white_disks | self.black_disks) # check if there are still possible capture moves if is_capture: self.mandatory_captures = self.captures_from_position(to_square) capture_count = len(self.mandatory_captures) # only one mandatory capture, execute it if capture_count == 1: capture_action = move_to_action(self.mandatory_captures[0], self.player) self.execute_action(capture_action) return # more than one capture, the same player needs to decide which capture to execute elif capture_count > 1: return # no mandatory captures, change the player self.move_count += 1 self.player = self.move_count % 2 # find the new capture moves self.mandatory_captures = self.all_captures() # check if the game has ended self.check_terminal()
Python
def legal_actions(self): """ returns a list with all legal actions :return: """ # check if there are some captures if len(self.mandatory_captures) > 0: if self.player == CONST.WHITE: actions = [MOVE_ACTION_DICT[move] for move in self.mandatory_captures] else: actions = [MOVE_ACTION_DICT[mirror_move(move)] for move in self.mandatory_captures] return actions # no captures possible, find normal moves if self.player == CONST.WHITE: rf = (self.empty >> 4) & self.white_disks # right forward move lf = (self.empty >> 5) & self.white_disks # left forward move rb = (self.empty << 4) & self.white_kings # right backwards move lb = (self.empty << 5) & self.white_kings # left backwards move else: rf = (self.empty >> 4) & self.black_kings # right forward move lf = (self.empty >> 5) & self.black_kings # left forward move rb = (self.empty << 4) & self.black_disks # right backwards move lb = (self.empty << 5) & self.black_disks # left backwards move moves = [0x11 << i for (i, bit) in enumerate(bin(rf)[::-1]) if bit == '1'] moves += [0x21 << i for (i, bit) in enumerate(bin(lf)[::-1]) if bit == '1'] moves += [BAKWARDS_BIT + (0x11 << (i - 4)) for (i, bit) in enumerate(bin(rb)[::-1]) if bit == '1'] moves += [BAKWARDS_BIT + (0x21 << (i - 5)) for (i, bit) in enumerate(bin(lb)[::-1]) if bit == '1'] if self.player == CONST.WHITE: actions = [MOVE_ACTION_DICT[move] for move in moves] else: actions = [MOVE_ACTION_DICT[mirror_move(move)] for move in moves] # mirror the moves for black return actions
def legal_actions(self): """ returns a list with all legal actions :return: """ # check if there are some captures if len(self.mandatory_captures) > 0: if self.player == CONST.WHITE: actions = [MOVE_ACTION_DICT[move] for move in self.mandatory_captures] else: actions = [MOVE_ACTION_DICT[mirror_move(move)] for move in self.mandatory_captures] return actions # no captures possible, find normal moves if self.player == CONST.WHITE: rf = (self.empty >> 4) & self.white_disks # right forward move lf = (self.empty >> 5) & self.white_disks # left forward move rb = (self.empty << 4) & self.white_kings # right backwards move lb = (self.empty << 5) & self.white_kings # left backwards move else: rf = (self.empty >> 4) & self.black_kings # right forward move lf = (self.empty >> 5) & self.black_kings # left forward move rb = (self.empty << 4) & self.black_disks # right backwards move lb = (self.empty << 5) & self.black_disks # left backwards move moves = [0x11 << i for (i, bit) in enumerate(bin(rf)[::-1]) if bit == '1'] moves += [0x21 << i for (i, bit) in enumerate(bin(lf)[::-1]) if bit == '1'] moves += [BAKWARDS_BIT + (0x11 << (i - 4)) for (i, bit) in enumerate(bin(rb)[::-1]) if bit == '1'] moves += [BAKWARDS_BIT + (0x21 << (i - 5)) for (i, bit) in enumerate(bin(lb)[::-1]) if bit == '1'] if self.player == CONST.WHITE: actions = [MOVE_ACTION_DICT[move] for move in moves] else: actions = [MOVE_ACTION_DICT[mirror_move(move)] for move in moves] # mirror the moves for black return actions
Python
def illegal_actions(self): """ returns a list of illegal actions :return: """ legal_actions = self.legal_actions() illegal_actions = [a for a in range(Config.tot_actions)] for legal_action in legal_actions: illegal_actions.remove(legal_action) return illegal_actions
def illegal_actions(self): """ returns a list of illegal actions :return: """ legal_actions = self.legal_actions() illegal_actions = [a for a in range(Config.tot_actions)] for legal_action in legal_actions: illegal_actions.remove(legal_action) return illegal_actions
Python
def check_terminal(self): """ checks if the game is terminal :return: """ # check if the current player can move if len(self.legal_actions()) == 0: self.score = 1 if self.player == CONST.BLACK else -1 self.terminal = True return # if there are some captures the game is not drawn if len(self.mandatory_captures) > 0: return # the game is drawn if during the last 40 moves no men was moved or no piece was captured if self.no_progress_count >= 80: self.score = 0 self.terminal = True return # rule out some basic endgames to shorten the games popcount_kings_w = utils.popcount(self.white_kings) popcount_kings_b = utils.popcount(self.black_kings) # no men if (self.white_disks ^ self.white_kings) == 0 and (self.black_disks ^ self.black_kings) == 0: # same king count which is not larger than 3 is a draw if popcount_kings_w <= 3 and popcount_kings_w == popcount_kings_b: self.score = 0 self.terminal = True return if popcount_kings_w <= 3 and popcount_kings_b <= 3: if popcount_kings_w > popcount_kings_b: self.score = 1 self.terminal = True return if popcount_kings_b > popcount_kings_w: self.score = -1 self.terminal = True return
def check_terminal(self): """ checks if the game is terminal :return: """ # check if the current player can move if len(self.legal_actions()) == 0: self.score = 1 if self.player == CONST.BLACK else -1 self.terminal = True return # if there are some captures the game is not drawn if len(self.mandatory_captures) > 0: return # the game is drawn if during the last 40 moves no men was moved or no piece was captured if self.no_progress_count >= 80: self.score = 0 self.terminal = True return # rule out some basic endgames to shorten the games popcount_kings_w = utils.popcount(self.white_kings) popcount_kings_b = utils.popcount(self.black_kings) # no men if (self.white_disks ^ self.white_kings) == 0 and (self.black_disks ^ self.black_kings) == 0: # same king count which is not larger than 3 is a draw if popcount_kings_w <= 3 and popcount_kings_w == popcount_kings_b: self.score = 0 self.terminal = True return if popcount_kings_w <= 3 and popcount_kings_b <= 3: if popcount_kings_w > popcount_kings_b: self.score = 1 self.terminal = True return if popcount_kings_b > popcount_kings_w: self.score = -1 self.terminal = True return
Python
def captures_from_position(self, position_mask): """ returns a list of all possible captures form the passed position :param position_mask: disk position to analyze :return: list of all possible capture moves """ # the rules for a successful capture are empty at the destination and an opponent disk inbetween # the start and the end square if self.player == CONST.WHITE: # captures for men rfc = (self.empty >> 8) & (self.black_disks >> 4) & position_mask # right forward capture lfc = (self.empty >> 10) & (self.black_disks >> 5) & position_mask # left forward capture # captures for kings if position_mask & self.black_kings: rbc = (self.empty << 8) & (self.black_disks << 4) & position_mask # right backwards capture lbc = (self.empty << 10) & (self.black_disks << 5) & position_mask # left backwards capture else: rbc = 0 lbc = 0 else: # captures for men rbc = (self.empty << 8) & (self.white_disks << 4) & position_mask # right backwards capture lbc = (self.empty << 10) & (self.white_disks << 5) & position_mask # left backwards capture # captures for kings if position_mask & self.white_kings: rfc = (self.empty >> 8) & (self.white_disks >> 4) & position_mask # right forward capture lfc = (self.empty >> 10) & (self.white_disks >> 5) & position_mask # left forward capture else: rfc = 0 lfc = 0 capture_moves = [] if (rfc | lfc | rbc | lbc) != 0: capture_moves += [-0x101 << i for (i, bit) in enumerate(bin(rfc)[::-1]) if bit == '1'] capture_moves += [-0x401 << i for (i, bit) in enumerate(bin(lfc)[::-1]) if bit == '1'] capture_moves += [-BAKWARDS_BIT - (0x101 << (i - 8)) for (i, bit) in enumerate(bin(rbc)[::-1]) if bit == '1'] capture_moves += [-BAKWARDS_BIT - (0x401 << (i - 10)) for (i, bit) in enumerate(bin(lbc)[::-1]) if bit == '1'] return capture_moves
def captures_from_position(self, position_mask): """ returns a list of all possible captures form the passed position :param position_mask: disk position to analyze :return: list of all possible capture moves """ # the rules for a successful capture are empty at the destination and an opponent disk inbetween # the start and the end square if self.player == CONST.WHITE: # captures for men rfc = (self.empty >> 8) & (self.black_disks >> 4) & position_mask # right forward capture lfc = (self.empty >> 10) & (self.black_disks >> 5) & position_mask # left forward capture # captures for kings if position_mask & self.black_kings: rbc = (self.empty << 8) & (self.black_disks << 4) & position_mask # right backwards capture lbc = (self.empty << 10) & (self.black_disks << 5) & position_mask # left backwards capture else: rbc = 0 lbc = 0 else: # captures for men rbc = (self.empty << 8) & (self.white_disks << 4) & position_mask # right backwards capture lbc = (self.empty << 10) & (self.white_disks << 5) & position_mask # left backwards capture # captures for kings if position_mask & self.white_kings: rfc = (self.empty >> 8) & (self.white_disks >> 4) & position_mask # right forward capture lfc = (self.empty >> 10) & (self.white_disks >> 5) & position_mask # left forward capture else: rfc = 0 lfc = 0 capture_moves = [] if (rfc | lfc | rbc | lbc) != 0: capture_moves += [-0x101 << i for (i, bit) in enumerate(bin(rfc)[::-1]) if bit == '1'] capture_moves += [-0x401 << i for (i, bit) in enumerate(bin(lfc)[::-1]) if bit == '1'] capture_moves += [-BAKWARDS_BIT - (0x101 << (i - 8)) for (i, bit) in enumerate(bin(rbc)[::-1]) if bit == '1'] capture_moves += [-BAKWARDS_BIT - (0x401 << (i - 10)) for (i, bit) in enumerate(bin(lbc)[::-1]) if bit == '1'] return capture_moves
Python
def all_captures(self): """ returns a list of all captures of the current position :return: """ if self.player == CONST.WHITE: rfc = (self.empty >> 8) & (self.black_disks >> 4) & self.white_disks # right forward capture lfc = (self.empty >> 10) & (self.black_disks >> 5) & self.white_disks # left forward capture rbc = (self.empty << 8) & (self.black_disks << 4) & self.white_kings # right backwards capture lbc = (self.empty << 10) & (self.black_disks << 5) & self.white_kings # left backwards capture else: rfc = (self.empty >> 8) & (self.white_disks >> 4) & self.black_kings # right forward capture lfc = (self.empty >> 10) & (self.white_disks >> 5) & self.black_kings # left forward capture rbc = (self.empty << 8) & (self.white_disks << 4) & self.black_disks # right backwards capture lbc = (self.empty << 10) & (self.white_disks << 5) & self.black_disks # left backwards capture capture_moves = [] if (rfc | lfc | rbc | lbc) != 0: capture_moves += [-0x101 << i for (i, bit) in enumerate(bin(rfc)[::-1]) if bit == '1'] capture_moves += [-0x401 << i for (i, bit) in enumerate(bin(lfc)[::-1]) if bit == '1'] capture_moves += [-BAKWARDS_BIT - (0x101 << (i - 8)) for (i, bit) in enumerate(bin(rbc)[::-1]) if bit == '1'] capture_moves += [-BAKWARDS_BIT - (0x401 << (i - 10)) for (i, bit) in enumerate(bin(lbc)[::-1]) if bit == '1'] return capture_moves
def all_captures(self): """ returns a list of all captures of the current position :return: """ if self.player == CONST.WHITE: rfc = (self.empty >> 8) & (self.black_disks >> 4) & self.white_disks # right forward capture lfc = (self.empty >> 10) & (self.black_disks >> 5) & self.white_disks # left forward capture rbc = (self.empty << 8) & (self.black_disks << 4) & self.white_kings # right backwards capture lbc = (self.empty << 10) & (self.black_disks << 5) & self.white_kings # left backwards capture else: rfc = (self.empty >> 8) & (self.white_disks >> 4) & self.black_kings # right forward capture lfc = (self.empty >> 10) & (self.white_disks >> 5) & self.black_kings # left forward capture rbc = (self.empty << 8) & (self.white_disks << 4) & self.black_disks # right backwards capture lbc = (self.empty << 10) & (self.white_disks << 5) & self.black_disks # left backwards capture capture_moves = [] if (rfc | lfc | rbc | lbc) != 0: capture_moves += [-0x101 << i for (i, bit) in enumerate(bin(rfc)[::-1]) if bit == '1'] capture_moves += [-0x401 << i for (i, bit) in enumerate(bin(lfc)[::-1]) if bit == '1'] capture_moves += [-BAKWARDS_BIT - (0x101 << (i - 8)) for (i, bit) in enumerate(bin(rbc)[::-1]) if bit == '1'] capture_moves += [-BAKWARDS_BIT - (0x401 << (i - 10)) for (i, bit) in enumerate(bin(lbc)[::-1]) if bit == '1'] return capture_moves
Python
def print(self): """ prints out the board in human readable form :return: """ print(self.to_string())
def print(self): """ prints out the board in human readable form :return: """ print(self.to_string())
Python
def int_to_board(number): """ converts the passed integer to the board representation :param number: integer to convert to one channel of the neural network input :return: """ board = np.zeros((8, 8)) pos = -1 for row in range(7, -1, -1): for col in range(7, -1, -1): if row % 2 == 0 and col % 2 == 1: pos += 1 elif row % 2 == 1 and col % 2 == 0: pos += 1 else: continue # field not used shift = pos + pos // 8 cell = 1 << shift if cell & number: board[row][col] = 1 return board
def int_to_board(number): """ converts the passed integer to the board representation :param number: integer to convert to one channel of the neural network input :return: """ board = np.zeros((8, 8)) pos = -1 for row in range(7, -1, -1): for col in range(7, -1, -1): if row % 2 == 0 and col % 2 == 1: pos += 1 elif row % 2 == 1 and col % 2 == 0: pos += 1 else: continue # field not used shift = pos + pos // 8 cell = 1 << shift if cell & number: board[row][col] = 1 return board
Python
def int_to_mirrored_board(number): """ converts the passed integer to the board representation that is rotated :param number: integer to convert to one channel of the neural network input :return: """ board = np.zeros((8, 8)) pos = -1 for row in range(8): for col in range(8): if row % 2 == 0 and col % 2 == 1: pos += 1 elif row % 2 == 1 and col % 2 == 0: pos += 1 else: continue # field not used shift = pos + pos // 8 cell = 1 << shift if cell & number: board[row][col] = 1 return board
def int_to_mirrored_board(number): """ converts the passed integer to the board representation that is rotated :param number: integer to convert to one channel of the neural network input :return: """ board = np.zeros((8, 8)) pos = -1 for row in range(8): for col in range(8): if row % 2 == 0 and col % 2 == 1: pos += 1 elif row % 2 == 1 and col % 2 == 0: pos += 1 else: continue # field not used shift = pos + pos // 8 cell = 1 << shift if cell & number: board[row][col] = 1 return board
Python
def play_self_play_games(self, game_class, network_path): """ plays some games against itself and adds the experience into the experience buffer :param game_class the class of the implemented games :param network_path the path of the current network :return: the average nu,ber of moves played in a games """ # execute the self-play self_play_results = __self_play_worker__(game_class, network_path, config.episodes) # add the training examples to the experience buffer self.experience_buffer.add_new_cycle() tot_moves_played = len(self_play_results) / game_class.symmetry_count() # account for symmetric boards, self.experience_buffer.add_data(self_play_results) avg_game_length = tot_moves_played / config.episodes return avg_game_length
def play_self_play_games(self, game_class, network_path): """ plays some games against itself and adds the experience into the experience buffer :param game_class the class of the implemented games :param network_path the path of the current network :return: the average nu,ber of moves played in a games """ # execute the self-play self_play_results = __self_play_worker__(game_class, network_path, config.episodes) # add the training examples to the experience buffer self.experience_buffer.add_new_cycle() tot_moves_played = len(self_play_results) / game_class.symmetry_count() # account for symmetric boards, self.experience_buffer.add_data(self_play_results) avg_game_length = tot_moves_played / config.episodes return avg_game_length
Python
def nn_update(self, generation): """ updates the neural network by picking a random batch form the experience replay :param generation: the network generation (number of iterations so far) :return: average policy and value loss over all mini batches """ # setup the data set training_generator = self.experience_buffer.prepare_data(generation) step_size = training_generator.dataset.__len__() // (2 * config.batch_size) logger.info("training data prepared, step size: {}".format(step_size)) # activate the training mode self.network = data_storage.net_to_device(self.network, config.training_device) if config.cyclic_learning: self.network.update_scheduler(step_size) # update the scheduler self.network.train() avg_loss_p = 0 avg_loss_v = 0 tot_batch_count = 0 for epoch in range(config.epochs): # training for state_batch, value_batch, policy_batch in training_generator: # send the data to the gpu state_batch = state_batch.to(config.training_device, dtype=torch.float) value_batch = value_batch.unsqueeze(1).to(config.training_device, dtype=torch.float) policy_batch = policy_batch.to(config.training_device, dtype=torch.float) # execute the training step with one batch if config.cyclic_learning: loss_p, loss_v = self.network.train_cyclical_step(state_batch, policy_batch, value_batch) else: loss_p, loss_v = self.network.train_step(state_batch, policy_batch, value_batch) avg_loss_p += loss_p avg_loss_v += loss_v tot_batch_count += 1 # calculate the mean of the loss avg_loss_p /= tot_batch_count avg_loss_v /= tot_batch_count # activate the evaluation mode self.network = data_storage.net_to_device(self.network, config.evaluation_device) self.network.eval() return avg_loss_p.item(), avg_loss_v.item()
def nn_update(self, generation): """ updates the neural network by picking a random batch form the experience replay :param generation: the network generation (number of iterations so far) :return: average policy and value loss over all mini batches """ # setup the data set training_generator = self.experience_buffer.prepare_data(generation) step_size = training_generator.dataset.__len__() // (2 * config.batch_size) logger.info("training data prepared, step size: {}".format(step_size)) # activate the training mode self.network = data_storage.net_to_device(self.network, config.training_device) if config.cyclic_learning: self.network.update_scheduler(step_size) # update the scheduler self.network.train() avg_loss_p = 0 avg_loss_v = 0 tot_batch_count = 0 for epoch in range(config.epochs): # training for state_batch, value_batch, policy_batch in training_generator: # send the data to the gpu state_batch = state_batch.to(config.training_device, dtype=torch.float) value_batch = value_batch.unsqueeze(1).to(config.training_device, dtype=torch.float) policy_batch = policy_batch.to(config.training_device, dtype=torch.float) # execute the training step with one batch if config.cyclic_learning: loss_p, loss_v = self.network.train_cyclical_step(state_batch, policy_batch, value_batch) else: loss_p, loss_v = self.network.train_step(state_batch, policy_batch, value_batch) avg_loss_p += loss_p avg_loss_v += loss_v tot_batch_count += 1 # calculate the mean of the loss avg_loss_p /= tot_batch_count avg_loss_v /= tot_batch_count # activate the evaluation mode self.network = data_storage.net_to_device(self.network, config.evaluation_device) self.network.eval() return avg_loss_p.item(), avg_loss_v.item()
Python
def fill_with_initial_data(self): """ fills the experience buffer with initial training data from an untrained network this helps to prevents early overfitting of the network :return: """ with open("initial_training_data.pkl", 'rb') as input: initial_data = pickle.load(input) for i in range(config.min_window_size): self.add_new_cycle() start_idx = i*config.episode_count*config.initial_game_length end_idx = (i+1)*config.episode_count*config.initial_game_length data = initial_data[start_idx:end_idx] self.add_data(data)
def fill_with_initial_data(self): """ fills the experience buffer with initial training data from an untrained network this helps to prevents early overfitting of the network :return: """ with open("initial_training_data.pkl", 'rb') as input: initial_data = pickle.load(input) for i in range(config.min_window_size): self.add_new_cycle() start_idx = i*config.episode_count*config.initial_game_length end_idx = (i+1)*config.episode_count*config.initial_game_length data = initial_data[start_idx:end_idx] self.add_data(data)
Python
def add_new_cycle(self): """ adds a new training cycle to the training cycle list :return: """ self.training_cycles.append([])
def add_new_cycle(self): """ adds a new training cycle to the training cycle list :return: """ self.training_cycles.append([])
Python
def add_data(self, training_examples): """ adds the passed training examples to the experience buffer :param training_examples: list containing the training examples :return: """ self.training_cycles[-1] += training_examples
def add_data(self, training_examples): """ adds the passed training examples to the experience buffer :param training_examples: list containing the training examples :return: """ self.training_cycles[-1] += training_examples
Python
def window_size_from_generation(self, generation): """ returns the size of the window that is used for training :param generation: the network generation :return: the size of the training window """ # some initilal data is used if config.use_initial_data: window_size = config.min_window_size + generation // 2 if window_size > config.max_window_size: window_size = config.max_window_size return window_size # no initial data is used window_size = max(config.min_window_size + (generation - config.min_window_size + 1) // 2, config.min_window_size) if window_size > config.max_window_size: window_size = config.max_window_size return window_size
def window_size_from_generation(self, generation): """ returns the size of the window that is used for training :param generation: the network generation :return: the size of the training window """ # some initilal data is used if config.use_initial_data: window_size = config.min_window_size + generation // 2 if window_size > config.max_window_size: window_size = config.max_window_size return window_size # no initial data is used window_size = max(config.min_window_size + (generation - config.min_window_size + 1) // 2, config.min_window_size) if window_size > config.max_window_size: window_size = config.max_window_size return window_size
Python
def prepare_data(self, generation): """ prepares the training data for training :param generation: the generation of the network (number of iterations so far) :return: torch training generator for training """ # calculate the size of the window window_size = self.window_size_from_generation(generation) logger.debug("window_size: {}".format(window_size)) # get rid of old data while len(self.training_cycles) > window_size: self.training_cycles.pop(0) # get the whole training data training_data = [] for sample in self.training_cycles: training_data += sample # average the positions (early positions are overrepresented) if config.average_positions: training_data = self.__average_positions__(training_data) # create the training set training_set = SelfPlayDataSet(training_data) training_generator = data.DataLoader(training_set, **config.data_set_params) return training_generator
def prepare_data(self, generation): """ prepares the training data for training :param generation: the generation of the network (number of iterations so far) :return: torch training generator for training """ # calculate the size of the window window_size = self.window_size_from_generation(generation) logger.debug("window_size: {}".format(window_size)) # get rid of old data while len(self.training_cycles) > window_size: self.training_cycles.pop(0) # get the whole training data training_data = [] for sample in self.training_cycles: training_data += sample # average the positions (early positions are overrepresented) if config.average_positions: training_data = self.__average_positions__(training_data) # create the training set training_set = SelfPlayDataSet(training_data) training_generator = data.DataLoader(training_set, **config.data_set_params) return training_generator
Python
def main_lr(): """ finds the min and the max learning rate. train the network for a few epochs and plot the prediction accuracy vs the learning rate. min learning rate is the rate where the prediction accuracy starts to increase and the max learning rate is the lr where the prediction accuracy slows down or even deteriorates. The batch size and all other hyperparameters should be the same for this test and the actual training. This test can be done with a smaller subset of the data set if the full data set is too large. :return: """ # The logger utils.init_logger(logging.DEBUG, file_name="log/connect4.log") logger = logging.getLogger('find_lr') np.set_printoptions(suppress=True, precision=6) # set the random seed random.seed(a=None, version=2) np.random.seed(seed=None) # parameters config.batch_size = 256 config.weight_decay = 1e-4 config.n_blocks = 10 config.n_filters = 128 epochs = 8 csv_training_set_path = "../data_sets/training_set.csv" csv_test_set_path = "../data_sets/training_set.csv" # load the test set csv_test_set = pd.read_csv(csv_test_set_path, sep=",") # load the training set csv_training_set = pd.read_csv(csv_training_set_path, sep=",") sample_count = supervised.weak_sample_size(csv_training_set) logger.info("the training set contains {} weak training examples".format(sample_count)) # create the training data training_set = supervised.create_training_set(csv_training_set) logger.info("finished parsing the training set, size: {}".format(training_set.__len__())) # define the parameters for the training params = { 'batch_size': config.batch_size, 'shuffle': True, 'num_workers': 2, 'pin_memory': True, 'drop_last': True, } # generators training_generator = data.DataLoader(training_set, **params) # train the neural network learning_rates = [] prediction_errors = [] value_errors = [] for power in np.arange(-6, 0.1, 0.25): config.learning_rate = 10**power prediction_error, value_error = train_net(epochs, training_generator, csv_test_set) learning_rates.append(config.learning_rate) prediction_errors.append(prediction_error) value_errors.append(value_error) # save the results np.save("learning_rates.npy", np.array(learning_rates)) np.save("lr_policy_error.npy", np.array(prediction_errors)) np.save("lr_value_error.npy", np.array(value_errors)) # set the style of the plot plt.style.use('seaborn-dark-palette') # policy prediction error fig1 = plt.figure(1) plt.semilogx(learning_rates, prediction_errors) axes = plt.gca() axes.grid(True, color=(0.9, 0.9, 0.9)) plt.title("Move Prediction Error") plt.xlabel("Learning Rate") plt.ylabel("Prediciton Error") fig1.show() # value prediction error fig2 = plt.figure(2) plt.semilogx(learning_rates, value_errors) axes = plt.gca() axes.grid(True, color=(0.9, 0.9, 0.9)) plt.title("Position Value Error") plt.xlabel("Learning Rate") plt.ylabel("Value Error") fig2.show() plt.show()
def main_lr(): """ finds the min and the max learning rate. train the network for a few epochs and plot the prediction accuracy vs the learning rate. min learning rate is the rate where the prediction accuracy starts to increase and the max learning rate is the lr where the prediction accuracy slows down or even deteriorates. The batch size and all other hyperparameters should be the same for this test and the actual training. This test can be done with a smaller subset of the data set if the full data set is too large. :return: """ # The logger utils.init_logger(logging.DEBUG, file_name="log/connect4.log") logger = logging.getLogger('find_lr') np.set_printoptions(suppress=True, precision=6) # set the random seed random.seed(a=None, version=2) np.random.seed(seed=None) # parameters config.batch_size = 256 config.weight_decay = 1e-4 config.n_blocks = 10 config.n_filters = 128 epochs = 8 csv_training_set_path = "../data_sets/training_set.csv" csv_test_set_path = "../data_sets/training_set.csv" # load the test set csv_test_set = pd.read_csv(csv_test_set_path, sep=",") # load the training set csv_training_set = pd.read_csv(csv_training_set_path, sep=",") sample_count = supervised.weak_sample_size(csv_training_set) logger.info("the training set contains {} weak training examples".format(sample_count)) # create the training data training_set = supervised.create_training_set(csv_training_set) logger.info("finished parsing the training set, size: {}".format(training_set.__len__())) # define the parameters for the training params = { 'batch_size': config.batch_size, 'shuffle': True, 'num_workers': 2, 'pin_memory': True, 'drop_last': True, } # generators training_generator = data.DataLoader(training_set, **params) # train the neural network learning_rates = [] prediction_errors = [] value_errors = [] for power in np.arange(-6, 0.1, 0.25): config.learning_rate = 10**power prediction_error, value_error = train_net(epochs, training_generator, csv_test_set) learning_rates.append(config.learning_rate) prediction_errors.append(prediction_error) value_errors.append(value_error) # save the results np.save("learning_rates.npy", np.array(learning_rates)) np.save("lr_policy_error.npy", np.array(prediction_errors)) np.save("lr_value_error.npy", np.array(value_errors)) # set the style of the plot plt.style.use('seaborn-dark-palette') # policy prediction error fig1 = plt.figure(1) plt.semilogx(learning_rates, prediction_errors) axes = plt.gca() axes.grid(True, color=(0.9, 0.9, 0.9)) plt.title("Move Prediction Error") plt.xlabel("Learning Rate") plt.ylabel("Prediciton Error") fig1.show() # value prediction error fig2 = plt.figure(2) plt.semilogx(learning_rates, value_errors) axes = plt.gca() axes.grid(True, color=(0.9, 0.9, 0.9)) plt.title("Position Value Error") plt.xlabel("Learning Rate") plt.ylabel("Value Error") fig2.show() plt.show()
Python
def train_net(epoch_count, training_generator, csv_test_set): """ trains the neural network a few times and returns the value and prediciton error :param epoch_count: the number of epochs to train the neural network :param training_generator: the torch training generator :param csv_test_set: the test set on which the network is tested :return: prediction error, value error """ logger = logging.getLogger('Sup Learning') # create a new network to train network = networks.ResNet(config.learning_rate, config.n_blocks, config.n_filters, config.weight_decay) network = data_storage.net_to_device(network, config.training_device) # execute the training by looping over all epochs network.train() for epoch in range(epoch_count): # training for state_batch, value_batch, policy_batch in training_generator: # send the data to the gpu state_batch = state_batch.to(config.training_device) value_batch = value_batch.to(config.training_device) policy_batch = policy_batch.to(config.training_device) # execute one training step _, _ = network.train_step(state_batch, policy_batch, value_batch) # evaluation pred_error, val_error = evaluation.net_prediction_error(network, csv_test_set) logger.debug("learning rate {}, prediction error: {}, value-error: {}".format(config.learning_rate, pred_error, val_error)) return pred_error, val_error
def train_net(epoch_count, training_generator, csv_test_set): """ trains the neural network a few times and returns the value and prediciton error :param epoch_count: the number of epochs to train the neural network :param training_generator: the torch training generator :param csv_test_set: the test set on which the network is tested :return: prediction error, value error """ logger = logging.getLogger('Sup Learning') # create a new network to train network = networks.ResNet(config.learning_rate, config.n_blocks, config.n_filters, config.weight_decay) network = data_storage.net_to_device(network, config.training_device) # execute the training by looping over all epochs network.train() for epoch in range(epoch_count): # training for state_batch, value_batch, policy_batch in training_generator: # send the data to the gpu state_batch = state_batch.to(config.training_device) value_batch = value_batch.to(config.training_device) policy_batch = policy_batch.to(config.training_device) # execute one training step _, _ = network.train_step(state_batch, policy_batch, value_batch) # evaluation pred_error, val_error = evaluation.net_prediction_error(network, csv_test_set) logger.debug("learning rate {}, prediction error: {}, value-error: {}".format(config.learning_rate, pred_error, val_error)) return pred_error, val_error
Python
def create_state_dict(): """ fills the state dict with the white score values :return: """ global state_dict if len(state_dict) > 0: return # load the state dict form file if it is already present if os.path.exists(state_dict_path): with open(state_dict_path, 'rb') as input: state_dict = pickle.load(input) logger.debug("loaded the state dict from file") return logger.debug("start to fill the minimax state dict") start_time = time.time() board = tic_tac_toe.TicTacToeBoard() # fill in the first state state = board.state_id() # go through the whole game score = minimax(board, board.player, True) state_dict[state] = score end_time = time.time() elapsed_time = end_time - start_time logger.debug("elapsed time to fill the state dict: {}".format(elapsed_time)) logger.debug("size of the state dict: {}".format(len(state_dict))) # dump the state dict to a file with open(state_dict_path, 'wb') as output: pickle.dump(state_dict, output, pickle.HIGHEST_PROTOCOL)
def create_state_dict(): """ fills the state dict with the white score values :return: """ global state_dict if len(state_dict) > 0: return # load the state dict form file if it is already present if os.path.exists(state_dict_path): with open(state_dict_path, 'rb') as input: state_dict = pickle.load(input) logger.debug("loaded the state dict from file") return logger.debug("start to fill the minimax state dict") start_time = time.time() board = tic_tac_toe.TicTacToeBoard() # fill in the first state state = board.state_id() # go through the whole game score = minimax(board, board.player, True) state_dict[state] = score end_time = time.time() elapsed_time = end_time - start_time logger.debug("elapsed time to fill the state dict: {}".format(elapsed_time)) logger.debug("size of the state dict: {}".format(len(state_dict))) # dump the state dict to a file with open(state_dict_path, 'wb') as output: pickle.dump(state_dict, output, pickle.HIGHEST_PROTOCOL)
Python
def minimax(board, player, fill_state_dict = False): """ optimally solves tic tac toe in every board position. this is an implementation of the minimax algorithm. it fills the state dict with the seen states :param board: the tic tac toe board :param player: the current player :return: the score of the current player 1: win 0: draw -1: loss """ if board.terminal: reward = board.reward() if player == CONST.BLACK: reward = -reward return reward move = -1 score = -2 for a in board.legal_actions(): board_clone = board.clone() current_player = board_clone.player board_clone.execute_action(a) # try the move move_score = -minimax(board_clone, board_clone.player, fill_state_dict) # get the score for the opponent # fill the state dict if fill_state_dict: white_score = move_score if current_player == CONST.WHITE else -move_score state_number = board_clone.state_id() state_dict[state_number] = white_score if move_score > score: score = move_score move = a if move == -1: return 0 return score
def minimax(board, player, fill_state_dict = False): """ optimally solves tic tac toe in every board position. this is an implementation of the minimax algorithm. it fills the state dict with the seen states :param board: the tic tac toe board :param player: the current player :return: the score of the current player 1: win 0: draw -1: loss """ if board.terminal: reward = board.reward() if player == CONST.BLACK: reward = -reward return reward move = -1 score = -2 for a in board.legal_actions(): board_clone = board.clone() current_player = board_clone.player board_clone.execute_action(a) # try the move move_score = -minimax(board_clone, board_clone.player, fill_state_dict) # get the score for the opponent # fill the state dict if fill_state_dict: white_score = move_score if current_player == CONST.WHITE else -move_score state_number = board_clone.state_id() state_dict[state_number] = white_score if move_score > score: score = move_score move = a if move == -1: return 0 return score
Python
def play_minimax_games(net, game_count, mcts_sim_count, network_color): """ returns the error percentage of the optimal move prediction by the network the network and the mcts are used to predict the move to play :param net: the network :param game_count: the number of games to play :param mcts_sim_count: the number of monte carlo simulations :param network_color: the color of the network :return: the score of the network vs the minimax player """ mcts_list = [mcts.MCTS(tic_tac_toe.TicTacToeBoard()) for _ in range(game_count)] player = CONST.WHITE all_terminated = False while not all_terminated: # make a move with the az agent if player == network_color: # run all mcts simulations mcts.run_simulations(mcts_list, mcts_sim_count, net, 0) # paly the best move suggested by the mcts policy for i_mcts_ctx, mcts_ctx in enumerate(mcts_list): # skip terminated games if mcts_ctx.board.is_terminal(): continue policy = mcts_list[i_mcts_ctx].policy_from_state(mcts_ctx.board.state_id(), 0) move = np.where(policy == 1)[0][0] mcts_ctx.board.execute_action(move) # make an optimal minimax move else: for mcts_ctx in mcts_list: # skip terminated games if mcts_ctx.board.is_terminal(): continue move = mcts_ctx.board.minimax_move() mcts_ctx.board.execute_action(move) # swap the player player = CONST.WHITE if player == CONST.BLACK else CONST.BLACK # check if all games are terminated all_terminated = True for mcts_ctx in mcts_list: if not mcts_ctx.board.is_terminal(): all_terminated = False break # extract the score from all boards tot_score = 0 for mcts_ctx in mcts_list: score = mcts_ctx.board.white_score() if network_color == CONST.WHITE else mcts_ctx.board.black_score() tot_score += score tot_score /= game_count return tot_score
def play_minimax_games(net, game_count, mcts_sim_count, network_color): """ returns the error percentage of the optimal move prediction by the network the network and the mcts are used to predict the move to play :param net: the network :param game_count: the number of games to play :param mcts_sim_count: the number of monte carlo simulations :param network_color: the color of the network :return: the score of the network vs the minimax player """ mcts_list = [mcts.MCTS(tic_tac_toe.TicTacToeBoard()) for _ in range(game_count)] player = CONST.WHITE all_terminated = False while not all_terminated: # make a move with the az agent if player == network_color: # run all mcts simulations mcts.run_simulations(mcts_list, mcts_sim_count, net, 0) # paly the best move suggested by the mcts policy for i_mcts_ctx, mcts_ctx in enumerate(mcts_list): # skip terminated games if mcts_ctx.board.is_terminal(): continue policy = mcts_list[i_mcts_ctx].policy_from_state(mcts_ctx.board.state_id(), 0) move = np.where(policy == 1)[0][0] mcts_ctx.board.execute_action(move) # make an optimal minimax move else: for mcts_ctx in mcts_list: # skip terminated games if mcts_ctx.board.is_terminal(): continue move = mcts_ctx.board.minimax_move() mcts_ctx.board.execute_action(move) # swap the player player = CONST.WHITE if player == CONST.BLACK else CONST.BLACK # check if all games are terminated all_terminated = True for mcts_ctx in mcts_list: if not mcts_ctx.board.is_terminal(): all_terminated = False break # extract the score from all boards tot_score = 0 for mcts_ctx in mcts_list: score = mcts_ctx.board.white_score() if network_color == CONST.WHITE else mcts_ctx.board.black_score() tot_score += score tot_score /= game_count return tot_score
Python
def train_step(self, batch, target_p, target_v): """ executes one training step of the neural network :param batch: tensor with data [batchSize, nn_input_size] :param target_p: policy target :param target_v: value target :return: policy loss, value loss """ # send the tensors to the used device data = batch.to(config.training_device) self.optimizer.zero_grad() # reset the gradients to zero in every epoch prediction_p, prediction_v = self(data) # pass the data through the network to get the prediction # create the label criterion_v = nn.MSELoss() # define the loss loss_p = -torch.sum(target_p * torch.log(1e-8 + prediction_p), 1).mean() loss_v = criterion_v(prediction_v, target_v) loss = loss_p + loss_v loss.backward() # back propagation self.optimizer.step() # make one optimization step return loss_p, loss_v
def train_step(self, batch, target_p, target_v): """ executes one training step of the neural network :param batch: tensor with data [batchSize, nn_input_size] :param target_p: policy target :param target_v: value target :return: policy loss, value loss """ # send the tensors to the used device data = batch.to(config.training_device) self.optimizer.zero_grad() # reset the gradients to zero in every epoch prediction_p, prediction_v = self(data) # pass the data through the network to get the prediction # create the label criterion_v = nn.MSELoss() # define the loss loss_p = -torch.sum(target_p * torch.log(1e-8 + prediction_p), 1).mean() loss_v = criterion_v(prediction_v, target_v) loss = loss_p + loss_v loss.backward() # back propagation self.optimizer.step() # make one optimization step return loss_p, loss_v
Python
def update_scheduler(self, step_size): """ initializes a new scheduler, this method is needed when the size of the training data changes :param step_size: step size of the cyclical learning rate :return: """ self.scheduler = torch.optim.lr_scheduler.CyclicLR( self.optimizer, step_size_up=step_size, base_lr=config.min_lr, max_lr=config.max_lr, cycle_momentum=False)
def update_scheduler(self, step_size): """ initializes a new scheduler, this method is needed when the size of the training data changes :param step_size: step size of the cyclical learning rate :return: """ self.scheduler = torch.optim.lr_scheduler.CyclicLR( self.optimizer, step_size_up=step_size, base_lr=config.min_lr, max_lr=config.max_lr, cycle_momentum=False)
Python
def train_cyclical_step(self, batch, target_p, target_v): """ executes one training step of the neural network with a cyclic learning rate :param batch: tensor with data [batchSize, nn_input_size] :param target_p: policy target :param target_v: value target :return: policy loss, value loss """ # send the tensors to the used device data = batch.to(config.training_device) self.optimizer.zero_grad() # reset the gradients to zero in every epoch prediction_p, prediction_v = self(data) # pass the data through the network to get the prediction # create the label target_p = target_p.to(config.training_device) target_v = target_v.to(config.training_device) criterion_v = nn.MSELoss() # define the loss loss_p = - torch.sum(target_p * torch.log(1e-8 + prediction_p), 1).mean() loss_v = criterion_v(prediction_v, target_v) loss = loss_p + loss_v loss.backward() # back propagation # make one optimization step self.optimizer.step() self.scheduler.step() return loss_p, loss_v
def train_cyclical_step(self, batch, target_p, target_v): """ executes one training step of the neural network with a cyclic learning rate :param batch: tensor with data [batchSize, nn_input_size] :param target_p: policy target :param target_v: value target :return: policy loss, value loss """ # send the tensors to the used device data = batch.to(config.training_device) self.optimizer.zero_grad() # reset the gradients to zero in every epoch prediction_p, prediction_v = self(data) # pass the data through the network to get the prediction # create the label target_p = target_p.to(config.training_device) target_v = target_v.to(config.training_device) criterion_v = nn.MSELoss() # define the loss loss_p = - torch.sum(target_p * torch.log(1e-8 + prediction_p), 1).mean() loss_v = criterion_v(prediction_v, target_v) loss = loss_p + loss_v loss.backward() # back propagation # make one optimization step self.optimizer.step() self.scheduler.step() return loss_p, loss_v
Python
def state_id(self): """ uses the cantor pairing function to create one unique id for the state form the two integers representing the board state """ # state = "{}_{}".format(self.position, self.disk_mask) state = self.position + self.disk_mask return state
def state_id(self): """ uses the cantor pairing function to create one unique id for the state form the two integers representing the board state """ # state = "{}_{}".format(self.position, self.disk_mask) state = self.position + self.disk_mask return state
Python
def execute_action(self, column): """ plays the passed move on the board :param column: integer that defines the column in which the disk is played :return: """ column = int(column) # old_mask = self.disk_mask self.position = self.position ^ self.disk_mask # get position of the opponent self.disk_mask = self.disk_mask | (self.disk_mask + (1 << (column * 7))) self.move_count += 1 self.check_win(self.position ^ self.disk_mask) self.player = self.move_count % 2 if self.move_count == 42: self.terminal = True
def execute_action(self, column): """ plays the passed move on the board :param column: integer that defines the column in which the disk is played :return: """ column = int(column) # old_mask = self.disk_mask self.position = self.position ^ self.disk_mask # get position of the opponent self.disk_mask = self.disk_mask | (self.disk_mask + (1 << (column * 7))) self.move_count += 1 self.check_win(self.position ^ self.disk_mask) self.player = self.move_count % 2 if self.move_count == 42: self.terminal = True
Python
def mirror(self): """ returns a position that is mirrored on the y - axis :return: """ mirrored_position = self.clone() mirrored_position.position = self.mirror_board_number(self.position) mirrored_position.disk_mask = self.mirror_board_number(self.disk_mask) return mirrored_position
def mirror(self): """ returns a position that is mirrored on the y - axis :return: """ mirrored_position = self.clone() mirrored_position.position = self.mirror_board_number(self.position) mirrored_position.disk_mask = self.mirror_board_number(self.disk_mask) return mirrored_position
Python
def mirror_board_number(self, number): """ mirrors the passed number representing a board :param number: any number representing some board configuration (position, board mask, disk maksk etc) :return: """ mirrored_number = 0 # left half of the board for col in range((Config.board_width+1) // 2 - 1): mirrored_number += (number & column_mask(col)) << ((Config.board_width - (2 * col + 1)) * (Config.board_height + 1)) # right half of the board for col in range((Config.board_width+1) // 2 - 1): mirrored_number += (number & column_mask(Config.board_width - col - 1)) >> ((Config.board_width - (2 * col + 1)) * (Config.board_height + 1)) # center row if Config.board_width % 2 != 0: col = Config.board_width // 2 mirrored_number += (number & column_mask(col)) return mirrored_number
def mirror_board_number(self, number): """ mirrors the passed number representing a board :param number: any number representing some board configuration (position, board mask, disk maksk etc) :return: """ mirrored_number = 0 # left half of the board for col in range((Config.board_width+1) // 2 - 1): mirrored_number += (number & column_mask(col)) << ((Config.board_width - (2 * col + 1)) * (Config.board_height + 1)) # right half of the board for col in range((Config.board_width+1) // 2 - 1): mirrored_number += (number & column_mask(Config.board_width - col - 1)) >> ((Config.board_width - (2 * col + 1)) * (Config.board_height + 1)) # center row if Config.board_width % 2 != 0: col = Config.board_width // 2 mirrored_number += (number & column_mask(col)) return mirrored_number
Python
def from_board_matrix(self, board): """ creates the bit board from the passed board representation :param board: games represented as one board :return: """ self.disk_mask = 0 self.position = 0 count = 0 self.move_count = 0 for x in range(7): for y in range(5, -1, -1): if board[y, x]: self.disk_mask += 1 << (count + x) self.move_count += 1 if board[y, x] == CONST.WHITE + 1: self.position += 1 << (count + x) count += 1 self.player = self.move_count % 2 if self.player == CONST.BLACK: self.position = self.position ^ self.disk_mask # check the games states self.check_win(self.position)
def from_board_matrix(self, board): """ creates the bit board from the passed board representation :param board: games represented as one board :return: """ self.disk_mask = 0 self.position = 0 count = 0 self.move_count = 0 for x in range(7): for y in range(5, -1, -1): if board[y, x]: self.disk_mask += 1 << (count + x) self.move_count += 1 if board[y, x] == CONST.WHITE + 1: self.position += 1 << (count + x) count += 1 self.player = self.move_count % 2 if self.player == CONST.BLACK: self.position = self.position ^ self.disk_mask # check the games states self.check_win(self.position)
Python
def from_position(self, position, disk_mask): """ creates a position from the integer representations :param position: position of the current player :param disk_mask: all disks that are set :return: """ self.position = position self.disk_mask = disk_mask self.move_count = utils.popcount(disk_mask) self.player = self.move_count % 2 # check the games states self.check_win(self.position)
def from_position(self, position, disk_mask): """ creates a position from the integer representations :param position: position of the current player :param disk_mask: all disks that are set :return: """ self.position = position self.disk_mask = disk_mask self.move_count = utils.popcount(disk_mask) self.player = self.move_count % 2 # check the games states self.check_win(self.position)
Python
def check_win(self, position): """ checks if the current player has won the games :param position: the position that is checked :return: """ if self.four_in_a_row(position): self.terminal = True self.score = 1 if self.player == CONST.WHITE else -1
def check_win(self, position): """ checks if the current player has won the games :param position: the position that is checked :return: """ if self.four_in_a_row(position): self.terminal = True self.score = 1 if self.player == CONST.WHITE else -1
Python
def four_in_a_row(self, position): """ checks if the passed player has a row of four :param position: the position that is checked :return: """ # vertical temp = position & (position >> 1) if temp & (temp >> 2): return True # horizontal temp = position & (position >> 7) if temp & (temp >> 14): return True # diagonal / temp = position & (position >> 8) if temp & (temp >> 16): return True # diagonal \ temp = position & (position >> 6) if temp & (temp >> 12): return True # no row of 4 found return False
def four_in_a_row(self, position): """ checks if the passed player has a row of four :param position: the position that is checked :return: """ # vertical temp = position & (position >> 1) if temp & (temp >> 2): return True # horizontal temp = position & (position >> 7) if temp & (temp >> 14): return True # diagonal / temp = position & (position >> 8) if temp & (temp >> 16): return True # diagonal \ temp = position & (position >> 6) if temp & (temp >> 12): return True # no row of 4 found return False
Python
def column_mask(col): """ bitmask with all cells of the passed column :param col: board column :return: """ return ((1 << Config.board_height) - 1) << col * (Config.board_height + 1)
def column_mask(col): """ bitmask with all cells of the passed column :param col: board column :return: """ return ((1 << Config.board_height) - 1) << col * (Config.board_height + 1)
Python
def net_prediction_error(net, test_set): """ returns the error percentage of the optimal move prediction by the network only the network is used to predict the correct move :param net: the network :param test_set: the test set :return: error percentage, mean squared value error """ tot_positions = test_set.shape[0] # test_set.shape[0] # the total number of positions in the test set correct_predictions = 0 # the correctly predicted positions in the test set tot_predictions = 0 avg_mse_value = 0 # to track the mean squared value error batch_size = 512 batch_list = [] idx_list = [] board_list = [] for j in range(tot_positions): # ignore losing positions if test_set["weak_score"][j] < 0: continue # load the board board = connect4.Connect4Board() board.from_position(test_set["position"][j], test_set["disk_mask"][j]) board_list.append(board) # get the white perspective sample, _ = board.white_perspective() batch_list.append(sample) idx_list.append(j) if len(batch_list) == batch_size or j == tot_positions - 1: batch = torch.Tensor(batch_list).to(torch_device) policy, value = net(batch) for i_batch in range(policy.shape[0]): _, move = policy[i_batch].max(0) move = move.item() # check if the move is part of the optimal moves idx = idx_list[i_batch] if str(move) in str(test_set["weak_moves"][idx]): correct_predictions += 1 tot_predictions += 1 # value error correct_value = test_set["weak_score"][idx] net_value = value[i_batch].item() mse_value = (correct_value - net_value)**2 avg_mse_value += mse_value batch_list = [] idx_list = [] board_list = [] # calculate the prediction error pred_error = (tot_predictions - correct_predictions) / tot_predictions * 100 avg_mse_value /= tot_predictions return pred_error, avg_mse_value
def net_prediction_error(net, test_set): """ returns the error percentage of the optimal move prediction by the network only the network is used to predict the correct move :param net: the network :param test_set: the test set :return: error percentage, mean squared value error """ tot_positions = test_set.shape[0] # test_set.shape[0] # the total number of positions in the test set correct_predictions = 0 # the correctly predicted positions in the test set tot_predictions = 0 avg_mse_value = 0 # to track the mean squared value error batch_size = 512 batch_list = [] idx_list = [] board_list = [] for j in range(tot_positions): # ignore losing positions if test_set["weak_score"][j] < 0: continue # load the board board = connect4.Connect4Board() board.from_position(test_set["position"][j], test_set["disk_mask"][j]) board_list.append(board) # get the white perspective sample, _ = board.white_perspective() batch_list.append(sample) idx_list.append(j) if len(batch_list) == batch_size or j == tot_positions - 1: batch = torch.Tensor(batch_list).to(torch_device) policy, value = net(batch) for i_batch in range(policy.shape[0]): _, move = policy[i_batch].max(0) move = move.item() # check if the move is part of the optimal moves idx = idx_list[i_batch] if str(move) in str(test_set["weak_moves"][idx]): correct_predictions += 1 tot_predictions += 1 # value error correct_value = test_set["weak_score"][idx] net_value = value[i_batch].item() mse_value = (correct_value - net_value)**2 avg_mse_value += mse_value batch_list = [] idx_list = [] board_list = [] # calculate the prediction error pred_error = (tot_predictions - correct_predictions) / tot_predictions * 100 avg_mse_value /= tot_predictions return pred_error, avg_mse_value
Python
def mcts_prediction_error(net, test_set, mcts_sim_count, alpha_dirich, temp): """ returns the error percentage of the optimal move prediction by the network the network and the mcts are used to predict the move to play :param net: the network :param test_set: the test set :param mcts_sim_count: the number of monte carlo simulations :param alpha_dirich: dirichlet noise parameter :param temp: the temperature :return: error percentage """ tot_positions = test_set.shape[0] # test_set.shape[0] # the total number of positions in the test set correct_predictions = 0 # the correctly predicted positions in the test set tot_predictions = 0 batch_size = 512 idx_list = [] mcts_list = [] for j in range(tot_positions): # ignore losing positions if test_set["weak_score"][j] < 0: continue # load the board board = connect4.Connect4Board() board.from_position(test_set["position"][j], test_set["disk_mask"][j]) mcts_list.append(MCTS(board)) # save the index idx_list.append(j) if len(mcts_list) == batch_size or j == tot_positions - 1: # =========================================== execute the mcts simulations for all boards mcts.run_simulations(mcts_list, mcts_sim_count, net, alpha_dirich) # =========================================== get the policy from the mcts for i_mcts_ctx, mcts_ctx in enumerate(mcts_list): policy = mcts_list[i_mcts_ctx].policy_from_state(mcts_ctx.board.state_id(), temp) move = np.argmax(policy) # check if the move is part of the optimal moves idx = idx_list[i_mcts_ctx] if str(move) in str(test_set["weak_moves"][idx]): correct_predictions += 1 tot_predictions += 1 idx_list = [] mcts_list = [] # calculate the prediction error error = (tot_predictions - correct_predictions) / tot_predictions * 100 return error
def mcts_prediction_error(net, test_set, mcts_sim_count, alpha_dirich, temp): """ returns the error percentage of the optimal move prediction by the network the network and the mcts are used to predict the move to play :param net: the network :param test_set: the test set :param mcts_sim_count: the number of monte carlo simulations :param alpha_dirich: dirichlet noise parameter :param temp: the temperature :return: error percentage """ tot_positions = test_set.shape[0] # test_set.shape[0] # the total number of positions in the test set correct_predictions = 0 # the correctly predicted positions in the test set tot_predictions = 0 batch_size = 512 idx_list = [] mcts_list = [] for j in range(tot_positions): # ignore losing positions if test_set["weak_score"][j] < 0: continue # load the board board = connect4.Connect4Board() board.from_position(test_set["position"][j], test_set["disk_mask"][j]) mcts_list.append(MCTS(board)) # save the index idx_list.append(j) if len(mcts_list) == batch_size or j == tot_positions - 1: # =========================================== execute the mcts simulations for all boards mcts.run_simulations(mcts_list, mcts_sim_count, net, alpha_dirich) # =========================================== get the policy from the mcts for i_mcts_ctx, mcts_ctx in enumerate(mcts_list): policy = mcts_list[i_mcts_ctx].policy_from_state(mcts_ctx.board.state_id(), temp) move = np.argmax(policy) # check if the move is part of the optimal moves idx = idx_list[i_mcts_ctx] if str(move) in str(test_set["weak_moves"][idx]): correct_predictions += 1 tot_predictions += 1 idx_list = [] mcts_list = [] # calculate the prediction error error = (tot_predictions - correct_predictions) / tot_predictions * 100 return error
Python
def net_vs_net_prediction(net1, net2, game_count, game_class): """ plays the two passed network against each other, in half of the games net1 is white and in the other half net2 is white. to get the policy only the network prediction is used without any mcts simulations. the move to play is sampled from the policy distribution. playing deterministically makes no sense as the same games would just be repeated over and over again :param net1: network 1 :param net2: network 2 :param game_count: the number of games to play in total, half of the games are played as white and the other half as black :param game_class: the class of the game :return: score of net1, the score is in the range of 0-1 where: 0: loss 0.5: draw 1: win """ half_count = game_count // 2 board_wrapper_list = [] for i in range(2*half_count): if i < half_count: board_wrapper_list.append(BoardWrapper(game_class(), CONST.WHITE)) # net1 is white else: board_wrapper_list.append(BoardWrapper(game_class(), CONST.BLACK)) # net2 is white all_terminated = False while not all_terminated: batch_list1 = [] batch_list2 = [] idx_list1 = [] idx_list2 = [] for idx, board_wrapper in enumerate(board_wrapper_list): # skip finished games if board_wrapper.board.is_terminal(): continue # get the white perspective sample, player = board_wrapper.board.white_perspective() if player == CONST.WHITE: if board_wrapper.white_network_number == 1: batch_list1.append(sample) idx_list1.append(idx) else: batch_list2.append(sample) idx_list2.append(idx) else: if board_wrapper.white_network_number == 1: batch_list2.append(sample) idx_list2.append(idx) else: batch_list1.append(sample) idx_list1.append(idx) # get the policy form the network if len(batch_list1) > 0: batch1 = torch.Tensor(batch_list1).to(torch_device) policy1, _ = net1(batch1) policy1 = policy1.detach().cpu().numpy() else: policy1 = None if len(batch_list2) > 0: batch2 = torch.Tensor(batch_list2).to(torch_device) policy2, _ = net2(batch2) policy2 = policy2.detach().cpu().numpy() else: policy2 = None if policy1 is not None: for i_batch in range(policy1.shape[0]): # set the illegal moves to 0 policy = policy1[i_batch] idx = idx_list1[i_batch] illegal_moves = board_wrapper_list[idx].board.illegal_actions() policy[illegal_moves] = 0 # choose an action according to the probability distribution of all legal actions policy /= np.sum(policy) action = np.random.choice(len(policy), p=policy) # execute the best legal action board_wrapper_list[idx].board.execute_action(action) if policy2 is not None: for i_batch in range(policy2.shape[0]): # set the illegal moves to 0 policy = policy2[i_batch] idx = idx_list2[i_batch] illegal_moves = board_wrapper_list[idx].board.illegal_actions() policy[illegal_moves] = 0 # choose an action according to the probability distribution of all legal actions policy /= np.sum(policy) action = np.random.choice(len(policy), p=policy) # execute the best legal action board_wrapper_list[idx].board.execute_action(action) # check if all boards are terminated all_terminated = True for board_wrapper in board_wrapper_list: if not board_wrapper.board.is_terminal(): all_terminated = False break # calculate the score of network 1 score = 0 for board_wrapper in board_wrapper_list: reward = (board_wrapper.board.reward() + 1) / 2 if board_wrapper.white_network_number == 1: score += reward # net1 is white else: score += (1 - reward) # net1 is black score = score / (2*half_count) return score
def net_vs_net_prediction(net1, net2, game_count, game_class): """ plays the two passed network against each other, in half of the games net1 is white and in the other half net2 is white. to get the policy only the network prediction is used without any mcts simulations. the move to play is sampled from the policy distribution. playing deterministically makes no sense as the same games would just be repeated over and over again :param net1: network 1 :param net2: network 2 :param game_count: the number of games to play in total, half of the games are played as white and the other half as black :param game_class: the class of the game :return: score of net1, the score is in the range of 0-1 where: 0: loss 0.5: draw 1: win """ half_count = game_count // 2 board_wrapper_list = [] for i in range(2*half_count): if i < half_count: board_wrapper_list.append(BoardWrapper(game_class(), CONST.WHITE)) # net1 is white else: board_wrapper_list.append(BoardWrapper(game_class(), CONST.BLACK)) # net2 is white all_terminated = False while not all_terminated: batch_list1 = [] batch_list2 = [] idx_list1 = [] idx_list2 = [] for idx, board_wrapper in enumerate(board_wrapper_list): # skip finished games if board_wrapper.board.is_terminal(): continue # get the white perspective sample, player = board_wrapper.board.white_perspective() if player == CONST.WHITE: if board_wrapper.white_network_number == 1: batch_list1.append(sample) idx_list1.append(idx) else: batch_list2.append(sample) idx_list2.append(idx) else: if board_wrapper.white_network_number == 1: batch_list2.append(sample) idx_list2.append(idx) else: batch_list1.append(sample) idx_list1.append(idx) # get the policy form the network if len(batch_list1) > 0: batch1 = torch.Tensor(batch_list1).to(torch_device) policy1, _ = net1(batch1) policy1 = policy1.detach().cpu().numpy() else: policy1 = None if len(batch_list2) > 0: batch2 = torch.Tensor(batch_list2).to(torch_device) policy2, _ = net2(batch2) policy2 = policy2.detach().cpu().numpy() else: policy2 = None if policy1 is not None: for i_batch in range(policy1.shape[0]): # set the illegal moves to 0 policy = policy1[i_batch] idx = idx_list1[i_batch] illegal_moves = board_wrapper_list[idx].board.illegal_actions() policy[illegal_moves] = 0 # choose an action according to the probability distribution of all legal actions policy /= np.sum(policy) action = np.random.choice(len(policy), p=policy) # execute the best legal action board_wrapper_list[idx].board.execute_action(action) if policy2 is not None: for i_batch in range(policy2.shape[0]): # set the illegal moves to 0 policy = policy2[i_batch] idx = idx_list2[i_batch] illegal_moves = board_wrapper_list[idx].board.illegal_actions() policy[illegal_moves] = 0 # choose an action according to the probability distribution of all legal actions policy /= np.sum(policy) action = np.random.choice(len(policy), p=policy) # execute the best legal action board_wrapper_list[idx].board.execute_action(action) # check if all boards are terminated all_terminated = True for board_wrapper in board_wrapper_list: if not board_wrapper.board.is_terminal(): all_terminated = False break # calculate the score of network 1 score = 0 for board_wrapper in board_wrapper_list: reward = (board_wrapper.board.reward() + 1) / 2 if board_wrapper.white_network_number == 1: score += reward # net1 is white else: score += (1 - reward) # net1 is black score = score / (2*half_count) return score
Python
def mcts_info(self): """ returns the information needed for the next mcts simulations :return: the mcts object 1 or 2 depending on the network to use """ if self.player1_color == 1: if self.board.current_player() == CONST.WHITE: return self.mcts_ctx1, 1 else: return self.mcts_ctx2, 2 else: if self.board.current_player() == CONST.WHITE: return self.mcts_ctx1, 2 else: return self.mcts_ctx2, 1
def mcts_info(self): """ returns the information needed for the next mcts simulations :return: the mcts object 1 or 2 depending on the network to use """ if self.player1_color == 1: if self.board.current_player() == CONST.WHITE: return self.mcts_ctx1, 1 else: return self.mcts_ctx2, 2 else: if self.board.current_player() == CONST.WHITE: return self.mcts_ctx1, 2 else: return self.mcts_ctx2, 1
Python
def net_vs_net_mcts(net1, net2, mcts_sim_count, temp, game_count, game_class): """ plays the two passed network against each other, in half of the games net1 is white and in the other half net2 is white. to get the policy mcts is used. :param net1: network 1 :param net2: network 2 :param game_count: the number of games to play in total, half of the games are played as white and the other half as black :param game_class: the class of the game :return: score of net1, the score is in the range of 0-1 where: 0: loss 0.5: draw 1: win """ half_count = game_count // 2 mcts_ctx_wrapper_list = [] for i in range(2*half_count): if i < half_count: mcts_ctx_wrapper_list.append(MCTSContextWrapper(game_class(), 1)) # net1 is white else: mcts_ctx_wrapper_list.append(MCTSContextWrapper(game_class(), 2)) # net2 is white all_terminated = False while not all_terminated: # prepare the mcts context lists mcts_list1 = [] # mcts list where net1 needs to be used mcts_list2 = [] # mcts list where net2 needs to be used for idx, mcts_ctx_wrapper in enumerate(mcts_ctx_wrapper_list): # skip finished games if mcts_ctx_wrapper.board.is_terminal(): continue mcts_ctx, net_number = mcts_ctx_wrapper.mcts_info() if net_number == 1: mcts_list1.append(mcts_ctx) else: mcts_list2.append(mcts_ctx) # run the mcts simulations mcts.run_simulations(mcts_list1, mcts_sim_count, net1, 0) mcts.run_simulations(mcts_list2, mcts_sim_count, net2, 0) # execute the move of the tree search for i_mcts_ctx, mcts_ctx in enumerate(mcts_list1): # skip terminated games if mcts_ctx.board.is_terminal(): continue # choose the action according to the probability distribution policy = mcts_ctx.policy_from_state(mcts_ctx.board.state_id(), temp) action = np.random.choice(len(policy), p=policy) # execute the action on the board mcts_ctx.board.execute_action(action) for i_mcts_ctx, mcts_ctx in enumerate(mcts_list2): # skip terminated games if mcts_ctx.board.is_terminal(): continue # choose the action according to the probability distribution policy = mcts_ctx.policy_from_state(mcts_ctx.board.state_id(), temp) action = np.random.choice(len(policy), p=policy) # execute the action on the board mcts_ctx.board.execute_action(action) # check if all boards are terminated all_terminated = True for mcts_ctx_wrapper in mcts_ctx_wrapper_list: if not mcts_ctx_wrapper.board.is_terminal(): all_terminated = False break # calculate the score of network 1 score = 0 for mcts_ctx_wrapper in mcts_ctx_wrapper_list: reward = (mcts_ctx_wrapper.board.reward() + 1) / 2 if mcts_ctx_wrapper.player1_color == 1: score += reward # net1 is white else: score += (1-reward) # net1 is white score = score / (2*half_count) return score
def net_vs_net_mcts(net1, net2, mcts_sim_count, temp, game_count, game_class): """ plays the two passed network against each other, in half of the games net1 is white and in the other half net2 is white. to get the policy mcts is used. :param net1: network 1 :param net2: network 2 :param game_count: the number of games to play in total, half of the games are played as white and the other half as black :param game_class: the class of the game :return: score of net1, the score is in the range of 0-1 where: 0: loss 0.5: draw 1: win """ half_count = game_count // 2 mcts_ctx_wrapper_list = [] for i in range(2*half_count): if i < half_count: mcts_ctx_wrapper_list.append(MCTSContextWrapper(game_class(), 1)) # net1 is white else: mcts_ctx_wrapper_list.append(MCTSContextWrapper(game_class(), 2)) # net2 is white all_terminated = False while not all_terminated: # prepare the mcts context lists mcts_list1 = [] # mcts list where net1 needs to be used mcts_list2 = [] # mcts list where net2 needs to be used for idx, mcts_ctx_wrapper in enumerate(mcts_ctx_wrapper_list): # skip finished games if mcts_ctx_wrapper.board.is_terminal(): continue mcts_ctx, net_number = mcts_ctx_wrapper.mcts_info() if net_number == 1: mcts_list1.append(mcts_ctx) else: mcts_list2.append(mcts_ctx) # run the mcts simulations mcts.run_simulations(mcts_list1, mcts_sim_count, net1, 0) mcts.run_simulations(mcts_list2, mcts_sim_count, net2, 0) # execute the move of the tree search for i_mcts_ctx, mcts_ctx in enumerate(mcts_list1): # skip terminated games if mcts_ctx.board.is_terminal(): continue # choose the action according to the probability distribution policy = mcts_ctx.policy_from_state(mcts_ctx.board.state_id(), temp) action = np.random.choice(len(policy), p=policy) # execute the action on the board mcts_ctx.board.execute_action(action) for i_mcts_ctx, mcts_ctx in enumerate(mcts_list2): # skip terminated games if mcts_ctx.board.is_terminal(): continue # choose the action according to the probability distribution policy = mcts_ctx.policy_from_state(mcts_ctx.board.state_id(), temp) action = np.random.choice(len(policy), p=policy) # execute the action on the board mcts_ctx.board.execute_action(action) # check if all boards are terminated all_terminated = True for mcts_ctx_wrapper in mcts_ctx_wrapper_list: if not mcts_ctx_wrapper.board.is_terminal(): all_terminated = False break # calculate the score of network 1 score = 0 for mcts_ctx_wrapper in mcts_ctx_wrapper_list: reward = (mcts_ctx_wrapper.board.reward() + 1) / 2 if mcts_ctx_wrapper.player1_color == 1: score += reward # net1 is white else: score += (1-reward) # net1 is white score = score / (2*half_count) return score
Python
def execute_action(self, move): """ plays the passed move on the board :param move: integer that defines the position to set the stone :return: """ # if move not in self.legal_moves: # print("move not in list") # set the token if self.player == CONST.WHITE: self.white_player = self.white_player + (1 << move) else: self.black_player = self.black_player + (1 << move) # check if the player won self.check_win() # swap the active player and calculate the legal moves self.swap_players() self.__calc_legal_moves__()
def execute_action(self, move): """ plays the passed move on the board :param move: integer that defines the position to set the stone :return: """ # if move not in self.legal_moves: # print("move not in list") # set the token if self.player == CONST.WHITE: self.white_player = self.white_player + (1 << move) else: self.black_player = self.black_player + (1 << move) # check if the player won self.check_win() # swap the active player and calculate the legal moves self.swap_players() self.__calc_legal_moves__()
Python
def illegal_actions(self): """ returns a list of illegal moves :return: """ # define the mask with all disks disk_mask = self.white_player ^ self.black_player illegal_moves = [] for move in range(9): if (1 << move) & disk_mask > 0: illegal_moves.append(move) return illegal_moves
def illegal_actions(self): """ returns a list of illegal moves :return: """ # define the mask with all disks disk_mask = self.white_player ^ self.black_player illegal_moves = [] for move in range(9): if (1 << move) & disk_mask > 0: illegal_moves.append(move) return illegal_moves
Python
def from_board_matrix(self, board): """ creates the bit board from the passed board representation :param board: games represented as one board :return: """ white_board = board == CONST.WHITE white_board = white_board.astype(int) self.white_player = self.board_to_int(white_board) black_board = board == CONST.BLACK black_board = black_board.astype(int) self.black_player = self.board_to_int(black_board) # calculate all legal moves and disks to flip self.__calc_legal_moves__() # check the games states self.swap_players() self.check_win() self.swap_players()
def from_board_matrix(self, board): """ creates the bit board from the passed board representation :param board: games represented as one board :return: """ white_board = board == CONST.WHITE white_board = white_board.astype(int) self.white_player = self.board_to_int(white_board) black_board = board == CONST.BLACK black_board = black_board.astype(int) self.black_player = self.board_to_int(black_board) # calculate all legal moves and disks to flip self.__calc_legal_moves__() # check the games states self.swap_players() self.check_win() self.swap_players()
Python
def int_to_board(self, number): """ creates the 3x3 bitmask that is represented by the passed integer :param number: move on the board :return: x3 matrix representing the board """ number = (number & 7) + ((number & 56) << 5) + ((number & 448) << 10) byte_arr = np.array([number], dtype=np.uint32).view(np.uint8) board_mask = np.unpackbits(byte_arr).reshape(-1, 8)[0:3, ::-1][:, 0:3] return board_mask
def int_to_board(self, number): """ creates the 3x3 bitmask that is represented by the passed integer :param number: move on the board :return: x3 matrix representing the board """ number = (number & 7) + ((number & 56) << 5) + ((number & 448) << 10) byte_arr = np.array([number], dtype=np.uint32).view(np.uint8) board_mask = np.unpackbits(byte_arr).reshape(-1, 8)[0:3, ::-1][:, 0:3] return board_mask
Python
def board_to_int(self, mask): """ converts the passed board mask (3x3) to an integer :param mask: binary board representation 3x3 :return: integer representing the passed board """ bit_arr = np.reshape(mask, -1).astype(np.uint32) number = bit_arr.dot(1 << np.arange(bit_arr.size, dtype=np.uint32)) return int(number)
def board_to_int(self, mask): """ converts the passed board mask (3x3) to an integer :param mask: binary board representation 3x3 :return: integer representing the passed board """ bit_arr = np.reshape(mask, -1).astype(np.uint32) number = bit_arr.dot(1 << np.arange(bit_arr.size, dtype=np.uint32)) return int(number)
Python
def check_win(self): """ checks if the current player has won the games :return: """ if self.three_in_a_row(self.player): self.terminal = True self.score = 1 if self.player == CONST.WHITE else -1
def check_win(self): """ checks if the current player has won the games :return: """ if self.three_in_a_row(self.player): self.terminal = True self.score = 1 if self.player == CONST.WHITE else -1
Python
def three_in_a_row(self, player): """ checks if the passed player has a row of three :param player: the player for which 3 in a row is checked :return: """ board = self.white_player if player == CONST.WHITE else self.black_player # horizontal check if board & 7 == 7 or board & 56 == 56 or board & 448 == 448: return True # vertical check if board & 73 == 73 or board & 146 == 146 or board & 292 == 292: return True # diagonal check / if board & 84 == 84: return True # diagonal check \ if board & 273 == 273: return True # nothing found return False
def three_in_a_row(self, player): """ checks if the passed player has a row of three :param player: the player for which 3 in a row is checked :return: """ board = self.white_player if player == CONST.WHITE else self.black_player # horizontal check if board & 7 == 7 or board & 56 == 56 or board & 448 == 448: return True # vertical check if board & 73 == 73 or board & 146 == 146 or board & 292 == 292: return True # diagonal check / if board & 84 == 84: return True # diagonal check \ if board & 273 == 273: return True # nothing found return False
Python
def minimax_move(self): """ returns the optimal minimax move, if there are more than one optimal moves, a ranodm one is picked :return: """ # get the white score for all legal moves score_list = np.empty(len(self.legal_moves_list)) for idx, move in enumerate(self.legal_moves_list): board_clone = self.clone() board_clone.execute_action(move) state = board_clone.state_id() white_score = minimax.state_dict.get(state) score_list[idx] = white_score # find the indices of the max score for white and the min score for black if self.player == CONST.WHITE: move_indices = np.argwhere(score_list == np.amax(score_list)) else: move_indices = np.argwhere(score_list == np.amin(score_list)) move_indices = move_indices.squeeze(axis=1) best_moves = np.array(self.legal_moves_list)[move_indices] best_move = np.random.choice(best_moves, 1) return int(best_move)
def minimax_move(self): """ returns the optimal minimax move, if there are more than one optimal moves, a ranodm one is picked :return: """ # get the white score for all legal moves score_list = np.empty(len(self.legal_moves_list)) for idx, move in enumerate(self.legal_moves_list): board_clone = self.clone() board_clone.execute_action(move) state = board_clone.state_id() white_score = minimax.state_dict.get(state) score_list[idx] = white_score # find the indices of the max score for white and the min score for black if self.player == CONST.WHITE: move_indices = np.argwhere(score_list == np.amax(score_list)) else: move_indices = np.argwhere(score_list == np.amin(score_list)) move_indices = move_indices.squeeze(axis=1) best_moves = np.array(self.legal_moves_list)[move_indices] best_move = np.random.choice(best_moves, 1) return int(best_move)
Python
def clone(self): """ returns a new board with the same state :return: """ board = copy.deepcopy(self) return board
def clone(self): """ returns a new board with the same state :return: """ board = copy.deepcopy(self) return board
Python
def current_player(self): """ returns the current player, needs to be CONST.WHITE or CONST.BLACK :return: """ pass
def current_player(self): """ returns the current player, needs to be CONST.WHITE or CONST.BLACK :return: """ pass
Python
def symmetry_count(): """ returns the number of symmetries that are created by symmetric_boards(). the symmetry count is always 1 larger than the size of the list returned by symmetric_boards(). if there is no symmetry this count should be 1 :return: """ return 1
def symmetry_count(): """ returns the number of symmetries that are created by symmetric_boards(). the symmetry count is always 1 larger than the size of the list returned by symmetric_boards(). if there is no symmetry this count should be 1 :return: """ return 1
Python
def white_perspective(self): """ returns the board from the white perspective. If it is white's move the normal board representation is returned. if it is black's move the white and the black pieces are swapped. :return: the matrix representation of the board the current player (CONST.WHITE or CONST.BLACK) """ pass
def white_perspective(self): """ returns the board from the white perspective. If it is white's move the normal board representation is returned. if it is black's move the white and the black pieces are swapped. :return: the matrix representation of the board the current player (CONST.WHITE or CONST.BLACK) """ pass
Python
def state_id(self): """ returns a unique state id of the current board :return: """ pass
def state_id(self): """ returns a unique state id of the current board :return: """ pass
Python
def illegal_actions(self): """ returns a list of all illegal actions, this list could be calculated from the legal actions but sometimes there are faster implementations available to find all illegal actions :return: """ pass
def illegal_actions(self): """ returns a list of all illegal actions, this list could be calculated from the legal actions but sometimes there are faster implementations available to find all illegal actions :return: """ pass
Python
def training_reward(self): """ returns the reward for training, this is normally the same method as self.reward() :return: """ pass
def training_reward(self): """ returns the reward for training, this is normally the same method as self.reward() :return: """ pass
Python
def main_az(game_class): """ trains an agent using the AlphaZero algorithm :param game_class: class of the implemented games :return: """ # The logger utils.init_logger(logging.DEBUG, file_name="log/app.log") logger = logging.getLogger('main_training') # set the random seed random.seed(a=None, version=2) np.random.seed(seed=None) # create the training data directory Path(config.save_dir).mkdir(parents=True, exist_ok=True) # create the storage object training_data = data_storage.load_data() # create the agent network = networks.ResNet() agent = alpha_zero_learning.Agent(network) if training_data.cycle == 0: logger.debug("create a new agent") training_data.save_data(agent.network) # save the generation 0 network if config.use_initial_data: logger.debug("fill the experience buffer with some initial data") agent.experience_buffer.fill_with_initial_data() # add training examples of untrained network else: # load the current network logger.debug("load an old network") agent.network = training_data.load_current_net() agent.experience_buffer = training_data.experience_buffer start_training = time.time() for i in range(training_data.cycle, config.cycles, 1): ###### self play and update: create some games data through self play logger.info("start playing games in cycle {}".format(i)) avg_moves_played = agent.play_self_play_games(game_class, training_data.network_path) training_data.avg_moves_played.append(avg_moves_played) logger.debug("average moves played: {}".format(avg_moves_played)) ###### training, train the training network and use the target network for predictions logger.info("start updates in cycle {}".format(i)) loss_p, loss_v = agent.nn_update(i) training_data.policy_loss.append(loss_p) training_data.value_loss.append(loss_v) logger.debug("policy loss: {}".format(loss_p)) logger.debug("value loss: {}".format(loss_v)) ###### save the new network logger.info("save check point to file in cycle {}".format(i)) training_data.cycle += 1 training_data.experience_buffer = agent.experience_buffer training_data.save_data(agent.network) end_training = time.time() training_time = end_training - start_training logger.info("elapsed time whole training process {}".format(training_time)) # save the results np.save("games/checkers/results/value_loss.npy", np.array(training_data.value_loss)) np.save("games/checkers/results/policy_loss.npy", np.array(training_data.policy_loss)) np.save("games/checkers/results/avg_moves.npy", np.array(training_data.avg_moves_played)) # set the style of the plot plt.style.use('seaborn-dark-palette') # plot the value training loss fig1 = plt.figure(1) plt.plot(training_data.value_loss) axes = plt.gca() axes.grid(True, color=(0.9, 0.9, 0.9)) plt.title("Average Value Training Loss") plt.xlabel("Generation") plt.ylabel("Value Loss") fig1.show() # plot the training policy loss fig2 = plt.figure(2) plt.plot(training_data.policy_loss) axes = plt.gca() axes.grid(True, color=(0.9, 0.9, 0.9)) plt.title("Average Policy Training Loss") plt.xlabel("Generation") plt.ylabel("Policy Loss") fig2.show() # plot the average number of moves played in the self-play games fig3 = plt.figure(3) plt.plot(training_data.avg_moves_played) axes = plt.gca() axes.grid(True, color=(0.9, 0.9, 0.9)) plt.title("Average Moves in Self-Play Games") plt.xlabel("Generation") plt.ylabel("Move Count") fig3.show() plt.show()
def main_az(game_class): """ trains an agent using the AlphaZero algorithm :param game_class: class of the implemented games :return: """ # The logger utils.init_logger(logging.DEBUG, file_name="log/app.log") logger = logging.getLogger('main_training') # set the random seed random.seed(a=None, version=2) np.random.seed(seed=None) # create the training data directory Path(config.save_dir).mkdir(parents=True, exist_ok=True) # create the storage object training_data = data_storage.load_data() # create the agent network = networks.ResNet() agent = alpha_zero_learning.Agent(network) if training_data.cycle == 0: logger.debug("create a new agent") training_data.save_data(agent.network) # save the generation 0 network if config.use_initial_data: logger.debug("fill the experience buffer with some initial data") agent.experience_buffer.fill_with_initial_data() # add training examples of untrained network else: # load the current network logger.debug("load an old network") agent.network = training_data.load_current_net() agent.experience_buffer = training_data.experience_buffer start_training = time.time() for i in range(training_data.cycle, config.cycles, 1): ###### self play and update: create some games data through self play logger.info("start playing games in cycle {}".format(i)) avg_moves_played = agent.play_self_play_games(game_class, training_data.network_path) training_data.avg_moves_played.append(avg_moves_played) logger.debug("average moves played: {}".format(avg_moves_played)) ###### training, train the training network and use the target network for predictions logger.info("start updates in cycle {}".format(i)) loss_p, loss_v = agent.nn_update(i) training_data.policy_loss.append(loss_p) training_data.value_loss.append(loss_v) logger.debug("policy loss: {}".format(loss_p)) logger.debug("value loss: {}".format(loss_v)) ###### save the new network logger.info("save check point to file in cycle {}".format(i)) training_data.cycle += 1 training_data.experience_buffer = agent.experience_buffer training_data.save_data(agent.network) end_training = time.time() training_time = end_training - start_training logger.info("elapsed time whole training process {}".format(training_time)) # save the results np.save("games/checkers/results/value_loss.npy", np.array(training_data.value_loss)) np.save("games/checkers/results/policy_loss.npy", np.array(training_data.policy_loss)) np.save("games/checkers/results/avg_moves.npy", np.array(training_data.avg_moves_played)) # set the style of the plot plt.style.use('seaborn-dark-palette') # plot the value training loss fig1 = plt.figure(1) plt.plot(training_data.value_loss) axes = plt.gca() axes.grid(True, color=(0.9, 0.9, 0.9)) plt.title("Average Value Training Loss") plt.xlabel("Generation") plt.ylabel("Value Loss") fig1.show() # plot the training policy loss fig2 = plt.figure(2) plt.plot(training_data.policy_loss) axes = plt.gca() axes.grid(True, color=(0.9, 0.9, 0.9)) plt.title("Average Policy Training Loss") plt.xlabel("Generation") plt.ylabel("Policy Loss") fig2.show() # plot the average number of moves played in the self-play games fig3 = plt.figure(3) plt.plot(training_data.avg_moves_played) axes = plt.gca() axes.grid(True, color=(0.9, 0.9, 0.9)) plt.title("Average Moves in Self-Play Games") plt.xlabel("Generation") plt.ylabel("Move Count") fig3.show() plt.show()
Python
def load_data(): """ loads the training data from the state file :return: """ # create a new storage object if not os.path.exists(storage_path): logger.info("create a new data storage object") if not os.path.exists(network_dir): os.makedirs(network_dir) shutil.rmtree(network_dir) os.makedirs(network_dir) return TrainingData() # load an old storage object with the current training data with open(storage_path, 'rb') as input: training_data = pickle.load(input) return training_data
def load_data(): """ loads the training data from the state file :return: """ # create a new storage object if not os.path.exists(storage_path): logger.info("create a new data storage object") if not os.path.exists(network_dir): os.makedirs(network_dir) shutil.rmtree(network_dir) os.makedirs(network_dir) return TrainingData() # load an old storage object with the current training data with open(storage_path, 'rb') as input: training_data = pickle.load(input) return training_data
Python
def net_to_device(net, device): """ sends the network to the passed device :param net: the network to transfer into the cpu :param device: the device to which the network is sent :return: """ net_path = "{}/temp_net.pt".format(temp_dir) # ensure that the temp dir exists and is empty and if os.path.exists(temp_dir): shutil.rmtree(temp_dir) os.makedirs(temp_dir) # put the model on the gpu if device.type == "cuda": torch.save(net, net_path) cuda_net = torch.load(net_path, map_location='cuda') shutil.rmtree(temp_dir) return cuda_net # put the model on the cpu if device.type == "cpu": torch.save(net, net_path) cpu_net = torch.load(net_path, map_location='cpu') shutil.rmtree(temp_dir) return cpu_net logger.error("device type {} is not known".format(device.type)) return None
def net_to_device(net, device): """ sends the network to the passed device :param net: the network to transfer into the cpu :param device: the device to which the network is sent :return: """ net_path = "{}/temp_net.pt".format(temp_dir) # ensure that the temp dir exists and is empty and if os.path.exists(temp_dir): shutil.rmtree(temp_dir) os.makedirs(temp_dir) # put the model on the gpu if device.type == "cuda": torch.save(net, net_path) cuda_net = torch.load(net_path, map_location='cuda') shutil.rmtree(temp_dir) return cuda_net # put the model on the cpu if device.type == "cpu": torch.save(net, net_path) cpu_net = torch.load(net_path, map_location='cpu') shutil.rmtree(temp_dir) return cpu_net logger.error("device type {} is not known".format(device.type)) return None
Python
def load_net(net_path, device): """ loads the network to the passed device :param net_path: the path of the network to load :param device: the device to which the network is loaded :return: """ # put the model on the gpu if device.type == "cuda": gpu_net = torch.load(net_path, map_location='cuda') return gpu_net # put the model on the cpu if device.type == "cpu": cpu_net = torch.load(net_path, map_location='cpu') return cpu_net
def load_net(net_path, device): """ loads the network to the passed device :param net_path: the path of the network to load :param device: the device to which the network is loaded :return: """ # put the model on the gpu if device.type == "cuda": gpu_net = torch.load(net_path, map_location='cuda') return gpu_net # put the model on the cpu if device.type == "cpu": cpu_net = torch.load(net_path, map_location='cpu') return cpu_net
Python
def weak_sample_size(data_set): """ returns the number of weak samples in the passed data set :param data_set: csv data set :return: """ sample_count = 0 for i in range(data_set.shape[0]): if data_set["weak_score"][i] >= 0: sample_count += 1 return sample_count
def weak_sample_size(data_set): """ returns the number of weak samples in the passed data set :param data_set: csv data set :return: """ sample_count = 0 for i in range(data_set.shape[0]): if data_set["weak_score"][i] >= 0: sample_count += 1 return sample_count
Python
def create_training_set(data_set): """ creates the pytorch data set from the passed csv data set :param data_set: csv data set :return: """ # parse the data set states = [] values = [] policies = [] for i in range(data_set.shape[0]): if data_set["weak_score"][i] >= 0: # state board = connect4.BitBoard() position = data_set["position"][i] disk_mask = data_set["disk_mask"][i] board.from_position(position, disk_mask) state, _ = board.white_perspective() states.append(state) # values value = data_set["weak_score"][i] values.append(value) # policy policy = Config.action_count * [0] move_str = data_set["weak_moves"][i] moves = move_str.split('-') probability = 1 / len(moves) for move in moves: policy[int(move)] = probability policies.append(policy) return Dataset(states, values, policies)
def create_training_set(data_set): """ creates the pytorch data set from the passed csv data set :param data_set: csv data set :return: """ # parse the data set states = [] values = [] policies = [] for i in range(data_set.shape[0]): if data_set["weak_score"][i] >= 0: # state board = connect4.BitBoard() position = data_set["position"][i] disk_mask = data_set["disk_mask"][i] board.from_position(position, disk_mask) state, _ = board.white_perspective() states.append(state) # values value = data_set["weak_score"][i] values.append(value) # policy policy = Config.action_count * [0] move_str = data_set["weak_moves"][i] moves = move_str.split('-') probability = 1 / len(moves) for move in moves: policy[int(move)] = probability policies.append(policy) return Dataset(states, values, policies)
Python
def exec_simulation(self, board, alpha_dirich=0): """ executes one Monte-Carlo Tree search simulation. the simulation always starts a the rootk node and ends when a leaf node is reached. this is a games state from which no simulation (playout) was started so far. if the leaf node is a terminal state, the reward is returned. if the leaf node is not a terminal node the value and the policy are estimated with the neural network. the value is the result of the simulation. if a node is reached with known value and policy the move (action) with the highest upper confidence bound is chosen. the upper confidence bound increases with larger probability and if the moves was not chose often in previous simulation. the upper confidence bound holds the balance between exploreation and exploitation. :param board: represents the games :param alpha_dirich: alpha parameter for the dirichlet noise that is added to the root node probabilities :return: the board if it needs to be analyzed by the network or None if the simulation completed """ self.states.clear() self.players.clear() self.actions.clear() while True: s = board.state_id() self.states.append(s) player = board.current_player() self.players.append(player) # check if we are on a leaf node (state form which no simulation was played so far) if s not in self.P: # return the board for the network evaluation return board # add dirichlet noise to the root node legal_actions = board.legal_actions() p_s = self.P[s] if alpha_dirich > 0: p_s = np.copy(p_s) alpha_params = alpha_dirich * np.ones(len(legal_actions)) dirichlet_noise = np.random.dirichlet(alpha_params) p_s[legal_actions] = 0.75 * p_s[legal_actions] + 0.25 * dirichlet_noise # normalize the probabilities again p_s /= np.sum(p_s) # set the dirichlet noise to 0 in order to only add it to the root node alpha_dirich = 0 # choose the action with the highest upper confidence bound max_ucb = -float("inf") action = -1 for a in legal_actions: if (s, a) in self.Q: u = self.Q[(s, a)] + config.c_puct * p_s[a] * math.sqrt(self.N_s[s]) / (1 + self.N_sa[(s, a)]) else: u = config.c_puct * p_s[a] * math.sqrt(self.N_s[s] + 1e-8) # avoid division by 0 if u > max_ucb: max_ucb = u action = a self.N_s[s] += 1 self.actions.append(action) board = board.clone() board.execute_action(action) # check if the games is terminal if board.is_terminal(): v = board.training_reward() self.finish_simulation(board, v) return None
def exec_simulation(self, board, alpha_dirich=0): """ executes one Monte-Carlo Tree search simulation. the simulation always starts a the rootk node and ends when a leaf node is reached. this is a games state from which no simulation (playout) was started so far. if the leaf node is a terminal state, the reward is returned. if the leaf node is not a terminal node the value and the policy are estimated with the neural network. the value is the result of the simulation. if a node is reached with known value and policy the move (action) with the highest upper confidence bound is chosen. the upper confidence bound increases with larger probability and if the moves was not chose often in previous simulation. the upper confidence bound holds the balance between exploreation and exploitation. :param board: represents the games :param alpha_dirich: alpha parameter for the dirichlet noise that is added to the root node probabilities :return: the board if it needs to be analyzed by the network or None if the simulation completed """ self.states.clear() self.players.clear() self.actions.clear() while True: s = board.state_id() self.states.append(s) player = board.current_player() self.players.append(player) # check if we are on a leaf node (state form which no simulation was played so far) if s not in self.P: # return the board for the network evaluation return board # add dirichlet noise to the root node legal_actions = board.legal_actions() p_s = self.P[s] if alpha_dirich > 0: p_s = np.copy(p_s) alpha_params = alpha_dirich * np.ones(len(legal_actions)) dirichlet_noise = np.random.dirichlet(alpha_params) p_s[legal_actions] = 0.75 * p_s[legal_actions] + 0.25 * dirichlet_noise # normalize the probabilities again p_s /= np.sum(p_s) # set the dirichlet noise to 0 in order to only add it to the root node alpha_dirich = 0 # choose the action with the highest upper confidence bound max_ucb = -float("inf") action = -1 for a in legal_actions: if (s, a) in self.Q: u = self.Q[(s, a)] + config.c_puct * p_s[a] * math.sqrt(self.N_s[s]) / (1 + self.N_sa[(s, a)]) else: u = config.c_puct * p_s[a] * math.sqrt(self.N_s[s] + 1e-8) # avoid division by 0 if u > max_ucb: max_ucb = u action = a self.N_s[s] += 1 self.actions.append(action) board = board.clone() board.execute_action(action) # check if the games is terminal if board.is_terminal(): v = board.training_reward() self.finish_simulation(board, v) return None
Python
def finish_simulation(self, board, value_white, policy=None): """ ends one monte-carlo simulation with the terminal games value of the network evaluation :param board: the board :param value_white: the simulated value from the white perspective :param policy: the policy if the simulation requires network inference :return: """ if policy is not None: s = board.state_id() self.P[s] = policy # ensure that the summed probability of all valid moves is 1 self.P[s][board.illegal_actions()] = 0 total_prob = np.sum(self.P[s]) if total_prob > 0: self.P[s] /= total_prob # normalize the probabilities else: # the network did not choose any legal move, make all moves equally probable print("warning: network probabilities for all legal moves are 0, choose a equal distribution") legal_moves = board.legal_actions() self.P[s][legal_moves] = 1 / len(legal_moves) self.N_s[s] = 0 # back up the tree by updating the Q and the N values for i in range(len(self.actions)): # flip the value for the black player since the games is always viewed from the white perspective v_true = value_white if self.players[i] == CONST.WHITE else -value_white s = self.states[i] a = self.actions[i] if (s, a) in self.Q: self.Q[(s, a)] = (self.N_sa[(s, a)] * self.Q[(s, a)] + v_true) / (self.N_sa[(s, a)] + 1) self.N_sa[(s, a)] += 1 else: self.Q[(s, a)] = v_true self.N_sa[(s, a)] = 1
def finish_simulation(self, board, value_white, policy=None): """ ends one monte-carlo simulation with the terminal games value of the network evaluation :param board: the board :param value_white: the simulated value from the white perspective :param policy: the policy if the simulation requires network inference :return: """ if policy is not None: s = board.state_id() self.P[s] = policy # ensure that the summed probability of all valid moves is 1 self.P[s][board.illegal_actions()] = 0 total_prob = np.sum(self.P[s]) if total_prob > 0: self.P[s] /= total_prob # normalize the probabilities else: # the network did not choose any legal move, make all moves equally probable print("warning: network probabilities for all legal moves are 0, choose a equal distribution") legal_moves = board.legal_actions() self.P[s][legal_moves] = 1 / len(legal_moves) self.N_s[s] = 0 # back up the tree by updating the Q and the N values for i in range(len(self.actions)): # flip the value for the black player since the games is always viewed from the white perspective v_true = value_white if self.players[i] == CONST.WHITE else -value_white s = self.states[i] a = self.actions[i] if (s, a) in self.Q: self.Q[(s, a)] = (self.N_sa[(s, a)] * self.Q[(s, a)] + v_true) / (self.N_sa[(s, a)] + 1) self.N_sa[(s, a)] += 1 else: self.Q[(s, a)] = v_true self.N_sa[(s, a)] = 1
Python
def policy_from_state(self, s, temp): """ returns the policy of the passed state id. it only makes sense to call this methods if a few monte carlo simulations were executed previously. :param s: state id of the board :param temp: the temperature :return: vector containing the policy value for the moves """ counts = [self.N_sa[(s, a)] if (s, a) in self.N_sa else 0 for a in range(config.tot_actions)] # in order to learn something set the probabilities of the best action to 1 and all other action to 0 if temp == 0: action = np.argmax(counts) probs = [0] * config.tot_actions probs[action] = 1 return np.array(probs) else: counts = [c ** (1. / temp) for c in counts] probs = [c / float(sum(counts)) for c in counts] return np.array(probs)
def policy_from_state(self, s, temp): """ returns the policy of the passed state id. it only makes sense to call this methods if a few monte carlo simulations were executed previously. :param s: state id of the board :param temp: the temperature :return: vector containing the policy value for the moves """ counts = [self.N_sa[(s, a)] if (s, a) in self.N_sa else 0 for a in range(config.tot_actions)] # in order to learn something set the probabilities of the best action to 1 and all other action to 0 if temp == 0: action = np.argmax(counts) probs = [0] * config.tot_actions probs[action] = 1 return np.array(probs) else: counts = [c ** (1. / temp) for c in counts] probs = [c / float(sum(counts)) for c in counts] return np.array(probs)
Python
def next_mcts_policy(self, board, mcts_sim_count, net, temp, alpha_dirich): """ uses the search tree that was already built to find the mcts policy :param board: the board of which the policy should be calculated :param mcts_sim_count: the number of mcts simulations :param net: the network :param temp: the temperature :param alpha_dirich: the dirichlet parameter alpha :return: """ self.board = board mcts_list = [self] run_simulations(mcts_list, mcts_sim_count, net, alpha_dirich) policy = mcts_list[0].policy_from_state(mcts_list[0].board.state_id(), temp) return policy
def next_mcts_policy(self, board, mcts_sim_count, net, temp, alpha_dirich): """ uses the search tree that was already built to find the mcts policy :param board: the board of which the policy should be calculated :param mcts_sim_count: the number of mcts simulations :param net: the network :param temp: the temperature :param alpha_dirich: the dirichlet parameter alpha :return: """ self.board = board mcts_list = [self] run_simulations(mcts_list, mcts_sim_count, net, alpha_dirich) policy = mcts_list[0].policy_from_state(mcts_list[0].board.state_id(), temp) return policy
Python
def run_simulations(mcts_list, mcts_sim_count, net, alpha_dirich): """ runs a bunch of mcts simulations in parallel :param mcts_list: list containing all the mcts objects :param mcts_sim_count: the number of mcts simulations to perform :param net: the network that is used for evaluation :param alpha_dirich: the dirichlet parameter alpha :return: """ batch_list = [] leaf_board_list = len(mcts_list) * [None] for sim in range(mcts_sim_count): batch_list.clear() for i_mcts_ctx, mcts_ctx in enumerate(mcts_list): # skip finished games if mcts_ctx.board.is_terminal(): leaf_board_list[i_mcts_ctx] = None continue # execute one simulation leaf_board = mcts_list[i_mcts_ctx].exec_simulation(mcts_ctx.board, alpha_dirich) leaf_board_list[i_mcts_ctx] = leaf_board if leaf_board is not None: batch, _ = leaf_board.white_perspective() batch_list.append(batch) # pass all samples through the network if len(batch_list) > 0: batch_bundle = torch.Tensor(batch_list).to(config.evaluation_device) policy, value = net(batch_bundle) policy = policy.detach().cpu().numpy() # finish the simulation of the states that need a result from the network i_sample = 0 for i_mcts_ctx in range(len(mcts_list)): leaf_board = leaf_board_list[i_mcts_ctx] if leaf_board is not None: # get the value from the white perspective value_white = value[i_sample].item() if leaf_board.current_player() == CONST.WHITE else -value[i_sample].item() # finish the simulation with the simulation with the network evaluation mcts_list[i_mcts_ctx].finish_simulation(leaf_board, value_white, policy[i_sample]) i_sample += 1
def run_simulations(mcts_list, mcts_sim_count, net, alpha_dirich): """ runs a bunch of mcts simulations in parallel :param mcts_list: list containing all the mcts objects :param mcts_sim_count: the number of mcts simulations to perform :param net: the network that is used for evaluation :param alpha_dirich: the dirichlet parameter alpha :return: """ batch_list = [] leaf_board_list = len(mcts_list) * [None] for sim in range(mcts_sim_count): batch_list.clear() for i_mcts_ctx, mcts_ctx in enumerate(mcts_list): # skip finished games if mcts_ctx.board.is_terminal(): leaf_board_list[i_mcts_ctx] = None continue # execute one simulation leaf_board = mcts_list[i_mcts_ctx].exec_simulation(mcts_ctx.board, alpha_dirich) leaf_board_list[i_mcts_ctx] = leaf_board if leaf_board is not None: batch, _ = leaf_board.white_perspective() batch_list.append(batch) # pass all samples through the network if len(batch_list) > 0: batch_bundle = torch.Tensor(batch_list).to(config.evaluation_device) policy, value = net(batch_bundle) policy = policy.detach().cpu().numpy() # finish the simulation of the states that need a result from the network i_sample = 0 for i_mcts_ctx in range(len(mcts_list)): leaf_board = leaf_board_list[i_mcts_ctx] if leaf_board is not None: # get the value from the white perspective value_white = value[i_sample].item() if leaf_board.current_player() == CONST.WHITE else -value[i_sample].item() # finish the simulation with the simulation with the network evaluation mcts_list[i_mcts_ctx].finish_simulation(leaf_board, value_white, policy[i_sample]) i_sample += 1
Python
def mcts_policy(board, mcts_sim_count, net, temp, alpha_dirich): """ calculates the mcts policy with a fresh tree search for one board state :param board: the board of which the policy should be calculated :param mcts_sim_count: the number of mcts simulations :param net: the network :param temp: the temperature :param alpha_dirich: the dirichlet parameter alpha :return: policy vector for all next moves """ mcts_list = [MCTS(board)] run_simulations(mcts_list, mcts_sim_count, net, alpha_dirich) policy = mcts_list[0].policy_from_state(mcts_list[0].board.state_id(), temp) return policy
def mcts_policy(board, mcts_sim_count, net, temp, alpha_dirich): """ calculates the mcts policy with a fresh tree search for one board state :param board: the board of which the policy should be calculated :param mcts_sim_count: the number of mcts simulations :param net: the network :param temp: the temperature :param alpha_dirich: the dirichlet parameter alpha :return: policy vector for all next moves """ mcts_list = [MCTS(board)] run_simulations(mcts_list, mcts_sim_count, net, alpha_dirich) policy = mcts_list[0].policy_from_state(mcts_list[0].board.state_id(), temp) return policy
Python
def _construct_profiling_options(self): """ Construct profiling options to determine which profiling data should be collected. """ profile_memory = "off" if self._profile_memory: profile_memory = "on" fp_point = os.environ.get("PROFILING_FP_START", "") bp_point = os.environ.get("PROFILING_BP_END", "") profiling_options = { "output": self._output_path, "fp_point": fp_point, "bp_point": bp_point, "training_trace": "on", "task_trace": "on", "aic_metrics": "ArithmeticUtilization", "aicpu": "on", "profile_memory": profile_memory } return profiling_options
def _construct_profiling_options(self): """ Construct profiling options to determine which profiling data should be collected. """ profile_memory = "off" if self._profile_memory: profile_memory = "on" fp_point = os.environ.get("PROFILING_FP_START", "") bp_point = os.environ.get("PROFILING_BP_END", "") profiling_options = { "output": self._output_path, "fp_point": fp_point, "bp_point": bp_point, "training_trace": "on", "task_trace": "on", "aic_metrics": "ArithmeticUtilization", "aicpu": "on", "profile_memory": profile_memory } return profiling_options
Python
def _parse_parameter_for_ascend(self, **kwargs): """Parse parameter in Proflier when the device target is Ascend.""" optypes_not_deal = kwargs.pop("optypes_not_deal", "Variable") if not isinstance(optypes_not_deal, str): raise TypeError("The parameter optypes_not_deal must be str.") self._filt_optype_names = optypes_not_deal.split(",") if optypes_not_deal else [] job_dir = kwargs.pop("ascend_job_id", "") if job_dir: job_dir = validate_and_normalize_path(job_dir) if not os.path.exists(job_dir): msg = f"Invalid ascend_job_id: {job_dir}, Please pass the absolute path of the JOB dir" logger.critical(msg) raise ValueError(msg) self._output_path, _ = os.path.split(job_dir) self.start_profile = kwargs.pop("start_profile", True) if not isinstance(self.start_profile, bool): raise TypeError("The parameter start_profile must be bool.") self._profile_communication = kwargs.pop("profile_communication", False) if not isinstance(self._profile_communication, bool): raise TypeError("The parameter profile_communication must be bool.") if self._profile_communication: hccl_option = {"output": self._output_path, "task_trace": "on"} os.environ['PROFILING_OPTIONS'] = json.dumps(hccl_option) self._profile_memory = kwargs.pop("profile_memory", False) if not isinstance(self._profile_memory, bool): raise TypeError("The parameter profile_memory must be bool") if kwargs: logger.warning("There are invalid params which don't work.") task_sink = os.getenv("GRAPH_OP_RUN") if task_sink and task_sink == "1": logger.warning("Profiling is not supported when task is not sink.")
def _parse_parameter_for_ascend(self, **kwargs): """Parse parameter in Proflier when the device target is Ascend.""" optypes_not_deal = kwargs.pop("optypes_not_deal", "Variable") if not isinstance(optypes_not_deal, str): raise TypeError("The parameter optypes_not_deal must be str.") self._filt_optype_names = optypes_not_deal.split(",") if optypes_not_deal else [] job_dir = kwargs.pop("ascend_job_id", "") if job_dir: job_dir = validate_and_normalize_path(job_dir) if not os.path.exists(job_dir): msg = f"Invalid ascend_job_id: {job_dir}, Please pass the absolute path of the JOB dir" logger.critical(msg) raise ValueError(msg) self._output_path, _ = os.path.split(job_dir) self.start_profile = kwargs.pop("start_profile", True) if not isinstance(self.start_profile, bool): raise TypeError("The parameter start_profile must be bool.") self._profile_communication = kwargs.pop("profile_communication", False) if not isinstance(self._profile_communication, bool): raise TypeError("The parameter profile_communication must be bool.") if self._profile_communication: hccl_option = {"output": self._output_path, "task_trace": "on"} os.environ['PROFILING_OPTIONS'] = json.dumps(hccl_option) self._profile_memory = kwargs.pop("profile_memory", False) if not isinstance(self._profile_memory, bool): raise TypeError("The parameter profile_memory must be bool") if kwargs: logger.warning("There are invalid params which don't work.") task_sink = os.getenv("GRAPH_OP_RUN") if task_sink and task_sink == "1": logger.warning("Profiling is not supported when task is not sink.")
Python
def analyse(self): """ Collect and analyse performance data, called after training or during training. The example shows above. """ if Profiler._has_analysed: msg = "Do not analyze twice in the profiler." raise RuntimeError(msg) Profiler._has_analysed = True _environment_check() self._cpu_profiler.stop() self._md_profiler.stop() self._md_profiler.save(self._output_path) if self._device_target and self._device_target == "GPU": self._gpu_analyse() elif self._device_target and self._device_target == "Ascend": self._ascend_analyse() logger.info("Profiling: all the data have been analyzed.")
def analyse(self): """ Collect and analyse performance data, called after training or during training. The example shows above. """ if Profiler._has_analysed: msg = "Do not analyze twice in the profiler." raise RuntimeError(msg) Profiler._has_analysed = True _environment_check() self._cpu_profiler.stop() self._md_profiler.stop() self._md_profiler.save(self._output_path) if self._device_target and self._device_target == "GPU": self._gpu_analyse() elif self._device_target and self._device_target == "Ascend": self._ascend_analyse() logger.info("Profiling: all the data have been analyzed.")
Python
def _ascend_analyse(self): """Collect and analyse ascend performance data""" self._rank_size = 1 if self._profile_communication and not GlobalComm.INITED: self._profile_communication = False if GlobalComm.INITED: self._rank_size = get_group_size() release() if (not self.start_profile) or self._has_started: self._ascend_profiler.stop() else: msg = "The profiler has not start, so can not stop." logger.info(msg) self._ascend_profiler.finalize() job_id = self._get_profiling_job_id() logger.info("Profiling: job id is %s ", job_id) source_path = os.path.join(self._output_path, job_id) # parse hwts.log.data.45.dev file, and get task profiling data hwts_output_filename = self._hwts_output_filename_target + self._rank_id + ".txt" hwts_output_filename = os.path.join(self._output_path, hwts_output_filename) source_path = validate_and_normalize_path(source_path) hwts_output_filename = validate_and_normalize_path(hwts_output_filename) hwtslog_parser = HWTSLogParser(source_path, hwts_output_filename) logger.info("Profiling: analyzing hwts data.") hwtslog_parser.execute() # parse Framework file, and get the relation of op and tasks framework_parser = FrameworkParser(job_id, self._dev_id, self._rank_id, self._output_path) logger.info("Profiling: analyzing framework data.") framework_parser.parse() op_task_dict = framework_parser.to_task_id_full_op_name_dict() if not op_task_dict: logger.error("Profiling: fail to parse framework files.") return # get op compute time from hwts data and framework data, write output_op_compute_time.txt opcompute_output_filename = self._opcompute_output_filename_target + self._rank_id + ".txt" opcompute_output_filename = os.path.join(self._output_path, opcompute_output_filename) opcompute_output_filename = validate_and_normalize_path(opcompute_output_filename) optime_parser = OPComputeTimeParser( hwts_output_filename, opcompute_output_filename, op_task_dict, self._output_path, self._rank_id ) logger.info("Profiling: analyzing the operation compute time.") optime_parser.execute() # parse DATA_PREPROCESS.dev.AICPU file, write output_data_preprocess_aicpu_x.txt output_data_preprocess_aicpu = self._aicpu_op_output_filename_target + self._rank_id + ".txt" output_data_preprocess_aicpu = os.path.join(self._output_path, output_data_preprocess_aicpu) output_data_preprocess_aicpu = validate_and_normalize_path(output_data_preprocess_aicpu) aicpu_data_parser = DataPreProcessParser(source_path, output_data_preprocess_aicpu) logger.info("Profiling: analyzing the data preprocess data.") aicpu_data_parser.execute() # Parsing minddata AICPU profiling logger.info("Profiling: analyzing the minddata AICPU data.") MinddataParser.execute(source_path, self._output_path, self._rank_id) # parse minddata pipeline operator and queue try: pipeline_parser = MinddataPipelineParser(self._output_path, self._rank_id, self._output_path) logger.info("Profiling: analyzing the minddata pipeline operator and queue.") pipeline_parser.parse() except ProfilerException as err: logger.warning(err.message) # Analyze minddata information try: md_analyzer = MinddataProfilingAnalyzer(self._output_path, self._rank_id, self._output_path) logger.info("Profiling: analyzing the minddata information.") md_analyzer.analyze() except ProfilerException as err: logger.warning(err.message) # analyse op compute time info try: logger.info("Profiling: analyzing the operation compute time.") self._analyser_op_info() except ProfilerException as err: logger.warning(err.message) # analyse step trace info points = None is_training_mode_flag = False try: logger.info("Profiling: analyzing the step trace data.") points, is_training_mode_flag = self._analyse_step_trace(source_path, framework_parser) except ProfilerException as err: logger.warning(err.message) # analyse timeline info try: logger.info("Profiling: analyzing the timeline data.") self._analyse_timeline(aicpu_data_parser, optime_parser, source_path) except (ProfilerIOException, ProfilerFileNotFoundException, RuntimeError) as err: logger.warning('Fail to write timeline data: %s', err) # analyse memory usage info if self._profile_memory: try: logger.info("Profiling: analyzing the memory usage info.") self._analyse_memory_usage(points) except (ProfilerIOException, ProfilerFileNotFoundException, ProfilerRawFileException) as err: logger.warning(err.message) # analyse hccl profiler info if self._profile_communication: try: logger.info("Profiling: analyzing the hccl profiler info.") self._analyse_hccl_info() except (ProfilerIOException, ProfilerFileNotFoundException, ProfilerRawFileException) as err: logger.warning(err.message) # get op FLOPs from aicore.data.x.slice.0 file, and compute FLOPS, write output_op_flops_x.txt flops_parser = FlopsParser(source_path, self._output_path, op_task_dict, self._dev_id, self._rank_id, is_training_mode_flag) logger.info("Profiling: analyzing the operation FLOPs.") flops_parser.execute()
def _ascend_analyse(self): """Collect and analyse ascend performance data""" self._rank_size = 1 if self._profile_communication and not GlobalComm.INITED: self._profile_communication = False if GlobalComm.INITED: self._rank_size = get_group_size() release() if (not self.start_profile) or self._has_started: self._ascend_profiler.stop() else: msg = "The profiler has not start, so can not stop." logger.info(msg) self._ascend_profiler.finalize() job_id = self._get_profiling_job_id() logger.info("Profiling: job id is %s ", job_id) source_path = os.path.join(self._output_path, job_id) # parse hwts.log.data.45.dev file, and get task profiling data hwts_output_filename = self._hwts_output_filename_target + self._rank_id + ".txt" hwts_output_filename = os.path.join(self._output_path, hwts_output_filename) source_path = validate_and_normalize_path(source_path) hwts_output_filename = validate_and_normalize_path(hwts_output_filename) hwtslog_parser = HWTSLogParser(source_path, hwts_output_filename) logger.info("Profiling: analyzing hwts data.") hwtslog_parser.execute() # parse Framework file, and get the relation of op and tasks framework_parser = FrameworkParser(job_id, self._dev_id, self._rank_id, self._output_path) logger.info("Profiling: analyzing framework data.") framework_parser.parse() op_task_dict = framework_parser.to_task_id_full_op_name_dict() if not op_task_dict: logger.error("Profiling: fail to parse framework files.") return # get op compute time from hwts data and framework data, write output_op_compute_time.txt opcompute_output_filename = self._opcompute_output_filename_target + self._rank_id + ".txt" opcompute_output_filename = os.path.join(self._output_path, opcompute_output_filename) opcompute_output_filename = validate_and_normalize_path(opcompute_output_filename) optime_parser = OPComputeTimeParser( hwts_output_filename, opcompute_output_filename, op_task_dict, self._output_path, self._rank_id ) logger.info("Profiling: analyzing the operation compute time.") optime_parser.execute() # parse DATA_PREPROCESS.dev.AICPU file, write output_data_preprocess_aicpu_x.txt output_data_preprocess_aicpu = self._aicpu_op_output_filename_target + self._rank_id + ".txt" output_data_preprocess_aicpu = os.path.join(self._output_path, output_data_preprocess_aicpu) output_data_preprocess_aicpu = validate_and_normalize_path(output_data_preprocess_aicpu) aicpu_data_parser = DataPreProcessParser(source_path, output_data_preprocess_aicpu) logger.info("Profiling: analyzing the data preprocess data.") aicpu_data_parser.execute() # Parsing minddata AICPU profiling logger.info("Profiling: analyzing the minddata AICPU data.") MinddataParser.execute(source_path, self._output_path, self._rank_id) # parse minddata pipeline operator and queue try: pipeline_parser = MinddataPipelineParser(self._output_path, self._rank_id, self._output_path) logger.info("Profiling: analyzing the minddata pipeline operator and queue.") pipeline_parser.parse() except ProfilerException as err: logger.warning(err.message) # Analyze minddata information try: md_analyzer = MinddataProfilingAnalyzer(self._output_path, self._rank_id, self._output_path) logger.info("Profiling: analyzing the minddata information.") md_analyzer.analyze() except ProfilerException as err: logger.warning(err.message) # analyse op compute time info try: logger.info("Profiling: analyzing the operation compute time.") self._analyser_op_info() except ProfilerException as err: logger.warning(err.message) # analyse step trace info points = None is_training_mode_flag = False try: logger.info("Profiling: analyzing the step trace data.") points, is_training_mode_flag = self._analyse_step_trace(source_path, framework_parser) except ProfilerException as err: logger.warning(err.message) # analyse timeline info try: logger.info("Profiling: analyzing the timeline data.") self._analyse_timeline(aicpu_data_parser, optime_parser, source_path) except (ProfilerIOException, ProfilerFileNotFoundException, RuntimeError) as err: logger.warning('Fail to write timeline data: %s', err) # analyse memory usage info if self._profile_memory: try: logger.info("Profiling: analyzing the memory usage info.") self._analyse_memory_usage(points) except (ProfilerIOException, ProfilerFileNotFoundException, ProfilerRawFileException) as err: logger.warning(err.message) # analyse hccl profiler info if self._profile_communication: try: logger.info("Profiling: analyzing the hccl profiler info.") self._analyse_hccl_info() except (ProfilerIOException, ProfilerFileNotFoundException, ProfilerRawFileException) as err: logger.warning(err.message) # get op FLOPs from aicore.data.x.slice.0 file, and compute FLOPS, write output_op_flops_x.txt flops_parser = FlopsParser(source_path, self._output_path, op_task_dict, self._dev_id, self._rank_id, is_training_mode_flag) logger.info("Profiling: analyzing the operation FLOPs.") flops_parser.execute()
Python
def start(self): """Used for Ascend, start profiling.""" if not self._has_started: self._has_started = True else: msg = "The profiler has already started." logger.error(msg) raise RuntimeError(msg) self._ascend_profiler.start() self._start_time = int(time.time() * 10000000) logger.info("Profiling: start time: %d", self._start_time)
def start(self): """Used for Ascend, start profiling.""" if not self._has_started: self._has_started = True else: msg = "The profiler has already started." logger.error(msg) raise RuntimeError(msg) self._ascend_profiler.start() self._start_time = int(time.time() * 10000000) logger.info("Profiling: start time: %d", self._start_time)