text
stringlengths
81
112k
Average the actual time series of the |Variable| object for all time points. Method |IOSequence.average_series| works similarly as method |Variable.average_values| of class |Variable|, from which we borrow some examples. However, firstly, we have to prepare a |Timegrids| object ...
Aggregates time series data based on the actual |FluxSequence.aggregation_ext| attribute of |IOSequence| subclasses. We prepare some nodes and elements with the help of method |prepare_io_example_1| and select a 1-dimensional flux sequence of type |lland_fluxes.NKor| as an examp...
Assess to the state value(s) at beginning of the time step, which has been processed most recently. When using *HydPy* in the normal manner. But it can be helpful for demonstration and debugging purposes. def old(self): """Assess to the state value(s) at beginning of the time step, wh...
Read time series data like method |IOSequence.load_ext| of class |IOSequence|, but with special handling of missing data. The method's "special handling" is to convert errors to warnings. We explain the reasons in the documentation on method |Obs.load_ext| of class |Obs|, from which we ...
Read time series data like method |IOSequence.load_ext| of class |IOSequence|, but with special handling of missing data. When reading incomplete time series data, *HydPy* usually raises a |RuntimeError| to prevent from performing erroneous calculations. For instance, this makes sense f...
Open all files with an activated disk flag. def open_files(self, idx): """Open all files with an activated disk flag.""" for name in self: if getattr(self, '_%s_diskflag' % name): path = getattr(self, '_%s_path' % name) file_ = open(path, 'rb+') ...
Close all files with an activated disk flag. def close_files(self): """Close all files with an activated disk flag.""" for name in self: if getattr(self, '_%s_diskflag' % name): file_ = getattr(self, '_%s_file' % name) file_.close()
Load the internal data of all sequences. Load from file if the corresponding disk flag is activated, otherwise load from RAM. def load_data(self, idx): """Load the internal data of all sequences. Load from file if the corresponding disk flag is activated, otherwise load from RAM.""" f...
Save the internal data of all sequences with an activated flag. Write to file if the corresponding disk flag is activated; store in working memory if the corresponding ram flag is activated. def save_data(self, idx): """Save the internal data of all sequences with an activated flag. Wri...
Load the next sim sequence value (of the given index). def load_simdata(self, idx: int) -> None: """Load the next sim sequence value (of the given index).""" if self._sim_ramflag: self.sim[0] = self._sim_array[idx] elif self._sim_diskflag: raw = self._sim_file.read(8) ...
Save the last sim sequence value (of the given index). def save_simdata(self, idx: int) -> None: """Save the last sim sequence value (of the given index).""" if self._sim_ramflag: self._sim_array[idx] = self.sim[0] elif self._sim_diskflag: raw = struct.pack('d', self.sim...
Load the next obs sequence value (of the given index). def load_obsdata(self, idx: int) -> None: """Load the next obs sequence value (of the given index).""" if self._obs_ramflag: self.obs[0] = self._obs_array[idx] elif self._obs_diskflag: raw = self._obs_file.read(8) ...
Update |AbsFHRU| based on |FT| and |FHRU|. >>> from hydpy.models.lland import * >>> parameterstep('1d') >>> nhru(2) >>> lnk(ACKER) >>> ft(100.0) >>> fhru(0.2, 0.8) >>> derived.absfhru.update() >>> derived.absfhru absfhru(20.0, 80.0) def update(se...
Update |KInz| based on |HInz| and |LAI|. >>> from hydpy.models.lland import * >>> parameterstep('1d') >>> nhru(2) >>> hinz(0.2) >>> lai.acker_jun = 1.0 >>> lai.vers_dec = 2.0 >>> derived.kinz.update() >>> from hydpy import round_ >>> round_(derive...
Update |WB| based on |RelWB| and |NFk|. >>> from hydpy.models.lland import * >>> parameterstep('1d') >>> nhru(2) >>> lnk(ACKER) >>> relwb(0.2) >>> nfk(100.0, 200.0) >>> derived.wb.update() >>> derived.wb wb(20.0, 40.0) def update(self): "...
Update |WZ| based on |RelWZ| and |NFk|. >>> from hydpy.models.lland import * >>> parameterstep('1d') >>> nhru(2) >>> lnk(ACKER) >>> relwz(0.8) >>> nfk(100.0, 200.0) >>> derived.wz.update() >>> derived.wz wz(80.0, 160.0) def update(self): ...
Update |KB| based on |EQB| and |TInd|. >>> from hydpy.models.lland import * >>> parameterstep('1d') >>> eqb(10.0) >>> tind.value = 10.0 >>> derived.kb.update() >>> derived.kb kb(100.0) def update(self): """Update |KB| based on |EQB| and |TInd|. ...
Update |KI1| based on |EQI1| and |TInd|. >>> from hydpy.models.lland import * >>> parameterstep('1d') >>> eqi1(5.0) >>> tind.value = 10.0 >>> derived.ki1.update() >>> derived.ki1 ki1(50.0) def update(self): """Update |KI1| based on |EQI1| and |TInd|. ...
Update |KI2| based on |EQI2| and |TInd|. >>> from hydpy.models.lland import * >>> parameterstep('1d') >>> eqi2(1.0) >>> tind.value = 10.0 >>> derived.ki2.update() >>> derived.ki2 ki2(10.0) def update(self): """Update |KI2| based on |EQI2| and |TInd|. ...
Update |KD1| based on |EQD1| and |TInd|. >>> from hydpy.models.lland import * >>> parameterstep('1d') >>> eqd1(0.5) >>> tind.value = 10.0 >>> derived.kd1.update() >>> derived.kd1 kd1(5.0) def update(self): """Update |KD1| based on |EQD1| and |TInd|. ...
Update |KD2| based on |EQD2| and |TInd|. >>> from hydpy.models.lland import * >>> parameterstep('1d') >>> eqd2(0.1) >>> tind.value = 10.0 >>> derived.kd2.update() >>> derived.kd2 kd2(1.0) def update(self): """Update |KD2| based on |EQD2| and |TInd|. ...
Update |QFactor| based on |FT| and the current simulation step size. >>> from hydpy.models.lland import * >>> parameterstep('1d') >>> simulationstep('1d') >>> ft(10.0) >>> derived.qfactor.update() >>> derived.qfactor qfactor(0.115741) def update(self): "...
A tuple of the numbers of all "routing" basins. def _router_numbers(self): """A tuple of the numbers of all "routing" basins.""" return tuple(up for up in self._up2down.keys() if up in self._up2down.values())
A |Elements| collection of all "supplying" basins. (All river basins are assumed to supply something to the downstream basin.) >>> from hydpy import RiverBasinNumbers2Selection >>> rbns2s = RiverBasinNumbers2Selection( ... (111, 113, 1129, 11269, 1125...
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( ... (111, 11...
A |Nodes| collection of all required nodes. >>> from hydpy import RiverBasinNumbers2Selection >>> rbns2s = RiverBasinNumbers2Selection( ... (111, 113, 1129, 11269, 1125, 11261, ... 11262, 1123, 1124, 1122, 1121)) Note that ...
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). >>> 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's', b'']], dtype='|S1') >>> str2...
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([]) [] def chars2str(chars) -> List[str]: """Inversion function of fu...
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 TestIO >>> from hydpy.core.netcdftools import netcdf4 >...
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: >>> from hydpy import TestIO >>> from hydpy.core.netcdftools import ...
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 query_variable >>> from hydpy import TestIO >>> from hyd...
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.netcdftools import query_timegrid >>> filepath = 'LahnH...
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: >>> from hydpy import TestIO >>> from hydpy....
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,...
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') ...
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. When writing data, the second argument should be an |InfoArray|. When reading data, this argument is ignored. Simply pass |None|. (1) We prepare some devices handling some sequences by applying ...
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| objec...
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| ...
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: ...
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 writing modified (e.g. spatially averaged) time s...
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 NetCDFVariableBase, chars2str >>> from hydpy import make_abc...
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 the (sub)device names both under the assumptions th...
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 |Subdevice2Index| object remembers the NetCDF file the (s...
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 make_abc_testable >>> NCVar = make_abc_testable(NetCDFVariableBase) >>> ...
Return a |tuple| for indexing a complete time series of a certain location available in |NetCDFVariableBase.array|. >>> from hydpy.core.netcdftools import NetCDFVariableBase >>> from hydpy import make_abc_testable >>> NCVar = make_abc_testable(NetCDFVariableBase) >>> ncvar = NCV...
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. See the general documentation on classes |NetCDFVariableDeep| and |NetCDFVariableAgg| for some examples. def write(self, ncfile) -> None: """Write the data to the given NetCDF file. See the general documentation on classes |NetCDFVariableDeep| ...
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: >>> from hydpy.core.examples import prepare_io_e...
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 = NetCDFVariableDeep('test', isolate=False, timeaxis=1) >>> ncvar.get_slices(2...
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|: >>> from hydpy.core.examples import pr...
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 default configuration, the first axis defi...
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: >>> from hydpy.core.examples import prepare_i...
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. def read(self, ncfile, timegrid_data) -> None: """Read the data from the give...
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|: >>> from hydpy.core.examples import pre...
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, under default configuration (`timeaxis=1`), ...
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 timesteps: >>> from hydpy.core.examples...
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 default configuration (`timeaxis=1`), the ...
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 device names are returned >>> from hydpy.core.examp...
Should return all "subdevice index combinations" for sequences with arbitrary dimensions: >>> from hydpy.core.netcdftools import NetCDFVariableFlat >>> _product = NetCDFVariableFlat.__dict__['_product'].__func__ >>> for comb in _product([1, 2, 3]): ... print(comb) (0...
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. def read(self, ncfile, timegrid_data) -> None: """Read the data from the give...
Write the data to the given NetCDF file. See the general documentation on class |NetCDFVariableFlat| for some examples. def write(self, ncfile) -> None: """Write the data to the given NetCDF file. See the general documentation on class |NetCDFVariableFlat| for some examples. ...
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 hours, there is only one...
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.update() >>> derived.nmbsu...
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 period of five days: >>> from hydpy import pub >>> pub.timegrids Timegrids(Timegrid('2000-01-01 00:00:00', ...
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('.'))) ... for folder in ('control', 'conditi...
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 class |TestIO|, for convenience: >>> from hydpy.core.examples import prepare_full_example_2 >>> hp, pub, Test...
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] ...
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 players have shot chart data. It is the default ...
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 Name, First Name' format. Passing in ...
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. 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 abbreviation. Returns ------- t...
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 The multidimensional numpy array of t...
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....
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" or "01/06/2016") or the expa...
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 ------- self : TeamLog The TeamLog objec...
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...
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 callback (function): callback to be called def subscribe(se...
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 Subscription object max (int=None): number of messages def...
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 def publish(self, subject, msg, reply=None): """ Publish publishes the data arg...
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): payload string def request(self, subject, callback, msg=None): ...
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 def wait(self, duration=None, count=0): """ Publish publishes the data argument to t...
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) coordinate. Twenty-two feet from the left of the center of the hoo...
Returns an Axes object with player shots plotted. Parameters ---------- x, y : strings or vector The x and y coordinates of the shots taken. They can be passed in as vectors (such as a pandas Series) or as columns from the pandas DataFrame passed into ``data``. data : DataFrame...
Returns a JointGrid object containing the shot chart. This function allows for more flexibility in customizing your shot chart than the ``shot_chart_jointplot`` function. Parameters ---------- x, y : strings or vector The x and y coordinates of the shots taken. They can be passed in as ...
Returns a seaborn JointGrid using sns.jointplot Parameters ---------- x, y : strings or vector The x and y coordinates of the shots taken. They can be passed in as vectors (such as a pandas Series) or as column names from the pandas DataFrame passed into ``data``. data : DataFr...
Returns an AxesImage object that contains a heatmap. TODO: Redo some code and explain parameters 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, out...
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,0) coordinate. Twenty-two feet from the left of the center of th...
Returns a figure with both FGA and basketball court lines drawn onto it. This function expects data to be a ColumnDataSource with the x and y values named "LOC_X" and "LOC_Y". Otherwise specify x and y. Parameters ---------- data : DataFrame The DataFrame that contains the shot chart dat...
Update Cluster Centers: calculate the mean of feature vectors for each cluster. distance can be a string or callable. def _update_centers(X, membs, n_clusters, distance): """ Update Cluster Centers: calculate the mean of feature vectors for each cluster. distance can be a st...
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) ...
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_...
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_ii - 2 sum w_jh K_ih + sum_r sum_s ...
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 ...
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. def __log_density_single(x, mean, covar): """ This is just a test function to calculate ...
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-mu)) def _log_multivariate_density(X, means, covars): """ ...