INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
A |Elements| collection of all routing basins.
def router_elements(self): """A |Elements| collection of all "routing" basins. (Only river basins with a upstream basin are assumed to route something to the downstream basin.) >>> from hydpy import RiverBasinNumbers2Selection >>> rbns2s = RiverBasinNumbers2Selection( ....
A |Nodes| collection of all required nodes.
def nodes(self): """A |Nodes| collection of all required nodes. >>> from hydpy import RiverBasinNumbers2Selection >>> rbns2s = RiverBasinNumbers2Selection( ... (111, 113, 1129, 11269, 1125, 11261, ... 11262, 1123, 1124, 1122...
A complete |Selection| object of all supplying and routing elements and required nodes.
def selection(self): """A complete |Selection| object of all "supplying" and "routing" elements and required nodes. >>> from hydpy import RiverBasinNumbers2Selection >>> rbns2s = RiverBasinNumbers2Selection( ... (111, 113, 1129, 11269, 1125, 11261, ...
Return |numpy. ndarray| containing the byte characters ( second axis ) of all given strings ( first axis ).
def str2chars(strings) -> numpy.ndarray: """Return |numpy.ndarray| containing the byte characters (second axis) of all given strings (first axis). >>> from hydpy.core.netcdftools import str2chars >>> str2chars(['zeros', 'ones']) array([[b'z', b'e', b'r', b'o', b's'], [b'o', b'n', b'e', b...
Inversion function of function |str2chars|.
def chars2str(chars) -> List[str]: """Inversion function of function |str2chars|. >>> from hydpy.core.netcdftools import chars2str >>> chars2str([[b'z', b'e', b'r', b'o', b's'], ... [b'o', b'n', b'e', b's', b'']]) ['zeros', 'ones'] >>> chars2str([]) [] """ strings = col...
Add a new dimension with the given name and length to the given NetCDF file.
def create_dimension(ncfile, name, length) -> None: """Add a new dimension with the given name and length to the given NetCDF file. Essentially, |create_dimension| just calls the equally named method of the NetCDF library, but adds information to possible error messages: >>> from hydpy import Test...
Add a new variable with the given name datatype and dimensions to the given NetCDF file.
def create_variable(ncfile, name, datatype, dimensions) -> None: """Add a new variable with the given name, datatype, and dimensions to the given NetCDF file. Essentially, |create_variable| just calls the equally named method of the NetCDF library, but adds information to possible error messages: ...
Return the variable with the given name from the given NetCDF file.
def query_variable(ncfile, name) -> netcdf4.Variable: """Return the variable with the given name from the given NetCDF file. Essentially, |query_variable| just performs a key assess via the used NetCDF library, but adds information to possible error messages: >>> from hydpy.core.netcdftools import que...
Return the |Timegrid| defined by the given NetCDF file.
def query_timegrid(ncfile) -> timetools.Timegrid: """Return the |Timegrid| defined by the given NetCDF file. >>> from hydpy.core.examples import prepare_full_example_1 >>> prepare_full_example_1() >>> from hydpy import TestIO >>> from hydpy.core.netcdftools import netcdf4 >>> from hydpy.core.ne...
Return the data of the variable with the given name from the given NetCDF file.
def query_array(ncfile, name) -> numpy.ndarray: """Return the data of the variable with the given name from the given NetCDF file. The following example shows that |query_array| returns |nan| entries to represent missing values even when the respective NetCDF variable defines a different fill value...
Prepare a |NetCDFFile| object suitable for the given |IOSequence| object when necessary and pass the given arguments to its |NetCDFFile. log| method.
def log(self, sequence, infoarray) -> None: """Prepare a |NetCDFFile| object suitable for the given |IOSequence| object, when necessary, and pass the given arguments to its |NetCDFFile.log| method.""" if isinstance(sequence, sequencetools.ModelSequence): descr = sequence.desc...
Call method |NetCDFFile. read| of all handled |NetCDFFile| objects.
def read(self) -> None: """Call method |NetCDFFile.read| of all handled |NetCDFFile| objects. """ for folder in self.folders.values(): for file_ in folder.values(): file_.read()
Call method |NetCDFFile. write| of all handled |NetCDFFile| objects.
def write(self) -> None: """Call method |NetCDFFile.write| of all handled |NetCDFFile| objects. """ if self.folders: init = hydpy.pub.timegrids.init timeunits = init.firstdate.to_cfunits('hours') timepoints = init.to_timepoints('hours') for folder ...
A |tuple| of names of all handled |NetCDFFile| objects.
def filenames(self) -> Tuple[str, ...]: """A |tuple| of names of all handled |NetCDFFile| objects.""" return tuple(sorted(set(itertools.chain( *(_.keys() for _ in self.folders.values())))))
Pass the given |IoSequence| to a suitable instance of a |NetCDFVariableBase| subclass.
def log(self, sequence, infoarray) -> None: """Pass the given |IoSequence| to a suitable instance of a |NetCDFVariableBase| subclass. When writing data, the second argument should be an |InfoArray|. When reading data, this argument is ignored. Simply pass |None|. (1) We prepare...
The NetCDF file path.
def filepath(self) -> str: """The NetCDF file path.""" return os.path.join(self._dirpath, self.name + '.nc')
Open an existing NetCDF file temporarily and call method |NetCDFVariableDeep. read| of all handled |NetCDFVariableBase| objects.
def read(self) -> None: """Open an existing NetCDF file temporarily and call method |NetCDFVariableDeep.read| of all handled |NetCDFVariableBase| objects.""" try: with netcdf4.Dataset(self.filepath, "r") as ncfile: timegrid = query_timegrid(ncfile) ...
Open a new NetCDF file temporarily and call method |NetCDFVariableBase. write| of all handled |NetCDFVariableBase| objects.
def write(self, timeunit, timepoints) -> None: """Open a new NetCDF file temporarily and call method |NetCDFVariableBase.write| of all handled |NetCDFVariableBase| objects.""" with netcdf4.Dataset(self.filepath, "w") as ncfile: ncfile.Conventions = 'CF-1.6' self._...
Item access to the wrapped |dict| object with a specialized error message.
def get_index(self, name_subdevice) -> int: """Item access to the wrapped |dict| object with a specialized error message.""" try: return self.dict_[name_subdevice] except KeyError: raise OSError( 'No data for sequence `%s` and (sub)device `%s` ' ...
Log the given |IOSequence| object either for reading or writing data.
def log(self, sequence, infoarray) -> None: """Log the given |IOSequence| object either for reading or writing data. The optional `array` argument allows for passing alternative data in an |InfoArray| object replacing the series of the |IOSequence| object, which is useful for wr...
Insert a variable of the names of the ( sub ) devices of the logged sequences into the given NetCDF file
def insert_subdevices(self, ncfile) -> None: """Insert a variable of the names of the (sub)devices of the logged sequences into the given NetCDF file (1) We prepare a |NetCDFVariableBase| subclass with fixed (sub)device names: >>> from hydpy.core.netcdftools import NetCDFVariab...
Query the names of the ( sub ) devices of the logged sequences from the given NetCDF file
def query_subdevices(self, ncfile) -> List[str]: """Query the names of the (sub)devices of the logged sequences from the given NetCDF file (1) We apply function |NetCDFVariableBase.query_subdevices| on an empty NetCDF file. The error message shows that the method tries to query...
Return a |Subdevice2Index| that maps the ( sub ) device names to their position within the given NetCDF file.
def query_subdevice2index(self, ncfile) -> Subdevice2Index: """Return a |Subdevice2Index| that maps the (sub)device names to their position within the given NetCDF file. Method |NetCDFVariableBase.query_subdevice2index| is based on |NetCDFVariableBase.query_subdevices|. The returned ...
Return a |tuple| containing the given timeentry and placeentry sorted in agreement with the currently selected timeaxis.
def sort_timeplaceentries(self, timeentry, placeentry) -> Tuple[Any, Any]: """Return a |tuple| containing the given `timeentry` and `placeentry` sorted in agreement with the currently selected `timeaxis`. >>> from hydpy.core.netcdftools import NetCDFVariableBase >>> from hydpy import ma...
Return a |tuple| for indexing a complete time series of a certain location available in |NetCDFVariableBase. array|.
def get_timeplaceslice(self, placeindex) -> \ Union[Tuple[slice, int], Tuple[int, slice]]: """Return a |tuple| for indexing a complete time series of a certain location available in |NetCDFVariableBase.array|. >>> from hydpy.core.netcdftools import NetCDFVariableBase >>> fro...
A |tuple| containing the device names.
def subdevicenames(self) -> Tuple[str, ...]: """A |tuple| containing the device names.""" self: NetCDFVariableBase return tuple(self.sequences.keys())
Write the data to the given NetCDF file.
def write(self, ncfile) -> None: """Write the data to the given NetCDF file. See the general documentation on classes |NetCDFVariableDeep| and |NetCDFVariableAgg| for some examples. """ self: NetCDFVariableBase self.insert_subdevices(ncfile) dimensions = self.dim...
The dimension names of the NetCDF variable.
def dimensions(self) -> Tuple[str, ...]: """The dimension names of the NetCDF variable. Usually, the string defined by property |IOSequence.descr_sequence| prefixes the first dimension name related to the location, which allows storing different sequences types in one NetCDF file: ...
Return a |tuple| of one |int| and some |slice| objects to accesses all values of a certain device within |NetCDFVariableDeep. array|.
def get_slices(self, idx, shape) -> Tuple[IntOrSlice, ...]: """Return a |tuple| of one |int| and some |slice| objects to accesses all values of a certain device within |NetCDFVariableDeep.array|. >>> from hydpy.core.netcdftools import NetCDFVariableDeep >>> ncvar = NetCDFVariabl...
Required shape of |NetCDFVariableDeep. array|.
def shape(self) -> Tuple[int, ...]: """Required shape of |NetCDFVariableDeep.array|. For the default configuration, the first axis corresponds to the number of devices, and the second one to the number of timesteps. We show this for the 0-dimensional input sequence |lland_inputs.Nied|: ...
The series data of all logged |IOSequence| objects contained in one single |numpy. ndarray|.
def array(self) -> numpy.ndarray: """The series data of all logged |IOSequence| objects contained in one single |numpy.ndarray|. The documentation on |NetCDFVariableDeep.shape| explains how |NetCDFVariableDeep.array| is structured. The first example confirms that, for the defau...
The dimension names of the NetCDF variable.
def dimensions(self) -> Tuple[str, ...]: """The dimension names of the NetCDF variable. Usually, the string defined by property |IOSequence.descr_sequence| prefixes all dimension names except the second one related to time, which allows storing different sequences in one NetCDF file: ...
Read the data from the given NetCDF file.
def read(self, ncfile, timegrid_data) -> None: """Read the data from the given NetCDF file. The argument `timegrid_data` defines the data period of the given NetCDF file. See the general documentation on class |NetCDFVariableDeep| for some examples. """ array = ...
Required shape of |NetCDFVariableAgg. array|.
def shape(self) -> Tuple[int, int]: """Required shape of |NetCDFVariableAgg.array|. For the default configuration, the first axis corresponds to the number of devices, and the second one to the number of timesteps. We show this for the 1-dimensional input sequence |lland_fluxes.NKor|: ...
The aggregated data of all logged |IOSequence| objects contained in one single |numpy. ndarray| object.
def array(self) -> numpy.ndarray: """The aggregated data of all logged |IOSequence| objects contained in one single |numpy.ndarray| object. The documentation on |NetCDFVariableAgg.shape| explains how |NetCDFVariableAgg.array| is structured. This first example confirms that, und...
Required shape of |NetCDFVariableFlat. array|.
def shape(self) -> Tuple[int, int]: """Required shape of |NetCDFVariableFlat.array|. For 0-dimensional sequences like |lland_inputs.Nied| and for the default configuration (`timeaxis=1`), the first axis corresponds to the number of devices, and the second one two the number of t...
The series data of all logged |IOSequence| objects contained in one single |numpy. ndarray| object.
def array(self) -> numpy.ndarray: """The series data of all logged |IOSequence| objects contained in one single |numpy.ndarray| object. The documentation on |NetCDFVariableAgg.shape| explains how |NetCDFVariableAgg.array| is structured. The first example confirms that, under de...
A |tuple| containing the ( sub ) device names.
def subdevicenames(self) -> Tuple[str, ...]: """A |tuple| containing the (sub)device names. Property |NetCDFVariableFlat.subdevicenames| clarifies which row of |NetCDFVariableAgg.array| contains which time series. For 0-dimensional series like |lland_inputs.Nied|, the plain devi...
Should return all subdevice index combinations for sequences with arbitrary dimensions:
def _product(shape) -> Iterator[Tuple[int, ...]]: """Should return all "subdevice index combinations" for sequences with arbitrary dimensions: >>> from hydpy.core.netcdftools import NetCDFVariableFlat >>> _product = NetCDFVariableFlat.__dict__['_product'].__func__ >>> for comb i...
Read the data from the given NetCDF file.
def read(self, ncfile, timegrid_data) -> None: """Read the data from the given NetCDF file. The argument `timegrid_data` defines the data period of the given NetCDF file. See the general documentation on class |NetCDFVariableFlat| for some examples. """ array = ...
Write the data to the given NetCDF file.
def write(self, ncfile) -> None: """Write the data to the given NetCDF file. See the general documentation on class |NetCDFVariableFlat| for some examples. """ self.insert_subdevices(ncfile) create_variable(ncfile, self.name, 'f8', self.dimensions) ncfile[self.na...
Determine the number of substeps.
def update(self): """Determine the number of substeps. Initialize a llake model and assume a simulation step size of 12 hours: >>> from hydpy.models.llake import * >>> parameterstep('1d') >>> simulationstep('12h') If the maximum internal step size is also set to 12 hou...
Calulate the auxilary term.
def update(self): """Calulate the auxilary term. >>> from hydpy.models.llake import * >>> parameterstep('1d') >>> simulationstep('12h') >>> n(3) >>> v(0., 1e5, 1e6) >>> q(_1=[0., 1., 2.], _7=[0., 2., 5.]) >>> maxdt('12h') >>> derived.seconds.updat...
Prepare an IO example configuration.
def prepare_io_example_1() -> Tuple[devicetools.Nodes, devicetools.Elements]: # noinspection PyUnresolvedReferences """Prepare an IO example configuration. >>> from hydpy.core.examples import prepare_io_example_1 >>> nodes, elements = prepare_io_example_1() (1) Prepares a short initialisation peri...
Prepare the complete LahnH project for testing.
def prepare_full_example_1() -> None: """Prepare the complete `LahnH` project for testing. >>> from hydpy.core.examples import prepare_full_example_1 >>> prepare_full_example_1() >>> from hydpy import TestIO >>> import os >>> with TestIO(): ... print('root:', *sorted(os.listdir('.'))) ...
Prepare the complete LahnH project for testing.
def prepare_full_example_2(lastdate='1996-01-05') -> ( hydpytools.HydPy, hydpy.pub, testtools.TestIO): """Prepare the complete `LahnH` project for testing. |prepare_full_example_2| calls |prepare_full_example_1|, but also returns a readily prepared |HydPy| instance, as well as module |pub| and ...
Bounding box calculations updated from pyzipcode
def get_postalcodes_around_radius(self, pc, radius): postalcodes = self.get(pc) if postalcodes is None: raise PostalCodeNotFoundException("Could not find postal code you're searching for.") else: pc = postalcodes[0] radius = float(radius) ...
Returns a pandas DataFrame containing the player IDs used in the stats. nba. com API.
def get_all_player_ids(ids="shots"): """ Returns a pandas DataFrame containing the player IDs used in the stats.nba.com API. Parameters ---------- ids : { "shots" | "all_players" | "all_data" }, optional Passing in "shots" returns a DataFrame that contains the player IDs of all ...
Returns the player ID ( s ) associated with the player name that is passed in.
def get_player_id(player): """ Returns the player ID(s) associated with the player name that is passed in. There are instances where players have the same name so there are multiple player IDs associated with it. Parameters ---------- player : str The desired player's name in 'Last...
Returns a pandas DataFrame with all Team IDs
def get_all_team_ids(): """Returns a pandas DataFrame with all Team IDs""" df = get_all_player_ids("all_data") df = pd.DataFrame({"TEAM_NAME": df.TEAM_NAME.unique(), "TEAM_ID": df.TEAM_ID.unique()}) return df
Returns the team ID associated with the team name that is passed in.
def get_team_id(team_name): """ Returns the team ID associated with the team name that is passed in. Parameters ---------- team_name : str The team name whose ID we want. NOTE: Only pass in the team name (e.g. "Lakers"), not the city, or city and team name, or the team abbrevia...
Returns the image of the player from stats. nba. com as a numpy array and saves the image as PNG file in the current directory.
def get_player_img(player_id): """ Returns the image of the player from stats.nba.com as a numpy array and saves the image as PNG file in the current directory. Parameters ---------- player_id: int The player ID used to find the image. Returns ------- player_img: ndarray ...
Returns team game logs as a pandas DataFrame
def get_game_logs(self): """Returns team game logs as a pandas DataFrame""" logs = self.response.json()['resultSets'][0]['rowSet'] headers = self.response.json()['resultSets'][0]['headers'] df = pd.DataFrame(logs, columns=headers) df.GAME_DATE = pd.to_datetime(df.GAME_DATE) ...
Returns the Game ID associated with the date that is passed in.
def get_game_id(self, date): """Returns the Game ID associated with the date that is passed in. Parameters ---------- date : str The date associated with the game whose Game ID. The date that is passed in can take on a numeric format of MM/DD/YY (like "01/06/16" ...
Pass in a dictionary to update url parameters for NBA stats API
def update_params(self, parameters): """Pass in a dictionary to update url parameters for NBA stats API Parameters ---------- parameters : dict A dict containing key, value pairs that correspond with NBA stats API parameters. Returns ------- ...
Returns the shot chart data as a pandas DataFrame.
def get_shots(self): """Returns the shot chart data as a pandas DataFrame.""" shots = self.response.json()['resultSets'][0]['rowSet'] headers = self.response.json()['resultSets'][0]['headers'] return pd.DataFrame(shots, columns=headers)
Connect will attempt to connect to the NATS server. The url can contain username/ password semantics.
def connect(self): """ Connect will attempt to connect to the NATS server. The url can contain username/password semantics. """ self._build_socket() self._connect_socket() self._build_file_socket() self._send_connect_msg()
Subscribe will express interest in the given subject. The subject can have wildcards ( partial: * full: > ). Messages will be delivered to the associated callback.
def subscribe(self, subject, callback, queue=''): """ Subscribe will express interest in the given subject. The subject can have wildcards (partial:*, full:>). Messages will be delivered to the associated callback. Args: subject (string): a string with the subject ...
Unsubscribe will remove interest in the given subject. If max is provided an automatic Unsubscribe that is processed by the server when max messages have been received
def unsubscribe(self, subscription, max=None): """ Unsubscribe will remove interest in the given subject. If max is provided an automatic Unsubscribe that is processed by the server when max messages have been received Args: subscription (pynats.Subscription): a Subs...
Publish publishes the data argument to the given subject.
def publish(self, subject, msg, reply=None): """ Publish publishes the data argument to the given subject. Args: subject (string): a string with the subject msg (string): payload string reply (string): subject used in the reply """ if msg is N...
ublish a message with an implicit inbox listener as the reply. Message is optional.
def request(self, subject, callback, msg=None): """ ublish a message with an implicit inbox listener as the reply. Message is optional. Args: subject (string): a string with the subject callback (function): callback to be called msg (string=None): pay...
Publish publishes the data argument to the given subject.
def wait(self, duration=None, count=0): """ Publish publishes the data argument to the given subject. Args: duration (float): will wait for the given number of seconds count (count): stop of wait after n messages from any subject """ start = time.time() ...
Returns an axes with a basketball court drawn onto to it.
def draw_court(ax=None, color='gray', lw=1, outer_lines=False): """Returns an axes with a basketball court drawn onto to it. This function draws a court based on the x and y-axis values that the NBA stats API provides for the shot chart data. For example the center of the hoop is located at the (0,0) ...
Returns an Axes object with player shots plotted.
def shot_chart(x, y, kind="scatter", title="", color="b", cmap=None, xlim=(-250, 250), ylim=(422.5, -47.5), court_color="gray", court_lw=1, outer_lines=False, flip_court=False, kde_shade=True, gridsize=None, ax=None, despine=False, **kwargs): """ Retur...
Returns a JointGrid object containing the shot chart.
def shot_chart_jointgrid(x, y, data=None, joint_type="scatter", title="", joint_color="b", cmap=None, xlim=(-250, 250), ylim=(422.5, -47.5), court_color="gray", court_lw=1, outer_lines=False, flip_court=False, joint_kde...
Returns a seaborn JointGrid using sns. jointplot
def shot_chart_jointplot(x, y, data=None, kind="scatter", title="", color="b", cmap=None, xlim=(-250, 250), ylim=(422.5, -47.5), court_color="gray", court_lw=1, outer_lines=False, flip_court=False, size=(12, 11), space=0, ...
Returns an AxesImage object that contains a heatmap.
def heatmap(x, y, z, title="", cmap=plt.cm.YlOrRd, bins=20, xlim=(-250, 250), ylim=(422.5, -47.5), facecolor='lightgray', facecolor_alpha=0.4, court_color="black", court_lw=0.5, outer_lines=False, flip_court=False, ax=None, **kwargs): """ Returns an AxesImage obj...
Returns a figure with the basketball court lines drawn onto it
def bokeh_draw_court(figure, line_color='gray', line_width=1): """Returns a figure with the basketball court lines drawn onto it This function draws a court based on the x and y-axis values that the NBA stats API provides for the shot chart data. For example the center of the hoop is located at the (0...
Returns a figure with both FGA and basketball court lines drawn onto it.
def bokeh_shot_chart(data, x="LOC_X", y="LOC_Y", fill_color="#1f77b4", scatter_size=10, fill_alpha=0.4, line_alpha=0.4, court_line_color='gray', court_line_width=1, hover_tool=False, tooltips=None, **kwargs): # TODO: Settings for hover tooltip """ ...
Update Cluster Centers: calculate the mean of feature vectors for each cluster.
def _update_centers(X, membs, n_clusters, distance): """ Update Cluster Centers: calculate the mean of feature vectors for each cluster. distance can be a string or callable. """ centers = np.empty(shape=(n_clusters, X.shape[1]), dtype=float) sse = np.empty(shape=n_clusters, dtype=fl...
Run a single trial of k - medoids clustering on dataset X and given number of clusters
def _kmedoids_run(X, n_clusters, distance, max_iter, tol, rng): """ Run a single trial of k-medoids clustering on dataset X, and given number of clusters """ membs = np.empty(shape=X.shape[0], dtype=int) centers = kmeans._kmeans_init(X, n_clusters, method='', rng=rng) sse_last = 9999.9 ...
Apply KMeans Clustering X: dataset with feature vectors
def fit(self, X): """ Apply KMeans Clustering X: dataset with feature vectors """ self.centers_, self.labels_, self.sse_arr_, self.n_iter_ = \ _kmedoids(X, self.n_clusters, self.distance, self.max_iter, self.n_trials, self.tol, self.rng)
Computin the distance in transformed feature space to cluster centers. K is the kernel gram matrix. wmemb contains cluster assignment. { 0 1 }
def _kernelized_dist2centers(K, n_clusters, wmemb, kernel_dist): """ Computin the distance in transformed feature space to cluster centers. K is the kernel gram matrix. wmemb contains cluster assignment. {0,1} Assume j is the cluster id: ||phi(x_i) - Phi_center_j|| = K_i...
Initialize mixture density parameters with equal priors random means identity covariance matrices
def _init_mixture_params(X, n_mixtures, init_method): """ Initialize mixture density parameters with equal priors random means identity covariance matrices """ init_priors = np.ones(shape=n_mixtures, dtype=float) / n_mixtures if init_method == 'kmeans': km = _km...
This is just a test function to calculate the normal density at x given mean and covariance matrix.
def __log_density_single(x, mean, covar): """ This is just a test function to calculate the normal density at x given mean and covariance matrix. Note: this function is not efficient, so _log_multivariate_density is recommended for use. """ n_dim = mean.shape[0] dx = x - ...
Class conditional density: P ( x | mu Sigma ) = 1/ (( 2pi ) ^d/ 2 * |Sigma|^1/ 2 ) * exp ( - 1/ 2 * ( x - mu ) ^T * Sigma^ - 1 * ( x - mu ))
def _log_multivariate_density(X, means, covars): """ Class conditional density: P(x | mu, Sigma) = 1/((2pi)^d/2 * |Sigma|^1/2) * exp(-1/2 * (x-mu)^T * Sigma^-1 * (x-mu)) log of class conditional density: log P(x | mu, Sigma) = -1/2*(d*log(2pi) + log(|Sigma|) + (x-mu)^T * Sigma^-1 * (x-m...
Theta = ( theta_1 theta_2... theta_M ) Likelihood of mixture parameters given data: L ( Theta | X ) = product_i P ( x_i | Theta ) log likelihood: log L ( Theta | X ) = sum_i log ( P ( x_i | Theta ))
def _log_likelihood_per_sample(X, means, covars): """ Theta = (theta_1, theta_2, ... theta_M) Likelihood of mixture parameters given data: L(Theta | X) = product_i P(x_i | Theta) log likelihood: log L(Theta | X) = sum_i log(P(x_i | Theta)) and note that p(x_i | Theta) = sum_j prior_j * p(x_...
Validation Check for M. L. paramateres
def _validate_params(priors, means, covars): """ Validation Check for M.L. paramateres """ for i,(p,m,cv) in enumerate(zip(priors, means, covars)): if np.any(np.isinf(p)) or np.any(np.isnan(p)): raise ValueError("Component %d of priors is not valid " % i) if np.any(np.isinf(m))...
Update class parameters as below: priors: P ( w_i ) = sum_x P ( w_i | x ) == > Then normalize to get in [ 0 1 ] Class means: center_w_i = sum_x P ( w_i|x ) * x/ sum_i sum_x P ( w_i|x )
def _maximization_step(X, posteriors): """ Update class parameters as below: priors: P(w_i) = sum_x P(w_i | x) ==> Then normalize to get in [0,1] Class means: center_w_i = sum_x P(w_i|x)*x / sum_i sum_x P(w_i|x) """ ### Prior probabilities or class weights sum_post_proba = np.sum...
Fit mixture - density parameters with EM algorithm
def fit(self, X): """ Fit mixture-density parameters with EM algorithm """ params_dict = _fit_gmm_params(X=X, n_mixtures=self.n_clusters, \ n_init=self.n_trials, init_method=self.init_method, \ n_iter=self.max_iter, tol=self.tol) self.prior...
Initialize k = n_clusters centroids randomly
def _kmeans_init(X, n_clusters, method='balanced', rng=None): """ Initialize k=n_clusters centroids randomly """ n_samples = X.shape[0] if rng is None: cent_idx = np.random.choice(n_samples, replace=False, size=n_clusters) else: #print('Generate random centers using RNG') cen...
Assignment Step: assign each point to the closet cluster center
def _assign_clusters(X, centers): """ Assignment Step: assign each point to the closet cluster center """ dist2cents = scipy.spatial.distance.cdist(X, centers, metric='seuclidean') membs = np.argmin(dist2cents, axis=1) return(membs)
Calculate the SSE to the cluster center
def _cal_dist2center(X, center): """ Calculate the SSE to the cluster center """ dmemb2cen = scipy.spatial.distance.cdist(X, center.reshape(1,X.shape[1]), metric='seuclidean') return(np.sum(dmemb2cen))
Update Cluster Centers: calculate the mean of feature vectors for each cluster
def _update_centers(X, membs, n_clusters): """ Update Cluster Centers: calculate the mean of feature vectors for each cluster """ centers = np.empty(shape=(n_clusters, X.shape[1]), dtype=float) sse = np.empty(shape=n_clusters, dtype=float) for clust_id in range(n_clusters): memb_i...
Run a single trial of k - means clustering on dataset X and given number of clusters
def _kmeans_run(X, n_clusters, max_iter, tol): """ Run a single trial of k-means clustering on dataset X, and given number of clusters """ membs = np.empty(shape=X.shape[0], dtype=int) centers = _kmeans_init(X, n_clusters) sse_last = 9999.9 n_iter = 0 for it in range(1,max_iter): ...
Run multiple trials of k - means clustering and outputt he best centers and cluster labels
def _kmeans(X, n_clusters, max_iter, n_trials, tol): """ Run multiple trials of k-means clustering, and outputt he best centers, and cluster labels """ n_samples, n_features = X.shape[0], X.shape[1] centers_best = np.empty(shape=(n_clusters,n_features), dtype=float) labels_best = np.empty(...
Apply KMeans Clustering X: dataset with feature vectors
def fit(self, X): """ Apply KMeans Clustering X: dataset with feature vectors """ self.centers_, self.labels_, self.sse_arr_, self.n_iter_ = \ _kmeans(X, self.n_clusters, self.max_iter, self.n_trials, self.tol)
Cut the tree to get desired number of clusters as n_clusters 2 < = n_desired < = n_clusters
def _cut_tree(tree, n_clusters, membs): """ Cut the tree to get desired number of clusters as n_clusters 2 <= n_desired <= n_clusters """ ## starting from root, ## a node is added to the cut_set or ## its children are added to node_set assert(n_clusters >= 2) assert(n_clusters <...
Add a node to the tree if parent is not known the node is a root
def _add_tree_node(tree, label, ilev, X=None, size=None, center=None, sse=None, parent=None): """ Add a node to the tree if parent is not known, the node is a root The nodes of this tree keep properties of each cluster/subcluster: size --> cluster size as the number of points in the ...
Apply Bisecting Kmeans clustering to reach n_clusters number of clusters
def _bisect_kmeans(X, n_clusters, n_trials, max_iter, tol): """ Apply Bisecting Kmeans clustering to reach n_clusters number of clusters """ membs = np.empty(shape=X.shape[0], dtype=int) centers = dict() #np.empty(shape=(n_clusters,X.shape[1]), dtype=float) sse_arr = dict() #-1.0*np.ones(sha...
r Returns the corrected Deviance Information Criterion ( DIC ) for all chains loaded into ChainConsumer.
def dic(self): r""" Returns the corrected Deviance Information Criterion (DIC) for all chains loaded into ChainConsumer. If a chain does not have a posterior, this method will return `None` for that chain. **Note that the DIC metric is only valid on posterior surfaces which closely resemble mul...
r Returns the corrected Bayesian Information Criterion ( BIC ) for all chains loaded into ChainConsumer.
def bic(self): r""" Returns the corrected Bayesian Information Criterion (BIC) for all chains loaded into ChainConsumer. If a chain does not have a posterior, number of data points, and number of free parameters loaded, this method will return `None` for that chain. Formally, the BIC is defined...
r Returns the corrected Akaike Information Criterion ( AICc ) for all chains loaded into ChainConsumer.
def aic(self): r""" Returns the corrected Akaike Information Criterion (AICc) for all chains loaded into ChainConsumer. If a chain does not have a posterior, number of data points, and number of free parameters loaded, this method will return `None` for that chain. Formally, the AIC is defined ...
Return a LaTeX ready table of model comparisons.
def comparison_table(self, caption=None, label="tab:model_comp", hlines=True, aic=True, bic=True, dic=True, sort="bic", descending=True): # pragma: no cover """ Return a LaTeX ready table of model comparisons. Parameters ---------- caption : str, option...
Estimate un - normalised probability density at target points Parameters ---------- data: np. ndarray A ( num_targets num_dim ) array of points to investigate. Returns ------- np. ndarray A ( num_targets ) length array of estimates
def evaluate(self, data): """ Estimate un-normalised probability density at target points Parameters ---------- data : np.ndarray A `(num_targets, num_dim)` array of points to investigate. Returns ------- np.ndarray A `(n...
Plot the chain!
def plot(self, figsize="GROW", parameters=None, chains=None, extents=None, filename=None, display=False, truth=None, legend=None, blind=None, watermark=None): # pragma: no cover """ Plot the chain! Parameters ---------- figsize : str|tuple(float)|float, optional ...
Plots the chain walk ; the parameter values as a function of step index.
def plot_walks(self, parameters=None, truth=None, extents=None, display=False, filename=None, chains=None, convolve=None, figsize=None, plot_weights=True, plot_posterior=True, log_weight=None): # pragma: no cover """ Plots the chain walk; the parameter values as a function...
Plots the 1D parameter distributions for verification purposes.
def plot_distributions(self, parameters=None, truth=None, extents=None, display=False, filename=None, chains=None, col_wrap=4, figsize=None, blind=None): # pragma: no cover """ Plots the 1D parameter distributions for verification purposes. This plot is more for a sanity or ...
Plots parameter summaries
def plot_summary(self, parameters=None, truth=None, extents=None, display=False, filename=None, chains=None, figsize=1.0, errorbar=False, include_truth_chain=True, blind=None, watermark=None, extra_parameter_spacing=0.5, vertical_spacing_ratio=1.0, show_nam...
r Runs the Gelman Rubin diagnostic on the supplied chains.
def gelman_rubin(self, chain=None, threshold=0.05): r""" Runs the Gelman Rubin diagnostic on the supplied chains. Parameters ---------- chain : int|str, optional Which chain to run the diagnostic on. By default, this is `None`, which will run the diagnostic on al...