text
stringlengths
81
112k
Convert PyStan data into an InferenceData object. Parameters ---------- posterior : StanFit4Model or stan.fit.Fit PyStan fit object for posterior. posterior_predictive : str, a list of str Posterior predictive samples for the posterior. prior : StanFit4Model or stan.fit.Fit ...
Extract posterior samples from fit. def posterior_to_xarray(self): """Extract posterior samples from fit.""" posterior = self.posterior # filter posterior_predictive and log_likelihood posterior_predictive = self.posterior_predictive if posterior_predictive is None: ...
Extract sample_stats from posterior. def sample_stats_to_xarray(self): """Extract sample_stats from posterior.""" posterior = self.posterior # copy dims and coords dims = deepcopy(self.dims) if self.dims is not None else {} coords = deepcopy(self.coords) if self.coords is...
Convert posterior_predictive samples to xarray. def posterior_predictive_to_xarray(self): """Convert posterior_predictive samples to xarray.""" posterior = self.posterior posterior_predictive = self.posterior_predictive data = get_draws(posterior, variables=posterior_predictive) ...
Convert prior samples to xarray. def prior_to_xarray(self): """Convert prior samples to xarray.""" prior = self.prior # filter posterior_predictive and log_likelihood prior_predictive = self.prior_predictive if prior_predictive is None: prior_predictive = [] ...
Extract sample_stats_prior from prior. def sample_stats_prior_to_xarray(self): """Extract sample_stats_prior from prior.""" prior = self.prior data = get_sample_stats(prior) return dict_to_dataset(data, library=self.pystan, coords=self.coords, dims=self.dims)
Convert prior_predictive samples to xarray. def prior_predictive_to_xarray(self): """Convert prior_predictive samples to xarray.""" prior = self.prior prior_predictive = self.prior_predictive data = get_draws(prior, variables=prior_predictive) return dict_to_dataset(data, l...
Extract posterior samples from fit. def posterior_to_xarray(self): """Extract posterior samples from fit.""" posterior = self.posterior posterior_model = self.posterior_model # filter posterior_predictive and log_likelihood posterior_predictive = self.posterior_predictive ...
Extract sample_stats from posterior. def sample_stats_to_xarray(self): """Extract sample_stats from posterior.""" posterior = self.posterior posterior_model = self.posterior_model # copy dims and coords dims = deepcopy(self.dims) if self.dims is not None else {} co...
Convert posterior_predictive samples to xarray. def posterior_predictive_to_xarray(self): """Convert posterior_predictive samples to xarray.""" posterior = self.posterior posterior_model = self.posterior_model posterior_predictive = self.posterior_predictive data = get_draw...
Convert prior samples to xarray. def prior_to_xarray(self): """Convert prior samples to xarray.""" prior = self.prior prior_model = self.prior_model # filter posterior_predictive and log_likelihood prior_predictive = self.prior_predictive if prior_predictive is Non...
Extract sample_stats_prior from prior. def sample_stats_prior_to_xarray(self): """Extract sample_stats_prior from prior.""" prior = self.prior prior_model = self.prior_model data = get_sample_stats_stan3(prior, model=prior_model) return dict_to_dataset(data, library=self.st...
Convert prior_predictive samples to xarray. def prior_predictive_to_xarray(self): """Convert prior_predictive samples to xarray.""" prior = self.prior prior_model = self.prior_model prior_predictive = self.prior_predictive data = get_draws_stan3(prior, model=prior_model, va...
Convert observed data to xarray. def observed_data_to_xarray(self): """Convert observed data to xarray.""" posterior_model = self.posterior_model if self.dims is None: dims = {} else: dims = self.dims observed_names = self.observed_data if...
Extract latent and observed variable names from pyro.MCMC. Parameters ---------- posterior : pyro.MCMC Fitted MCMC object from Pyro Returns ------- list[str], list[str] observed and latent variable names from the MCMC trace. def _get_var_names(posterior): """Extract latent and...
Convert pyro data into an InferenceData object. Parameters ---------- posterior : pyro.MCMC Fitted MCMC object from Pyro coords : dict[str] -> list[str] Map of dimensions to coordinates dims : dict[str] -> list[str] Map variable names to their coordinates def from_pyro(post...
Convert the posterior to an xarray dataset. def posterior_to_xarray(self): """Convert the posterior to an xarray dataset.""" # Do not make pyro a requirement from pyro.infer import EmpiricalMarginal try: # Try pyro>=0.3 release syntax data = { name: np.expa...
Bar plot of the autocorrelation function for a sequence of data. Useful in particular for posteriors from MCMC samples which may display correlation. Parameters ---------- data : obj Any object that can be converted to an az.InferenceData object Refer to documentation of az.convert_to_...
Plot energy transition distribution and marginal energy distribution in HMC algorithms. This may help to diagnose poor exploration by gradient-based algorithms like HMC or NUTS. Parameters ---------- data : xarray dataset, or object that can be converted (must represent `sample_stats` and h...
From itertools cookbook. [a, b, c, ...] -> (a, b), (b, c), ... def pairwise(iterable): """From itertools cookbook. [a, b, c, ...] -> (a, b), (b, c), ...""" first, second = tee(iterable) next(second, None) return zip(first, second)
Forest plot to compare credible intervals from a number of distributions. Generates a forest plot of 100*(credible_interval)% credible intervals from a trace or list of traces. Parameters ---------- data : obj or list[obj] Any object that can be converted to an az.InferenceData object ...
Initialize an object for each variable to be plotted. def make_plotters(self): """Initialize an object for each variable to be plotted.""" plotters, y = {}, 0 for var_name in self.var_names: plotters[var_name] = VarHandler( var_name, self.data, ...
Collect labels and ticks from plotters. def labels_and_ticks(self): """Collect labels and ticks from plotters.""" labels, idxs = [], [] for plotter in self.plotters.values(): sub_labels, sub_idxs, _, _ = plotter.labels_ticks_and_vals() labels.append(sub_labels) ...
Display ROPE when more than one interval is provided. def display_multiple_ropes(self, rope, ax, y, linewidth, rope_var): """Display ROPE when more than one interval is provided.""" vals = dict(rope[rope_var][0])["rope"] ax.plot( vals, (y + 0.05, y + 0.05), l...
Draw ridgeplot for each plotter. Parameters ---------- mult : float How much to multiply height by. Set this to greater than 1 to have some overlap. linewidth : float Width of line on border of ridges alpha : float Transparency of ridges ...
Draw forestplot for each plotter. Parameters ---------- credible_interval : float How wide each line should be quartiles : bool Whether to mark quartiles xt_textsize : float Size of tick text titlesize : float Size of title...
Draw effective n for each plotter. def plot_neff(self, ax, xt_labelsize, titlesize, markersize): """Draw effective n for each plotter.""" for plotter in self.plotters.values(): for y, ess, color in plotter.ess(): if ess is not None: ax.plot( ...
Draw r-hat for each plotter. def plot_rhat(self, ax, xt_labelsize, titlesize, markersize): """Draw r-hat for each plotter.""" for plotter in self.plotters.values(): for y, r_hat, color in plotter.r_hat(): if r_hat is not None: ax.plot(r_hat, y, "o", color...
Draw shaded horizontal bands for each plotter. def make_bands(self, ax): """Draw shaded horizontal bands for each plotter.""" y_vals, y_prev, is_zero = [0], None, False prev_color_index = 0 for plotter in self.plotters.values(): for y, *_, color in plotter.iterator(): ...
Figure out the height of this plot. def fig_height(self): """Figure out the height of this plot.""" # hand-tuned return ( 4 + len(self.data) * len(self.var_names) - 1 + 0.1 * sum(1 for j in self.plotters.values() for _ in j.iterator()) )
Iterate over models and chains for each variable. def iterator(self): """Iterate over models and chains for each variable.""" if self.combined: grouped_data = [[(0, datum)] for datum in self.data] skip_dims = {"chain"} else: grouped_data = [datum.groupby("cha...
Get labels, ticks, values, and colors for the variable. def labels_ticks_and_vals(self): """Get labels, ticks, values, and colors for the variable.""" y_ticks = defaultdict(list) for y, label, _, vals, color in self.iterator(): y_ticks[label].append((y, vals, color)) labels,...
Get data for each treeplot for the variable. def treeplot(self, qlist, credible_interval): """Get data for each treeplot for the variable.""" for y, _, label, values, color in self.iterator(): ntiles = np.percentile(values.flatten(), qlist) ntiles[0], ntiles[-1] = hpd(values.fla...
Get data for each ridgeplot for the variable. def ridgeplot(self, mult): """Get data for each ridgeplot for the variable.""" xvals, yvals, pdfs, colors = [], [], [], [] for y, *_, values, color in self.iterator(): yvals.append(y) colors.append(color) values =...
Get effective n data for the variable. def ess(self): """Get effective n data for the variable.""" _, y_vals, values, colors = self.labels_ticks_and_vals() for y, value, color in zip(y_vals, values, colors): if value.ndim != 2 or value.shape[0] < 2: yield y, None, co...
Get rhat data for the variable. def r_hat(self): """Get rhat data for the variable.""" _, y_vals, values, colors = self.labels_ticks_and_vals() for y, value, color in zip(y_vals, values, colors): if value.ndim != 2 or value.shape[0] < 2: yield y, None, color ...
Get max y value for the variable. def y_max(self): """Get max y value for the variable.""" end_y = max(y for y, *_ in self.iterator()) if self.combined: end_y += self.group_offset return end_y + 2 * self.group_offset
Plot Pareto tail indices. Parameters ---------- khats : array Pareto tail indices. figsize : tuple Figure size. If None it will be defined automatically. textsize: float Text size scaling factor for labels, titles and lines. If None it will be autoscaled based on fig...
Generate KDE plots for continuous variables and histograms for discrete ones. Plots are truncated at their 100*(1-alpha)% credible intervals. Plots are grouped per variable and colors assigned to models. Parameters ---------- data : Union[Object, Iterator[Object]] Any object that can be co...
Plot an individual dimension. Parameters ---------- vec : array 1D array from trace vname : str variable name color : str matplotlib color bw : float Bandwidth scaling factor. Should be larger than 0. The higher this number the smoother the KDE will be. D...
1D or 2D KDE plot taking into account boundary conditions. Parameters ---------- values : array-like Values to plot values2 : array-like, optional Values to plot. If present, a 2D KDE will be estimated cumulative : bool If true plot the estimated cumulative distribution func...
Fast Fourier transform-based Gaussian kernel density estimate (KDE). The code was adapted from https://github.com/mfouesneau/faststats Parameters ---------- x : Numpy array or list cumulative : bool If true, estimate the cdf instead of the pdf bw : float Bandwidth scaling facto...
2D fft-based Gaussian kernel density estimate (KDE). The code was adapted from https://github.com/mfouesneau/faststats Parameters ---------- x : Numpy array or list y : Numpy array or list gridsize : tuple Number of points used to discretize data. Use powers of 2 for fft optimization ...
Handle var_names input across arviz. Parameters ---------- var_names: str, list, or None data : xarray.Dataset Posterior data in an xarray Returns ------- var_name: list or None def _var_names(var_names, data): """Handle var_names input across arviz. Parameters -------...
Use numba's jit decorator if numba is installed. Notes ----- If called without arguments then return wrapped function. @conditional_jit def my_func(): return else called with arguments @conditional_jit(nopython=True) def my_func(): ret...
Plot a scatter or hexbin matrix of the sampled parameters. Parameters ---------- data : obj Any object that can be converted to an az.InferenceData object Refer to documentation of az.convert_to_dataset for details var_names : list of variable names Variables to be plotted, if N...
Extract a module-level docstring def extract_docstring(self): """ Extract a module-level docstring """ lines = open(self.filename).readlines() start_row = 0 if lines[0].startswith('#!'): lines.pop(0) start_row = 1 docstring = '' first_par...
Plot distribution as histogram or kernel density estimates. By default continuous variables are plotted using KDEs and discrete ones using histograms Parameters ---------- values : array-like Values to plot values2 : array-like, optional Values to plot. If present, a 2D KDE or a he...
Add a histogram for the data to the axes. def _histplot_op(values, values2, rotated, ax, hist_kwargs): """Add a histogram for the data to the axes.""" if values2 is not None: raise NotImplementedError("Insert hexbin plot here") bins = hist_kwargs.pop("bins") if bins is None: bins = get...
Plot for posterior predictive checks. Parameters ---------- data : az.InferenceData object InferenceData object containing the observed and posterior predictive data. kind : str Type of plot to display (density, cumulative, or scatter). Defaults to density. alpha : float ...
Save dataset as a netcdf file. WARNING: Only idempotent in case `data` is InferenceData Parameters ---------- data : InferenceData, or any object accepted by `convert_to_inference_data` Object to be saved filename : str name or path of the file to load trace group : str (option...
Save dataset as a netcdf file. WARNING: Only idempotent in case `data` is InferenceData Parameters ---------- data : InferenceData, or any object accepted by `convert_to_inference_data` Object to be saved filename : str name or path of the file to load trace group : str (option...
Convert any array into a 2d numpy array. In case the array is already more than 2 dimensional, will ravel the dimensions after the first. def make_2d(ary): """Convert any array into a 2d numpy array. In case the array is already more than 2 dimensional, will ravel the dimensions after the first. ...
Scale figure properties according to rows and cols. Parameters ---------- figsize : float or None Size of figure in inches textsize : float or None fontsize rows : int Number of rows cols : int Number of columns Returns ------- figsize : float or Non...
Automatically compute the number of bins for discrete variables. Parameters ---------- values = numpy array values Returns ------- array with the bins Notes ----- Computes the width of the bins by taking the maximun of the Sturges and the Freedman-Diaconis estimators. ...
Make a grid for subplots. Tries to get as close to sqrt(n_items) x sqrt(n_items) as it can, but allows for custom logic Parameters ---------- n_items : int Number of panels required max_cols : int Maximum number of columns, inclusive min_cols : int Minimum number of...
Create figure and axes for grids with multiple plots. Parameters ---------- n_items : int Number of panels required rows : int Number of rows cols : int Number of columns Returns ------- fig : matplotlib figure ax : matplotlib axes def _create_axes_grid(len...
Consistent labelling for plots. Parameters ---------- var_name : str Name of the variable selection : dict[Any] -> Any Coordinates of the variable position : whether to position the coordinates' label "below" (default) or "beside" the name of the variable Returns...
Remove duplicates from list while preserving order. Parameters ---------- list_in: Iterable Returns ------- list List of first occurences in order def purge_duplicates(list_in): """Remove duplicates from list while preserving order. Parameters ---------- list_in: Iter...
Convert xarray data to an iterator over vectors. Iterates over each var_name and all of its coordinates, returning the 1d data. Parameters ---------- data : xarray.Dataset Posterior data in an xarray var_names : iterator of strings (optional) Should be a subset of data.data_va...
Take xarray data and unpacks into variables and data into list and numpy array respectively. Assumes that chain and draw are in coordinates Parameters ---------- data: xarray.DataSet Data in an xarray from an InferenceData object. Examples include posterior or sample_stats var_names: iter...
Subselects xarray dataset object to provided coords. Raises exception if fails. Raises ------ ValueError If coords name are not available in data KeyError If coords dims are not available in data Returns ------- data: xarray xarray.Dataset object def get_coords(da...
r"""Convert a supported object to an InferenceData object. This function sends `obj` to the right conversion function. It is idempotent, in that it will return arviz.InferenceData objects unchanged. Parameters ---------- obj : dict, str, np.ndarray, xr.Dataset, pystan fit, pymc3 trace A su...
Convert a supported object to an xarray dataset. This function is idempotent, in that it will return xarray.Dataset functions unchanged. Raises `ValueError` if the desired group can not be extracted. Note this goes through a DataInference object. See `convert_to_inference_data` for more details. Raise...
Use Sturges' formula to determine number of bins. See https://en.wikipedia.org/wiki/Histogram#Sturges'_formula or https://doi.org/10.1080%2F01621459.1926.10502161 Parameters ---------- dataset: xarray.DataSet Must have the `draw` dimension mult: float Used to scale the number ...
Plot rank order statistics of chains. From the paper: Rank plots are histograms of the ranked posterior draws (ranked over all chains) plotted separately for each chain. If all of the chains are targeting the same posterior, we expect the ranks in each chain to be uniform, whereas if one chain has a ...
Creates ExpandedTextAds that use ad customizations for specified AdGroups. Args: client: an AdWordsClient instance. adgroup_ids: a list containing the AdGroup ids to add ExpandedTextAds to. feed_name: the name of the feed used to apply customizations. Raises: GoogleAdsError: if no ExpandedTextAds ...
Creates a new AdCustomizerFeed. Args: client: an AdWordsClient instance. feed_name: the name for the new AdCustomizerFeed. Returns: The new AdCustomizerFeed. def CreateCustomizerFeed(client, feed_name): """Creates a new AdCustomizerFeed. Args: client: an AdWordsClient instance. feed_name...
Restricts the feed item to an ad group. Args: client: an AdWordsClient instance. feed_item: The feed item. adgroup_id: The ad group ID. def RestrictFeedItemToAdGroup(client, feed_item, adgroup_id): """Restricts the feed item to an ad group. Args: client: an AdWordsClient instance. feed_item...
Creates FeedItems for the specified AdGroups. These FeedItems contain values to use in ad customizations for the AdGroups. Args: client: an AdWordsClient instance. adgroup_ids: a list containing two AdGroup Ids. ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems with. ...
Creates a FeedItemOperation. The generated FeedItemOperation will create a FeedItem with the specified values when sent to FeedItemService.mutate. Args: name: the value for the name attribute of the FeedItem. price: the value for the price attribute of the FeedItem. date: the value for the date attr...
Creates an AdWordsClient with information stored in a yaml string. Args: yaml_doc: The yaml string containing the cached AdWords data. Returns: An AdWordsClient initialized with the values cached in the string. Raises: A GoogleAdsValueError if the given yaml string does not contain the ...
Creates an AdWordsClient with information stored in a yaml file. Args: [optional] path: The path string to the file containing cached AdWords data. Returns: An AdWordsClient initialized with the values cached in the file. Raises: A GoogleAdsValueError if the given yaml file does n...
Creates a service client for the given service. Args: service_name: A string identifying which AdWords service to create a service client for. [optional] version: A string identifying the AdWords version to connect to. This defaults to what is currently the latest version. Thi...
Returns a BatchJobHelper to work with the BatchJobService. This is a convenience method. It is functionally identical to calling BatchJobHelper(adwords_client, version). Args: [optional] version: A string identifying the AdWords version to connect to. This defaults to what is cur...
Creates a downloader for AdWords reports. This is a convenience method. It is functionally identical to calling ReportDownloader(adwords_client, version, server). Args: [optional] version: A string identifying the AdWords version to connect to. This defaults to what is currently the ...
Returns the SOAP headers required for request authorization. Args: create_method: The SOAP library specific method used to instantiate SOAP objects. Returns: A SOAP object containing the headers. def GetSOAPHeaders(self, create_method): """Returns the SOAP headers required for request a...
Returns the HTTP headers required for request authorization. Returns: A dictionary containing the required headers. def GetHTTPHeaders(self): """Returns the HTTP headers required for request authorization. Returns: A dictionary containing the required headers. """ http_headers = self....
Returns a dictionary of headers for a report download request. Note that the given keyword arguments will override any settings configured from the googleads.yaml file. Args: **kwargs: Optional keyword arguments. Keyword Arguments: client_customer_id: A string containing a client_customer...
Pack the given object using AdWords-specific logic. Args: obj: an object to be packed for SOAP using AdWords-specific logic, if applicable. version: the version of the current API, e.g. 'v201809' Returns: The given object packed with AdWords-specific logic for SOAP, if applic...
Loads an IncrementalUploadHelper from the given file-like object. Args: file_input: a file-like object containing a serialized IncrementalUploadHelper. client: an AdWordsClient instance. If not specified, an AdWordsClient will be instantiated using the default configuration file. R...
Ensures that the URL used to upload operations is properly initialized. Args: upload_url: a string url. current_content_length: an integer identifying the current content length of data uploaded to the Batch Job. Returns: An initialized string URL, or the provided string URL if the U...
Serialize the IncrementalUploadHelper and store in file-like object. Args: output: a file-like object where the status of the IncrementalUploadHelper will be written. Raises: GoogleAdsError: If a YAMLError occurs while writing to the file. def Dump(self, output): """Serialize the Incr...
Uploads operations to the given uploadUrl in incremental steps. Note: Each list of operations is expected to contain operations of the same type, similar to how one would normally send operations in an AdWords API Service request. Args: operations: one or more lists of operations as would be sen...
Extract fields used in the summary logs. Args: request: a urllib2.Request instance configured to make the request. [optional] error: a urllib2.HttpError instance used to retrieve error details. Returns: A dict containing the fields to be output in the summary logs. def _ExtractReques...
Creates a WHERE builder using a provided field. Args: field: the field to be added as an argument in the WHERE clause. Returns: The created WHERE builder. def Where(self, field): """Creates a WHERE builder using a provided field. Args: field: the field to be added as an argument in...
Sets the type of the WHERE clause as "equal to". Args: value: The value to be used in the WHERE condition. Returns: The query builder that this WHERE builder links to. def EqualTo(self, value): """Sets the type of the WHERE clause as "equal to". Args: value: The value to be used in...
Sets the type of the WHERE clause as "not equal to". Args: value: The value to be used in the WHERE condition. Returns: The query builder that this WHERE builder links to. def NotEqualTo(self, value): """Sets the type of the WHERE clause as "not equal to". Args: value: The value to...
Sets the type of the WHERE clause as "greater than". Args: value: The value to be used in the WHERE condition. Returns: The query builder that this WHERE builder links to. def GreaterThan(self, value): """Sets the type of the WHERE clause as "greater than". Args: value: The value t...
Sets the type of the WHERE clause as "greater than or equal to". Args: value: The value to be used in the WHERE condition. Returns: The query builder that this WHERE builder links to. def GreaterThanOrEqualTo(self, value): """Sets the type of the WHERE clause as "greater than or equal to". ...
Sets the type of the WHERE clause as "less than". Args: value: The value to be used in the WHERE condition. Returns: The query builder that this WHERE builder links to. def LessThan(self, value): """Sets the type of the WHERE clause as "less than". Args: value: The value to be used...
Sets the type of the WHERE clause as "less than or equal to. Args: value: The value to be used in the WHERE condition. Returns: The query builder that this WHERE builder links to. def LessThanOrEqualTo(self, value): """Sets the type of the WHERE clause as "less than or equal to. Args: ...
Sets the type of the WHERE clause as "starts with". Args: value: The value to be used in the WHERE condition. Returns: The query builder that this WHERE builder links to. def StartsWith(self, value): """Sets the type of the WHERE clause as "starts with". Args: value: The value to b...
Sets the type of the WHERE clause as "starts with ignore case". Args: value: The value to be used in the WHERE condition. Returns: The query builder that this WHERE builder links to. def StartsWithIgnoreCase(self, value): """Sets the type of the WHERE clause as "starts with ignore case". ...
Sets the type of the WHERE clause as "contains". Args: value: The value to be used in the WHERE condition. Returns: The query builder that this WHERE builder links to. def Contains(self, value): """Sets the type of the WHERE clause as "contains". Args: value: The value to be used i...
Sets the type of the WHERE clause as "contains ignore case". Args: value: The value to be used in the WHERE condition. Returns: The query builder that this WHERE builder links to. def ContainsIgnoreCase(self, value): """Sets the type of the WHERE clause as "contains ignore case". Args: ...
Sets the type of the WHERE clause as "does not contain". Args: value: The value to be used in the WHERE condition. Returns: The query builder that this WHERE builder links to. def DoesNotContain(self, value): """Sets the type of the WHERE clause as "does not contain". Args: value: ...
Sets the type of the WHERE clause as "doesn not contain ignore case". Args: value: The value to be used in the WHERE condition. Returns: The query builder that this WHERE builder links to. def DoesNotContainIgnoreCase(self, value): """Sets the type of the WHERE clause as "doesn not contain ig...
Sets the type of the WHERE clause as "in". Args: *values: The values to be used in the WHERE condition. Returns: The query builder that this WHERE builder links to. def In(self, *values): """Sets the type of the WHERE clause as "in". Args: *values: The values to be used in the WHER...
Sets the type of the WHERE clause as "in". Args: *values: The values to be used in the WHERE condition. Returns: The query builder that this WHERE builder links to. def NotIn(self, *values): """Sets the type of the WHERE clause as "in". Args: *values: The values to be used in the W...