INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Perform histogram matching of the time-series with respect to a reference scene :param eopatch: eopatch holding the time-series and reference data :type eopatch: EOPatch :return: The same eopatch instance with the normalised time-series
def execute(self, eopatch): """ Perform histogram matching of the time-series with respect to a reference scene :param eopatch: eopatch holding the time-series and reference data :type eopatch: EOPatch :return: The same eopatch instance with the normalised time-series ...
Checks if value fits the feature type. If not it tries to fix it or raise an error :raises: ValueError
def _parse_feature_value(self, value): """ Checks if value fits the feature type. If not it tries to fix it or raise an error :raises: ValueError """ if isinstance(value, _FileLoader): return value if not hasattr(self, 'ndim'): # Because of serialization/dese...
Helper method for loading old version of pickled BBox object :param bbox: BBox object which was incorrectly loaded with pickle :type bbox: sentinelhub.BBox :param path: Path to file where BBox object is stored :type path: str :param is_zipped: `True` if file is zipped and ...
def _correctly_load_bbox(bbox, path, is_zipped=False): """ Helper method for loading old version of pickled BBox object :param bbox: BBox object which was incorrectly loaded with pickle :type bbox: sentinelhub.BBox :param path: Path to file where BBox object is stored :typ...
Method which loads data from the file
def load(self): """ Method which loads data from the file """ # pylint: disable=too-many-return-statements if not os.path.isdir(self.patch_path): raise OSError('EOPatch does not exist in path {} anymore'.format(self.patch_path)) path = self.get_file_path() ...
Creates a filename with file path
def get_file_path(self, path): """ Creates a filename with file path """ feature_filename = self._get_filename_path(path) feature_filename += self.file_format.extension() if self.compress_level: feature_filename += FileFormat.GZIP.extension() return...
Helper function for creating filename without file extension
def _get_filename_path(self, path): """ Helper function for creating filename without file extension """ feature_filename = os.path.join(path, self.feature_type.value) if self.feature_name is not None: feature_filename = os.path.join(feature_filename, self.feature_name...
Method which does the saving :param eopatch: EOPatch containing the data which will be saved :type eopatch: EOPatch :param use_tmp: If `True` data will be saved to temporary file, otherwise it will be saved to intended (i.e. final) location :type use_tmp: bool
def save(self, eopatch, use_tmp=True): """ Method which does the saving :param eopatch: EOPatch containing the data which will be saved :type eopatch: EOPatch :param use_tmp: If `True` data will be saved to temporary file, otherwise it will be saved to intended (i.e. final...
Masks values of data feature with a given mask of given mask type. The masking is done by assigning `numpy.nan` value. :param feature_data: Data array which will be masked :type feature_data: numpy.ndarray :param mask: Mask array :type mask: numpy.ndarray :param mask_typ...
def _mask_feature_data(feature_data, mask, mask_type): """ Masks values of data feature with a given mask of given mask type. The masking is done by assigning `numpy.nan` value. :param feature_data: Data array which will be masked :type feature_data: numpy.ndarray :param mask: M...
Find NaN values in data that either start or end the time-series Function to return a binary array of same size as data where `True` values correspond to NaN values present at beginning or end of time-series. NaNs internal to the time-series are not included in the binary mask. :param data: Ar...
def _get_start_end_nans(data): """ Find NaN values in data that either start or end the time-series Function to return a binary array of same size as data where `True` values correspond to NaN values present at beginning or end of time-series. NaNs internal to the time-series are not included i...
Replace duplicate acquisitions which have same values on the chosen time scale with their average. The average is calculated with numpy.nanmean, meaning that NaN values are ignored when calculating the average. :param data: Array in a shape of t x nobs, where nobs = h x w x n :type data: numpy....
def _get_unique_times(data, times): """ Replace duplicate acquisitions which have same values on the chosen time scale with their average. The average is calculated with numpy.nanmean, meaning that NaN values are ignored when calculating the average. :param data: Array in a shape of t x nobs, w...
Copy features from old EOPatch :param new_eopatch: New EOPatch container where the old features will be copied to :type new_eopatch: EOPatch :param old_eopatch: Old EOPatch container where the old features are located :type old_eopatch: EOPatch :param copy_features: List of tupl...
def _copy_old_features(new_eopatch, old_eopatch, copy_features): """ Copy features from old EOPatch :param new_eopatch: New EOPatch container where the old features will be copied to :type new_eopatch: EOPatch :param old_eopatch: Old EOPatch container where the old features are located ...
Interpolates data feature :param data: Array in a shape of t x nobs, where nobs = h x w x n :type data: numpy.ndarray :param times: Array of reference times relative to the first timestamp :type times: numpy.array :param resampled_times: Array of reference times relative to the ...
def interpolate_data(self, data, times, resampled_times): """ Interpolates data feature :param data: Array in a shape of t x nobs, where nobs = h x w x n :type data: numpy.ndarray :param times: Array of reference times relative to the first timestamp :type times: numpy.array ...
Initializes interpolation model :param times: Array of reference times in second relative to the first timestamp :type times: numpy.array :param series: One dimensional array of time series :type series: numpy.array :return: Initialized interpolation model class
def get_interpolation_function(self, times, series): """ Initializes interpolation model :param times: Array of reference times in second relative to the first timestamp :type times: numpy.array :param series: One dimensional array of time series :type series: numpy.array ...
Takes a list of timestamps and generates new list of timestamps according to ``resample_range`` :param timestamp: list of timestamps :type timestamp: list(datetime.datetime) :return: new list of timestamps :rtype: list(datetime.datetime)
def get_resampled_timestamp(self, timestamp): """ Takes a list of timestamps and generates new list of timestamps according to ``resample_range`` :param timestamp: list of timestamps :type timestamp: list(datetime.datetime) :return: new list of timestamps :rtype: list(datetime.d...
Execute method that processes EOPatch and returns EOPatch
def execute(self, eopatch): """ Execute method that processes EOPatch and returns EOPatch """ # pylint: disable=too-many-locals feature_type, feature_name, new_feature_name = next(self.feature(eopatch)) # Make a copy not to change original numpy array feature_data = eopa...
Initializes interpolation model :param times: Array of reference times in second relative to the first timestamp :type times: numpy.array :param data: One dimensional array of time series :type data: numpy.array :return: Initialized interpolation model class
def get_interpolation_function(self, times, data): """ Initializes interpolation model :param times: Array of reference times in second relative to the first timestamp :type times: numpy.array :param data: One dimensional array of time series :type data: numpy.array :ret...
Interpolates data feature :param data: Array in a shape of t x nobs, where nobs = h x w x n :type data: numpy.ndarray :param times: Array of reference times in second relative to the first timestamp :type times: numpy.array :param resampled_times: Array of reference times in sec...
def interpolate_data(self, data, times, resampled_times): """ Interpolates data feature :param data: Array in a shape of t x nobs, where nobs = h x w x n :type data: numpy.ndarray :param times: Array of reference times in second relative to the first timestamp :type times: numpy...
return inner text in pyquery element
def get_text(element): ''' return inner text in pyquery element ''' _add_links_to_text(element) try: return element.text(squash_space=False) except TypeError: return element.text()
Simple wrapper around urlretrieve that uses tqdm to display a progress bar of download progress
def download_file(url, local_filename): """ Simple wrapper around urlretrieve that uses tqdm to display a progress bar of download progress """ local_filename = os.path.abspath(local_filename) path = os.path.dirname(local_filename) if not os.path.isdir(path): os.makedirs(path) with tqdm...
Try to find GCC on OSX for OpenMP support.
def extract_gcc_binaries(): """Try to find GCC on OSX for OpenMP support.""" patterns = ['/opt/local/bin/g++-mp-[0-9].[0-9]', '/opt/local/bin/g++-mp-[0-9]', '/usr/local/bin/g++-[0-9].[0-9]', '/usr/local/bin/g++-[0-9]'] if 'darwin' in platform.platform().lower(...
Try to use GCC on OSX for OpenMP support.
def set_gcc(): """Try to use GCC on OSX for OpenMP support.""" # For macports and homebrew if 'darwin' in platform.platform().lower(): gcc = extract_gcc_binaries() if gcc is not None: os.environ["CC"] = gcc os.environ["CXX"] = gcc else: global u...
returns the non zeroes of a row in csr_matrix
def nonzeros(m, row): """ returns the non zeroes of a row in csr_matrix """ for index in range(m.indptr[row], m.indptr[row+1]): yield m.indices[index], m.data[index]
checks to see if using OpenBlas/Intel MKL. If so, warn if the number of threads isn't set to 1 (causes severe perf issues when training - can be 10x slower)
def check_blas_config(): """ checks to see if using OpenBlas/Intel MKL. If so, warn if the number of threads isn't set to 1 (causes severe perf issues when training - can be 10x slower) """ # don't warn repeatedly global _checked_blas_config if _checked_blas_config: return _checked_blas_...
Reads the original dataset PSV as a pandas dataframe
def _read_dataframe(filename): """ Reads the original dataset PSV as a pandas dataframe """ import pandas # read in triples of user/artist/playcount from the input dataset # get a model based off the input params start = time.time() log.debug("reading data from %s", filename) data = pandas....
Returns the lastfm360k dataset, downloading locally if necessary. Returns a tuple of (artistids, userids, plays) where plays is a CSR matrix
def get_lastfm(): """ Returns the lastfm360k dataset, downloading locally if necessary. Returns a tuple of (artistids, userids, plays) where plays is a CSR matrix """ filename = os.path.join(_download.LOCAL_CACHE_DIR, "lastfm_360k.hdf5") if not os.path.isfile(filename): log.info("Downloading da...
factorizes the matrix Cui using an implicit alternating least squares algorithm. Note: this method is deprecated, consider moving to the AlternatingLeastSquares class instead
def alternating_least_squares(Ciu, factors, **kwargs): """ factorizes the matrix Cui using an implicit alternating least squares algorithm. Note: this method is deprecated, consider moving to the AlternatingLeastSquares class instead """ log.warning("This method is deprecated. Please use the Altern...
For each user in Cui, calculate factors Xu for them using least squares on Y. Note: this is at least 10 times slower than the cython version included here.
def least_squares(Cui, X, Y, regularization, num_threads=0): """ For each user in Cui, calculate factors Xu for them using least squares on Y. Note: this is at least 10 times slower than the cython version included here. """ users, n_factors = X.shape YtY = Y.T.dot(Y) for u in range(us...
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...
def fit(self, item_users, show_progress=True): """ 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 ...
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 train on GPU.") if self.dtype == np.float64: lo...
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...
def explain(self, userid, user_items, itemid, user_weights=None, N=10): """ 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 cont...
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 ...
def augment_inner_product_matrix(factors): """ 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 R...
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, numSlices=len(m.row)/1024) return spark.createDataFrame(d...
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 based off the input params start = time.time() ...
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 -> position track_lookup = dict((t.encode("utf8"), i) for i, t in enumerate(data...
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_matrix(X) X.data = X.data / sqrt(bincount(X.row, X.data ** 2))[X.row] return X
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 document (artist) row_sums = numpy.ravel(X.sum(axis=1...
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_threads=self.num_threads).tocsr() self...
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]: raise ValueError("userid is out of bounds of the us...
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(selected_items) >= user_items.shape[1] or min(selected_items)...
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
def get_reddit(): """ 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 ...
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 off the input params start = time.time() log.deb...
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...
def get_movielens(variant="20m"): """ 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. ...
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="."): """ 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./ ...
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.join(path, "u.item"), ...
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...
def recommend(self, userid, user_items, N=10, filter_already_liked_items=True, filter_items=None, recalculate_user=False): """ Recommends items for a user Calculates the N best recommendations for a user, and returns a list of itemids, score. Parameters ------...
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): return os.path.abspath(binpath) ...
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...
def locate_cuda(): """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...
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_lastfm() # create a model from the input data model = get_model(model_name) # if we're trainin...
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 input data model = get_model(model_name) # if we're tr...
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 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 """ m = re.search(r"\[(...
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(entry, MultiEntry): return " + ".join([latexify_ion(e.name) for e in entry.entry_list]) else: return late...
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 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 """ return se...
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_conditions(self, pH, V): """ 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 b...
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 calculated when constructing a PourbaixEntry object. """ d = {"@module": self.__class__.__module__, "@class": self.__class__.__name__} ...
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["concentration...
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 ...
def _generate_multielement_entries(self, entries, forced_include=None, nproc=None): """ Create entries for multi-element Pourbaix construction. This works by finding all possible linear combinations of entries that can result in the specified compo...
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. ...
def process_multientry(entry_list, prod_comp, coeff_threshold=1e-4): """ 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 compositi...
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 entry V (float): V to find stable entry Returns: """ energies_at_conditions = [e.normalized_energy_at_conditions(pH, V) ...
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...
def get_decomposition_energy(self, entry, pH, V): """ 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 ...
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 **kwargs: kwargs to get_pourbaix_plot Returns: None """ plt = self.get_pourbaix_plot(*args, **kwargs) plt.show()
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...
def get_pourbaix_plot(self, limits=None, title="", label_domains=True, plt=None): """ Plot Pourbaix diagram. Args: limits: 2D list containing limits of the Pourbaix diagram of the form [[xlo, xhi], [ylo, yhi]] title (str): Title ...
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...
def fast_ordering(self, structure, num_remove_dict, num_to_return=1): """ 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 con...
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...
def apply_transformation(self, structure, return_ranked_list=False): """ 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 ...
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 """ new_structure = structure.copy() for prop in self.site_properties.keys(): new_structure.add_site_p...
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...
def write_lammps_inputs(output_dir, script_template, settings=None, data=None, script_filename="in.lammps", make_dir_if_not_present=True, **kwargs): """ Writes input files for a LAMMPS run. Input script is constructed from a str template with placeholders to b...
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): """ 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 LammpsDa...
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...
def md(cls, data, force_field, temperature, nsteps, other_settings=None): """ 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...
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: reciprocal lattice vectors with energy less than encut """ vol = np.dot(a1, np.cross(a2, a3)) # 1/bohr^3 b1 = (2 * np.pi / vol) * np.cross(a2, a3) # units...
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...
def generate_reciprocal_vectors_squared(a1, a2, a3, encut): """ 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: Reciproc...
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 position for both bulk and defect structures Args: struct_blk: Bulk structure struct_def: Defect structure pos: Position Return: (site object, dist, index) """ blk_close_sites = struc...
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: raise Exception("Did not converge before...
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 squared reciprocal vector. Args: g2: Square of reciprocal vector Returns: Charge density at the reciprocal vector magnitude """ return (self.expnorm / np.sqrt(1 + sel...
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 """ return -2 * self.gamma2 * self.expnorm - 0.25 * self.beta2 * ( 1 - self.expnorm)
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 ...
def make_supercells_with_defects(self, scaling_matrix): """ 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: scal...
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 is taken into account. """ lattice = self.structure.lattice vfcoords = [v.frac_coords for v in self.vnodes] # M...
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 structure Args: min_dist(float): The minimum distance that a vertex needs to be from existing atoms. """ vfcoords = [v.frac_coords for v in self.v...
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(self.structure) for v in self.vnodes: new_s.append("X", v.frac_coords) return ne...
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_axis_grid(i)) / self.structure.lattice....
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: logger.warning( # Exit if both filter a...
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...
def get_local_extrema(self, find_min=True, threshold_frac=None, threshold_abs=None): """ Get all local extrema fractional coordinates in charge density, searching for local minimum by default. Note that sites are NOT grouped symmetrically. Args: ...
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 is taken into account. """ lattice = self.structure.lattice vf_coords = self.extrema_coords if len(vf_coords) ==...
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...
def remove_collisions(self, min_dist=0.5): """ 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 ...
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 ...
def get_structure_with_nodes(self, find_min=True, min_dist=0.5, tol=0.2, threshold_frac=None, threshold_abs=None): """ Get the modified structure with the possible interstitial sites added. The species is set as a DummySpecie X. Args: find_mi...
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 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 """ if self.extrema...
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...
def multiple_outputs_from_file(cls, filename, keep_sub_files=True): """ 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 calcua...
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') if temp_charge != None: ...
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\-\.]+)\s*([\d\-\.]+)\s*" footer...
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" else: ...
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 Charges\s+Atom\s+Charge \(a\.u\.\)\s+Spin\s\(a\.u\.\)\s+\-+" tab...
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\)\s+ATOM\s+X\s+Y\s+Z" table_pattern = r"\s+\d+\s+\w+\s+([\d\-\.]+)\s+([...
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.data.get("energy_trajectory"))) + \ r"\s+Coordinates \(Angstroms\)\s+ATOM\s...
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+([\d\-\.]+)(?:\s+([\d\-\.]+))*)*", "IR_int...
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"\s*SCF\s+energy in the final basis set\s+=\s*([\d\-\.]+)" }...