text
stringlengths
81
112k
Factorizes the item_users matrix. After calling this method, the members 'user_factors' and 'item_factors' will be initialized with a latent factor model of the input data. The item_users matrix does double duty here. It defines which items are liked by which users (P_iu in the origina...
specialized training on the gpu. copies inputs to/from cuda device def _fit_gpu(self, Ciu_host, Cui_host, show_progress=True): """ specialized training on the gpu. copies inputs to/from cuda device """ if not implicit.cuda.HAS_CUDA: raise ValueError("No CUDA extension has been built, can't ...
Provides explanations for why the item is liked by the user. Parameters --------- userid : int The userid to explain recommendations for user_items : csr_matrix Sparse matrix containing the liked items for the user itemid : int The itemid to e...
This function transforms a factor matrix such that an angular nearest neighbours search will return top related items of the inner product. This involves transforming each row by adding one extra dimension as suggested in the paper: "Speeding Up the Xbox Recommender System Using a Euclidean Transformation ...
Converts a scipy sparse matrix to a spark dataframe def convert_sparse_to_dataframe(spark, context, sparse_matrix): """ Converts a scipy sparse matrix to a spark dataframe """ m = sparse_matrix.tocoo() data = context.parallelize(numpy.array([m.row, m.col, m.data]).T, numSlice...
Generates a hdf5 datasetfile from the raw datafiles: You will need to download the train_triplets from here: https://labrosa.ee.columbia.edu/millionsong/tasteprofile#getting And the 'Summary File of the whole dataset' from here https://labrosa.ee.columbia.edu/millionsong/pages/getting-dataset ...
Reads the original dataset TSV as a pandas dataframe def _read_triplets_dataframe(filename): """ Reads the original dataset TSV as a pandas dataframe """ # delay importing this to avoid another dependency import pandas # read in triples of user/artist/playcount from the input dataset # get a model...
Gets the trackinfo array by joining taste profile to the track summary file def _join_summary_file(data, summary_filename="msd_summary_file.h5"): """ Gets the trackinfo array by joining taste profile to the track summary file """ msd = h5py.File(summary_filename) # create a lookup table of trackid -> posi...
Weights a Sparse Matrix by TF-IDF Weighted def tfidf_weight(X): """ Weights a Sparse Matrix by TF-IDF Weighted """ X = coo_matrix(X) # calculate IDF N = float(X.shape[0]) idf = log(N) - log1p(bincount(X.col)) # apply TF-IDF adjustment X.data = sqrt(X.data) * idf[X.col] return X
equivalent to scipy.preprocessing.normalize on sparse matrices , but lets avoid another depedency just for a small utility function def normalize(X): """ equivalent to scipy.preprocessing.normalize on sparse matrices , but lets avoid another depedency just for a small utility function """ X = coo_matri...
Weighs each row of a sparse matrix X by BM25 weighting def bm25_weight(X, K1=100, B=0.8): """ Weighs each row of a sparse matrix X by BM25 weighting """ # calculate idf per term (user) X = coo_matrix(X) N = float(X.shape[0]) idf = log(N) - log1p(bincount(X.col)) # calculate length_norm per ...
Computes and stores the similarity matrix def fit(self, weighted, show_progress=True): """ Computes and stores the similarity matrix """ self.similarity = all_pairs_knn(weighted, self.K, show_progress=show_progress, num_thr...
returns the best N recommendations for a user given its id def recommend(self, userid, user_items, N=10, filter_already_liked_items=True, filter_items=None, recalculate_user=False): """ returns the best N recommendations for a user given its id""" if userid >= user_items.shape[0]: ...
Rank given items for a user and returns sorted item list def rank_items(self, userid, user_items, selected_items, recalculate_user=False): """ Rank given items for a user and returns sorted item list """ # check if selected_items contains itemids that are not in the model(user_items) if max(sel...
Returns a list of the most similar other items def similar_items(self, itemid, N=10): """ Returns a list of the most similar other items """ if itemid >= self.similarity.shape[0]: return [] return sorted(list(nonzeros(self.similarity, itemid)), key=lambda x: -x[1])[:N]
Returns the reddit dataset, downloading locally if necessary. This dataset was released here: https://www.reddit.com/r/redditdev/comments/dtg4j/want_to_help_reddit_build_a_recommender_a_public/ and contains 23M up/down votes from 44K users on 3.4M links. Returns a CSR matrix of (item, user, rating de...
Reads the original dataset TSV as a pandas dataframe def _read_dataframe(filename): """ Reads the original dataset TSV as a pandas dataframe """ # delay importing this to avoid another dependency import pandas # read in triples of user/artist/playcount from the input dataset # get a model based of...
Gets movielens datasets Parameters --------- variant : string Which version of the movielens dataset to download. Should be one of '20m', '10m', '1m' or '100k'. Returns ------- movies : ndarray An array of the movie titles. ratings : csr_matrix A sparse matr...
Generates a hdf5 movielens datasetfile from the raw datafiles found at: https://grouplens.org/datasets/movielens/20m/ You shouldn't have to run this yourself, and can instead just download the output using the 'get_movielens' funciton./ def generate_dataset(path, variant='20m', outputpath="."): """ Ge...
reads in the movielens 20M def _read_dataframes_20M(path): """ reads in the movielens 20M""" import pandas ratings = pandas.read_csv(os.path.join(path, "ratings.csv")) movies = pandas.read_csv(os.path.join(path, "movies.csv")) return ratings, movies
reads in the movielens 100k dataset def _read_dataframes_100k(path): """ reads in the movielens 100k dataset""" import pandas ratings = pandas.read_table(os.path.join(path, "u.data"), names=['userId', 'movieId', 'rating', 'timestamp']) movies = pandas.read_csv(os.path....
Recommends items for a user Calculates the N best recommendations for a user, and returns a list of itemids, score. Parameters ---------- userid : int The userid to calculate recommendations for user_items : csr_matrix A sparse matrix of shape (number_us...
Find a file in a search path def find_in_path(name, path): "Find a file in a search path" # adapted fom http://code.activestate.com/recipes/52224-find-a-file-given-a-search-path/ for dir in path.split(os.pathsep): binpath = os.path.join(dir, name) if os.path.exists(binpath): ret...
Locate the CUDA environment on the system If a valid cuda installation is found this returns a dict with keys 'home', 'nvcc', 'include', and 'lib64' and values giving the absolute path to each directory. Starts by looking for the CUDAHOME env variable. If not found, everything is based on finding 'nvc...
generates a list of similar artists in lastfm by utiliizing the 'similar_items' api of the models def calculate_similar_artists(output_filename, model_name="als"): """ generates a list of similar artists in lastfm by utiliizing the 'similar_items' api of the models """ artists, users, plays = get_lastf...
Generates artist recommendations for each user in the dataset def calculate_recommendations(output_filename, model_name="als"): """ Generates artist recommendations for each user in the dataset """ # train the model based off input params artists, users, plays = get_lastfm() # create a model from the ...
Returns either an ion object or composition object given a formula. Args: formula: String formula. Eg. of ion: NaOH(aq), Na[+]; Eg. of solid: Fe2O3(s), Fe(s), Na2O Returns: Composition/Ion object def ion_or_solid_comp_object(formula): """ Returns either an ion object o...
Generates a label for the pourbaix plotter Args: entry (PourbaixEntry or MultiEntry): entry to get a label for def generate_entry_label(entry): """ Generates a label for the pourbaix plotter Args: entry (PourbaixEntry or MultiEntry): entry to get a label for """ if isinstance(...
Get free energy for a given pH and V Args: pH (float): pH at which to evaluate free energy V (float): voltage at which to evaluate free energy Returns: free energy at conditions def energy_at_conditions(self, pH, V): """ Get free energy for a given ...
Energy at an electrochemical condition, compatible with numpy arrays for pH/V input Args: pH (float): pH at condition V (float): applied potential at condition Returns: energy normalized by number of non-O/H atoms at condition def normalized_energy_at_condi...
Returns dict which contains Pourbaix Entry data. Note that the pH, voltage, H2O factors are always calculated when constructing a PourbaixEntry object. def as_dict(self): """ Returns dict which contains Pourbaix Entry data. Note that the pH, voltage, H2O factors are always calcu...
Invokes def from_dict(cls, d): """ Invokes """ entry_type = d["entry_type"] if entry_type == "Ion": entry = IonEntry.from_dict(d["entry"]) else: entry = PDEntry.from_dict(d["entry"]) entry_id = d["entry_id"] concentration = d["conc...
Sum of number of atoms minus the number of H and O in composition def normalization_factor(self): """ Sum of number of atoms minus the number of H and O in composition """ return 1.0 / (self.num_atoms - self.composition.get('H', 0) - self.composition.get('O', 0))
Returns an IonEntry object from a dict. def from_dict(cls, d): """ Returns an IonEntry object from a dict. """ return IonEntry(Ion.from_dict(d["ion"]), d["energy"], d.get("name", None))
Creates a dict of composition, energy, and ion name def as_dict(self): """ Creates a dict of composition, energy, and ion name """ d = {"ion": self.ion.as_dict(), "energy": self.energy, "name": self.name} return d
Create entries for multi-element Pourbaix construction. This works by finding all possible linear combinations of entries that can result in the specified composition from the initialized comp_dict. Args: entries ([PourbaixEntries]): list of pourbaix entries ...
Static method for finding a multientry based on a list of entries and a product composition. Essentially checks to see if a valid aqueous reaction exists between the entries and the product composition and returns a MultiEntry with weights according to the coefficients if so. ...
Returns a set of pourbaix stable domains (i. e. polygons) in pH-V space from a list of pourbaix_entries This function works by using scipy's HalfspaceIntersection function to construct all of the 2-D polygons that form the boundaries of the planes corresponding to individual entry ...
Finds stable entry at a pH,V condition Args: pH (float): pH to find stable entry V (float): V to find stable entry Returns: def find_stable_entry(self, pH, V): """ Finds stable entry at a pH,V condition Args: pH (float): pH to find stable ent...
Finds decomposition to most stable entry Args: entry (PourbaixEntry): PourbaixEntry corresponding to compound to find the decomposition for pH (float): pH at which to find the decomposition V (float): voltage at which to find the decomposition Return...
Shows the pourbaix plot Args: *args: args to get_pourbaix_plot **kwargs: kwargs to get_pourbaix_plot Returns: None def show(self, *args, **kwargs): """ Shows the pourbaix plot Args: *args: args to get_pourbaix_plot *...
Plot Pourbaix diagram. Args: limits: 2D list containing limits of the Pourbaix diagram of the form [[xlo, xhi], [ylo, yhi]] title (str): Title to display on plot label_domains (bool): whether to label pourbaix domains plt (pyplot): Pyplot instance...
Json-serializable dict representation. def as_dict(self): """ Json-serializable dict representation. """ d = MSONable.as_dict(self) d["translation_vector"] = self.translation_vector.tolist() return d
This method uses the matrix form of ewaldsum to calculate the ewald sums of the potential structures. This is on the order of 4 orders of magnitude faster when there are large numbers of permutations to consider. There are further optimizations possible (doing a smarter search of permuta...
Apply the transformation. Args: structure: input structure return_ranked_list (bool): Whether or not multiple structures are returned. If return_ranked_list is a number, that number of structures is returned. Returns: Depending on ret...
apply the transformation Args: structure (Structure): structure to add site properties to def apply_transformation(self, structure): """ apply the transformation Args: structure (Structure): structure to add site properties to """ ...
Writes input files for a LAMMPS run. Input script is constructed from a str template with placeholders to be filled by custom settings. Data file is either written from a LammpsData instance or copied from an existing file if read_data cmd is inspected in the input script. Other supporting files are not...
Writes all input files (input script, and data if needed). Other supporting files are not handled at this moment. Args: output_dir (str): Directory to output the input files. **kwargs: kwargs supported by LammpsData.write_file. def write_inputs(self, output_dir, **kwargs): ...
Example for a simple MD run based on template md.txt. Args: data (LammpsData or str): Data file as a LammpsData instance or path to an existing data file. force_field (str): Combined force field related cmds. For example, 'pair_style eam\npair_coeff * * C...
Args: a1, a2, a3: lattice vectors in bohr encut: energy cut off in eV Returns: reciprocal lattice vectors with energy less than encut def genrecip(a1, a2, a3, encut): """ Args: a1, a2, a3: lattice vectors in bohr encut: energy cut off in eV Returns: recip...
Generate reciprocal vector magnitudes within the cutoff along the specied lattice vectors. Args: a1: Lattice vector a (in Bohrs) a2: Lattice vector b (in Bohrs) a3: Lattice vector c (in Bohrs) encut: Reciprocal vector energy cutoff Returns: [[g1^2], [g2^2], ...] Squa...
Returns closest site to the input position for both bulk and defect structures Args: struct_blk: Bulk structure struct_def: Defect structure pos: Position Return: (site object, dist, index) def closestsites(struct_blk, struct_def, pos): """ Returns closest site to the input ...
simple newton iteration based convergence function def converge(f, step, tol, max_h): """ simple newton iteration based convergence function """ g = f(0) dx = 10000 h = step while (dx > tol): g2 = f(h) dx = abs(g - g2) g = g2 h += step if h > max_h: ...
Reciprocal space model charge value for input squared reciprocal vector. Args: g2: Square of reciprocal vector Returns: Charge density at the reciprocal vector magnitude def rho_rec(self, g2): """ Reciprocal space model charge value for input squ...
Reciprocal space model charge value close to reciprocal vector 0 . rho_rec(g->0) -> 1 + rho_rec_limit0 * g^2 def rho_rec_limit0(self): """ Reciprocal space model charge value close to reciprocal vector 0 . rho_rec(g->0) -> 1 + rho_rec_limit0 * g^2 """ ret...
Generate a sequence of supercells in which each supercell contains a single interstitial, except for the first supercell in the sequence which is a copy of the defect-free input structure. Args: scaling_matrix (3x3 integer array): scaling matrix to transform ...
Cluster nodes that are too close together using a tol. Args: tol (float): A distance tolerance. PBC is taken into account. def cluster_nodes(self, tol=0.2): """ Cluster nodes that are too close together using a tol. Args: tol (float): A distance tolerance. PBC ...
Remove vnodes that are too close to existing atoms in the structure Args: min_dist(float): The minimum distance that a vertex needs to be from existing atoms. def remove_collisions(self, min_dist=0.5): """ Remove vnodes that are too close to existing atoms in the st...
Get the modified structure with the voronoi nodes inserted. The species is set as a DummySpecie X. def get_structure_with_nodes(self): """ Get the modified structure with the voronoi nodes inserted. The species is set as a DummySpecie X. """ new_s = Structure.from_sites(...
Return a complete table of fractional coordinates - charge density. def _get_charge_distribution_df(self): """ Return a complete table of fractional coordinates - charge density. """ # Fraction coordinates and corresponding indices axis_grid = np.array([np.array(self.chgcar.get_...
Update _extrema_df, extrema_type and extrema_coords def _update_extrema(self, f_coords, extrema_type, threshold_frac=None, threshold_abs=None): """Update _extrema_df, extrema_type and extrema_coords""" if threshold_frac is not None: if threshold_abs is not None: ...
Get all local extrema fractional coordinates in charge density, searching for local minimum by default. Note that sites are NOT grouped symmetrically. Args: find_min (bool): True to find local minimum else maximum, otherwise find local maximum. threshold...
Cluster nodes that are too close together using a tol. Args: tol (float): A distance tolerance. PBC is taken into account. def cluster_nodes(self, tol=0.2): """ Cluster nodes that are too close together using a tol. Args: tol (float): A distance tolerance. PBC ...
Remove predicted sites that are too close to existing atoms in the structure. Args: min_dist (float): The minimum distance (in Angstrom) that a predicted site needs to be from existing atoms. A min_dist with value <= 0 returns all sites without distance check...
Get the modified structure with the possible interstitial sites added. The species is set as a DummySpecie X. Args: find_min (bool): True to find local minimum else maximum, otherwise find local maximum. min_dist (float): The minimum distance (in Angstrom) that ...
Get the average charge density around each local minima in the charge density and store the result in _extrema_df Args: r (float): radius of sphere around each site to evaluate the average def sort_sites_by_integrated_chg(self, r=0.4): """ Get the average charge density arou...
Parses a QChem output file with multiple calculations 1.) Seperates the output into sub-files e.g. qcout -> qcout.0, qcout.1, qcout.2 ... qcout.N a.) Find delimeter for multiple calcualtions b.) Make seperate output sub-files 2.) Creates seperate Q...
Parses charge and multiplicity. def _read_charge_and_multiplicity(self): """ Parses charge and multiplicity. """ temp_charge = read_pattern( self.text, { "key": r"\$molecule\s+([\-\d]+)\s+\d" }, terminate_on_match=True).get('key') ...
Parses species and initial geometry. def _read_species_and_inital_geometry(self): """ Parses species and initial geometry. """ header_pattern = r"Standard Nuclear Orientation \(Angstroms\)\s+I\s+Atom\s+X\s+Y\s+Z\s+-+" table_pattern = r"\s*\d+\s+([a-zA-Z]+)\s*([\d\-\.]+)\s*([\d\-...
Parses both old and new SCFs. def _read_SCF(self): """ Parses both old and new SCFs. """ if self.data.get('using_GEN_SCFMAN', []): if "SCF_failed_to_converge" in self.data.get("errors"): footer_pattern = r"^\s*gen_scfman_exception: SCF failed to converge" ...
Parses Mulliken charges. Also parses spins given an unrestricted SCF. def _read_mulliken(self): """ Parses Mulliken charges. Also parses spins given an unrestricted SCF. """ if self.data.get('unrestricted', []): header_pattern = r"\-+\s+Ground-State Mulliken Net Atomic Charg...
Parses optimized XYZ coordinates. If not present, parses optimized Z-matrix. def _read_optimized_geometry(self): """ Parses optimized XYZ coordinates. If not present, parses optimized Z-matrix. """ header_pattern = r"\*+\s+OPTIMIZATION\s+CONVERGED\s+\*+\s+\*+\s+Coordinates \(Angstroms\)...
Parses the last geometry from an optimization trajectory for use in a new input file. def _read_last_geometry(self): """ Parses the last geometry from an optimization trajectory for use in a new input file. """ header_pattern = r"\s+Optimization\sCycle:\s+" + \ str(len(self....
Parses frequencies, enthalpy, entropy, and mode vectors. def _read_frequency_data(self): """ Parses frequencies, enthalpy, entropy, and mode vectors. """ temp_dict = read_pattern( self.text, { "frequencies": r"\s*Frequency:\s+([\d\-\.]+)(?:\s+...
Parses final free energy information from single-point calculations. def _read_single_point_data(self): """ Parses final free energy information from single-point calculations. """ temp_dict = read_pattern( self.text, { "final_energy": r"\...
Parses information from PCM solvent calculations. def _read_pcm_information(self): """ Parses information from PCM solvent calculations. """ temp_dict = read_pattern( self.text, { "g_electrostatic": r"\s*G_electrostatic\s+=\s+([\d\-\.]+)\s+hartree\s+=\s+([\d...
Parses three potential optimization errors: failing to converge within the allowed number of optimization cycles, failure to determine the lamda needed to continue, and inconsistent size of MO files due to a linear dependence in the AO basis. def _check_optimization_errors(self): """ Pa...
Parses four potential errors that can cause jobs to crash: inability to transform coordinates due to a bad symmetric specification, an input file that fails to pass inspection, and errors reading and writing files. def _check_completion_errors(self): """ Parses four potential errors tha...
Queries the COD for all cod ids associated with a formula. Requires mysql executable to be in the path. Args: formula (str): Formula. Returns: List of cod ids. def get_cod_ids(self, formula): """ Queries the COD for all cod ids associated with a formula...
Queries the COD for a structure by id. Args: cod_id (int): COD id. kwargs: All kwargs supported by :func:`pymatgen.core.structure.Structure.from_str`. Returns: A Structure. def get_structure_by_id(self, cod_id, **kwargs): """ Queries...
Queries the COD for structures by formula. Requires mysql executable to be in the path. Args: cod_id (int): COD id. kwargs: All kwargs supported by :func:`pymatgen.core.structure.Structure.from_str`. Returns: A list of dict of the format ...
Returns the continuous symmetry measure(s) of site with index isite with respect to the perfect coordination environment with mp_symbol. For some environments, a given mp_symbol might not be available (if there is no voronoi parameters leading to a number of neighbours corresponding to the co...
Plotting of the coordination numbers of a given site for all the distfactor/angfactor parameters. If the chemical environments are given, a color map is added to the plot, with the lowest continuous symmetry measure as the value for the color of that distfactor/angfactor set. :param isite: Index...
Plotting of the coordination environments of a given site for all the distfactor/angfactor regions. The chemical environments with the lowest continuous symmetry measure is shown for each distfactor/angfactor region as the value for the color of that distfactor/angfactor region (using a colormap). ...
Plotting of the coordination numbers of a given site for all the distfactor/angfactor parameters. If the chemical environments are given, a color map is added to the plot, with the lowest continuous symmetry measure as the value for the color of that distfactor/angfactor set. :param isite: Index...
Bson-serializable dict representation of the StructureEnvironments object. :return: Bson-serializable dict representation of the StructureEnvironments object. def as_dict(self): """ Bson-serializable dict representation of the StructureEnvironments object. :return: Bson-serializable dic...
Reconstructs the StructureEnvironments object from a dict representation of the StructureEnvironments created using the as_dict method. :param d: dict representation of the StructureEnvironments object :return: StructureEnvironments object def from_dict(cls, d): """ Reconstructs...
Checks whether the structure contains a given atom in a given environment :param atom_symbol: Symbol of the atom :param ce_symbol: Symbol of the coordination environment :return: True if the coordination environment is found, False otherwise def structure_contains_atom_environment(self, atom_sy...
Bson-serializable dict representation of the LightStructureEnvironments object. :return: Bson-serializable dict representation of the LightStructureEnvironments object. def as_dict(self): """ Bson-serializable dict representation of the LightStructureEnvironments object. :return: Bson-s...
Reconstructs the LightStructureEnvironments object from a dict representation of the LightStructureEnvironments created using the as_dict method. :param d: dict representation of the LightStructureEnvironments object :return: LightStructureEnvironments object def from_dict(cls, d): """ ...
Returns the geometry with the minimum continuous symmetry measure of this ChemicalEnvironments :return: tuple (symbol, csm) with symbol being the geometry with the minimum continuous symmetry measure and csm being the continuous symmetry measure associted to it :raise: ValueError if no coordinat...
Returns a list of geometries with increasing continuous symmetry measure in this ChemicalEnvironments object :param n: Number of geometries to be included in the list :return: list of geometries with increasing continuous symmetry measure in this ChemicalEnvironments object :raise: ValueError if...
Adds a coordination geometry to the ChemicalEnvironments object :param mp_symbol: Symbol (internal) of the coordination geometry added :param symmetry_measure: Symmetry measure of the coordination geometry added :param algo: Algorithm used for the search of the coordination geometry added ...
Returns a dictionary representation of the ChemicalEnvironments object :return: def as_dict(self): """ Returns a dictionary representation of the ChemicalEnvironments object :return: """ return {"@module": self.__class__.__module__, "@class": self.__class...
Reconstructs the ChemicalEnvironments object from a dict representation of the ChemicalEnvironments created using the as_dict method. :param d: dict representation of the ChemicalEnvironments object :return: ChemicalEnvironments object def from_dict(cls, d): """ Reconstructs the...
Subroutine to extract bond label, site indices, and length from a LOBSTER header line. The site indices are zero-based, so they can be easily used with a Structure object. Example header line: No.4:Fe1->Fe9(2.4524893531900283) Example header line for orbtial-resolved COHP: N...
Returns: icohplist compatible with older version of this class def icohplist(self): """ Returns: icohplist compatible with older version of this class """ icohplist_new = {} for key, value in self._icohpcollection._icohplist.items(): icohplist_new[key] = {"length": v...
get a Structure with Mulliken and Loewdin charges as site properties Args: structure_filename: filename of POSCAR Returns: Structure Object with Mulliken and Loewdin charges as site properties def get_structure_with_charges(self, structure_filename): """ get a St...
returns a LobsterBandStructureSymmLine object which can be plotted with a normal BSPlotter def get_bandstructure(self): """ returns a LobsterBandStructureSymmLine object which can be plotted with a normal BSPlotter """ return LobsterBandStructureSymmLine(kpoints=self.kpoints_array, eig...
Get the decomposition leading to lowest cost Args: composition: Composition as a pymatgen.core.structure.Composition Returns: Decomposition as a dict of {Entry: amount} def get_lowest_decomposition(self, composition): """ Get the decomposition le...