INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Add data to the training data set of the GaussianProcess instance. Parameters ---------- X: array ( M D ) M input values of dimension D. y: array ( M ) M target values. err_y: array ( M ) or scalar float optional Non - negative values only. Error given as standard deviation ) in the M target values. If err_y is a scala...
def add_data(self, X, y, err_y=0, n=0, T=None): """Add data to the training data set of the GaussianProcess instance. Parameters ---------- X : array, (`M`, `D`) `M` input values of dimension `D`. y : array, (`M`,) `M` target values. er...
Condense duplicate points using a transformation matrix. This is useful if you have multiple non - transformed points at the same location or multiple transformed points that use the same quadrature points. Won t change the GP if all of the rows of [ X n ] are unique. Will create a transformation matrix T if necessary....
def condense_duplicates(self): """Condense duplicate points using a transformation matrix. This is useful if you have multiple non-transformed points at the same location or multiple transformed points that use the same quadrature points. Won't change the GP if ...
Remove outliers from the GP with very simplistic outlier detection. Removes points that are more than thresh * err_y away from the GP mean. Note that this is only very rough in that it ignores the uncertainty in the GP mean at any given point. But you should only be using this as a rough way of removing bad channels an...
def remove_outliers(self, thresh=3, **predict_kwargs): """Remove outliers from the GP with very simplistic outlier detection. Removes points that are more than `thresh` * `err_y` away from the GP mean. Note that this is only very rough in that it ignores the uncertainty in the G...
r Optimize the hyperparameters by maximizing the log - posterior. Leaves the: py: class: GaussianProcess instance in the optimized state. If: py: func: scipy. optimize. minimize is not available ( i. e. if your: py: mod: scipy version is older than 0. 11. 0 ) then: py: func: fmin_slsqp is used independent of what you s...
def optimize_hyperparameters(self, method='SLSQP', opt_kwargs={}, verbose=False, random_starts=None, num_proc=None, max_tries=1): r"""Optimize the hyperparameters by maximizing the log-posterior. Leaves the :py:class:`GaussianPro...
Predict the mean and covariance at the inputs Xstar. The order of the derivative is given by n. The keyword noise sets whether or not noise is included in the prediction. Parameters ---------- Xstar: array ( M D ) M test input values of dimension D. n: array ( M D ) or scalar non - negative int optional Order of deriva...
def predict(self, Xstar, n=0, noise=False, return_std=True, return_cov=False, full_output=False, return_samples=False, num_samples=1, samp_kwargs={}, return_mean_func=False, use_MCMC=False, full_MC=False, rejection_func=None, ddof=1, output_transform=None, ...
Plots the Gaussian process using the current hyperparameters. Only for num_dim < = 2. Parameters ---------- X: array - like ( M ) or ( M num_dim ) optional The values to evaluate the Gaussian process at. If None then 100 points between the minimum and maximum of the data s X are used for a univariate Gaussian process a...
def plot(self, X=None, n=0, ax=None, envelopes=[1, 3], base_alpha=0.375, return_prediction=False, return_std=True, full_output=False, plot_kwargs={}, **kwargs): """Plots the Gaussian process using the current hyperparameters. Only for num_dim <= 2. Parameters -...
Draw a sample evaluated at the given points Xstar. Note that this function draws samples from the GP given the current values for the hyperparameters ( which may be in a nonsense state if you just created the instance or called a method that performs MCMC sampling ). If you want to draw random samples from MCMC output ...
def draw_sample(self, Xstar, n=0, num_samp=1, rand_vars=None, rand_type='standard normal', diag_factor=1e3, method='cholesky', num_eig=None, mean=None, cov=None, modify_sign=None, **kwargs): """Draw a sample evaluated at the given points `Xstar`. ...
r Update the kernel s hyperparameters to the new parameters. This will call: py: meth: compute_K_L_alpha_ll to update the state accordingly. Note that if this method crashes and the hyper_deriv_handling keyword was used it may leave: py: attr: use_hyper_deriv in the wrong state. Parameters ---------- new_params:: py: c...
def update_hyperparameters(self, new_params, hyper_deriv_handling='default', exit_on_bounds=True, inf_on_error=True): r"""Update the kernel's hyperparameters to the new parameters. This will call :py:meth:`compute_K_L_alpha_ll` to update the state accordingly. Note that...
r Compute K L alpha and log - likelihood according to the first part of Algorithm 2. 1 in R&W. Computes K and the noise portion of K using: py: meth: compute_Kij computes L using: py: func: scipy. linalg. cholesky then computes alpha as L. T \\ ( L \\ y ). Only does the computation if: py: attr: K_up_to_date is False -...
def compute_K_L_alpha_ll(self): r"""Compute `K`, `L`, `alpha` and log-likelihood according to the first part of Algorithm 2.1 in R&W. Computes `K` and the noise portion of `K` using :py:meth:`compute_Kij`, computes `L` using :py:func:`scipy.linalg.cholesky`, then computes `alpha...
r Compute covariance matrix between datasets Xi and Xj. Specify the orders of derivatives at each location with the ni nj arrays. The include_noise flag is passed to the covariance kernel to indicate whether noise is to be included ( i. e. for evaluation of: math: K + \ sigma I versus: math: K_ * ). If Xj is None the s...
def compute_Kij(self, Xi, Xj, ni, nj, noise=False, hyper_deriv=None, k=None): r"""Compute covariance matrix between datasets `Xi` and `Xj`. Specify the orders of derivatives at each location with the `ni`, `nj` arrays. The `include_noise` flag is passed to the covariance kernel to ...
Compute the log likelihood over the ( free ) parameter space. Parameters ---------- bounds: 2 - tuple or list of 2 - tuples with length equal to the number of free parameters Bounds on the range to use for each of the parameters. If a single 2 - tuple is given it will be used for each of the parameters. num_pts: int or...
def compute_ll_matrix(self, bounds, num_pts): """Compute the log likelihood over the (free) parameter space. Parameters ---------- bounds : 2-tuple or list of 2-tuples with length equal to the number of free parameters Bounds on the range to use for each of the param...
Recursive helper function for compute_ll_matrix. Parameters ---------- idx: int The index of the parameter for this layer of the recursion to work on. idx == len ( num_pts ) is the base case that terminates the recursion. param_vals: List of: py: class: Array List of arrays of parameter values. Entries in the slots 0: ...
def _compute_ll_matrix(self, idx, param_vals, num_pts): """Recursive helper function for compute_ll_matrix. Parameters ---------- idx : int The index of the parameter for this layer of the recursion to work on. `idx` == len(`num_pts`) is the base case tha...
Produce samples from the posterior for the hyperparameters using MCMC. Returns the sampler created because storing it stops the GP from being pickleable. To add more samples to a previous sampler pass the sampler instance in the sampler keyword. Parameters ---------- nwalkers: int optional The number of walkers to use ...
def sample_hyperparameter_posterior(self, nwalkers=200, nsamp=500, burn=0, thin=1, num_proc=None, sampler=None, plot_posterior=False, plot_chains=False, sampler_type='ensemble', ...
Compute desired quantities from MCMC samples of the hyperparameter posterior. The return will be a list with a number of rows equal to the number of hyperparameter samples. The columns depend on the state of the boolean flags but will be some subset of ( mean stddev cov samples ) in that order. Samples will be the raw ...
def compute_from_MCMC(self, X, n=0, return_mean=True, return_std=True, return_cov=False, return_samples=False, return_mean_func=False, num_samples=1, noise=False, samp_kwargs={}, sampler=None, flat_trace=None, burn=0, ...
Compute desired quantities from MCMC samples of the hyperparameter posterior. The return will be a list with a number of rows equal to the number of hyperparameter samples. The columns will contain the covariance length scale function. Parameters ---------- X: array - like ( M ) or ( M num_dim ) The values to evaluate ...
def compute_l_from_MCMC(self, X, n=0, sampler=None, flat_trace=None, burn=0, thin=1, **kwargs): """Compute desired quantities from MCMC samples of the hyperparameter posterior. The return will be a list with a number of rows equal to the number of hyperparameter samples. The columns wil...
Make a prediction using MCMC samples. This is essentially a convenient wrapper of: py: meth: compute_from_MCMC designed to act more or less interchangeably with: py: meth: predict. Computes the mean of the GP posterior marginalized over the hyperparameters using iterated expectations. If return_std is True uses the law...
def predict_MCMC(self, X, ddof=1, full_MC=False, rejection_func=None, **kwargs): """Make a prediction using MCMC samples. This is essentially a convenient wrapper of :py:meth:`compute_from_MCMC`, designed to act more or less interchangeably with :py:meth:`predict`. Comp...
Build an argparse argument parser to parse the command line.
def build_parser(): "Build an argparse argument parser to parse the command line." parser = argparse.ArgumentParser( description="""Coursera OAuth2 client CLI. This tool helps users of the Coursera App Platform to programmatically access Coursera APIs.""", epilog="""Please file ...
Boots up the command line tool
def main(): "Boots up the command line tool" logging.captureWarnings(True) args = build_parser().parse_args() # Configure logging args.setup_logging(args) # Dispatch into the appropriate subcommand function. try: return args.func(args) except SystemExit: raise except:...
Add sponsor menu links.
def sponsor_menu( root_menu, menu="sponsors", label=_("Sponsors"), sponsors_item=_("Our sponsors"), packages_item=_("Sponsorship packages")): """Add sponsor menu links.""" root_menu.add_menu(menu, label, items=[]) for sponsor in ( Sponsor.objects.all() .order_...
this filter is going to be useful to execute an object method or get an object attribute dynamically. this method is going to take into account the atrib param can contains underscores
def objectatrib(instance, atrib): ''' this filter is going to be useful to execute an object method or get an object attribute dynamically. this method is going to take into account the atrib param can contains underscores ''' atrib = atrib.replace("__", ".") atribs = [] atribs = atrib.s...
Renders the field.
def as_widget(self, widget=None, attrs=None, only_initial=False): """ Renders the field. """ attrs = attrs or {} attrs.update(self.form.get_widget_attrs(self)) if hasattr(self.field, 'widget_css_classes'): css_classes = self.field.widget_css_classes el...
During form initialization some widgets have to be replaced by a counterpart suitable to be rendered the AngularJS way.
def convert_widgets(self): """ During form initialization, some widgets have to be replaced by a counterpart suitable to be rendered the AngularJS way. """ for field in self.base_fields.values(): try: new_widget = field.get_converted_widget() ...
Convet an epoch date to a tuple in format ( yyyy - mm - dd hh: mm: ss ) Example: 1023456427 - > ( 2002 - 06 - 07 15: 27: 07 )
def epochdate(timestamp): ''' Convet an epoch date to a tuple in format ("yyyy-mm-dd","hh:mm:ss") Example: "1023456427" -> ("2002-06-07","15:27:07") Parameters: - `timestamp`: date in epoch format ''' dt = datetime.fromtimestamp(float(timestamp)).timetuple() fecha = "{0:d}-{1:02d}-{2:0...
Analize itself looking for special information right now it returns: - Application name - Model name
def model_inspect(obj): ''' Analize itself looking for special information, right now it returns: - Application name - Model name ''' # Prepare the information object info = {} if hasattr(obj, '_meta'): info['verbose_name'] = getattr(obj._meta,...
This method is created to return the path to upload files. This path must be different from any other to avoid problems.
def upload_path(instance, filename): ''' This method is created to return the path to upload files. This path must be different from any other to avoid problems. ''' path_separator = "/" date_separator = "-" ext_separator = "." empty_string = "" # get the model name model_name = ...
for string get_FIELD_NAME_display return FIELD_NAME
def remove_getdisplay(field_name): ''' for string 'get_FIELD_NAME_display' return 'FIELD_NAME' ''' str_ini = 'get_' str_end = '_display' if str_ini == field_name[0:len(str_ini)] and str_end == field_name[(-1) * len(str_end):]: field_name = field_name[len(str_ini):(-1) * len(str_end)] ...
JSON Encoder newdfeault is a wrapper capable of encoding several kinds Usage: from codenerix. helpers import JSONEncoder_newdefault JSONEncoder_newdefault ()
def JSONEncoder_newdefault(kind=['uuid', 'datetime', 'time', 'decimal']): ''' JSON Encoder newdfeault is a wrapper capable of encoding several kinds Usage: from codenerix.helpers import JSONEncoder_newdefault JSONEncoder_newdefault() ''' JSONEncoder_olddefault = json.JSONEncoder.defa...
Update context with context_processors from settings Usage: from codenerix. helpers import context_processors_update context_processors_update ( context self. request )
def context_processors_update(context, request): ''' Update context with context_processors from settings Usage: from codenerix.helpers import context_processors_update context_processors_update(context, self.request) ''' for template in settings.TEMPLATES: for context_proces...
Appends a file with name filename_in_zip and contents of file_contents to the in - memory zip.
def append(self, filename_in_zip, file_contents): ''' Appends a file with name filename_in_zip and contents of file_contents to the in-memory zip. ''' # Set the file pointer to the end of the file self.in_memory_zip.seek(-1, io.SEEK_END) # Get a handle to the in-...
Writes the in - memory zip to a file.
def writetofile(self, filename): '''Writes the in-memory zip to a file.''' f = open(filename, "w") f.write(self.read()) f.close()
Returns the corresponding url from the sponsors images
def sponsor_image_url(sponsor, name): """Returns the corresponding url from the sponsors images""" if sponsor.files.filter(name=name).exists(): # We avoid worrying about multiple matches by always # returning the first one. return sponsor.files.filter(name=name).first().item.url retu...
returns the corresponding url from the tagged image list.
def sponsor_tagged_image(sponsor, tag): """returns the corresponding url from the tagged image list.""" if sponsor.files.filter(tag_name=tag).exists(): return sponsor.files.filter(tag_name=tag).first().tagged_file.item.url return ''
Check to see if the currently logged in user belongs to a specific group. Requires the Django authentication contrib app and middleware.
def ifusergroup(parser, token): """ Check to see if the currently logged in user belongs to a specific group. Requires the Django authentication contrib app and middleware. Usage: {% ifusergroup Admins %} ... {% endifusergroup %}, or {% ifusergroup Admins Clients Sellers %} ... {% else %} ... {%...
Gets a handle for use with other vSphere Guest API functions. The guest library handle provides a context for accessing information about the virtual machine.
def OpenHandle(self): '''Gets a handle for use with other vSphere Guest API functions. The guest library handle provides a context for accessing information about the virtual machine. Virtual machine statistics and state data are associated with a particular guest library handl...
Releases a handle acquired with VMGuestLib_OpenHandle
def CloseHandle(self): '''Releases a handle acquired with VMGuestLib_OpenHandle''' if hasattr(self, 'handle'): ret = vmGuestLib.VMGuestLib_CloseHandle(self.handle.value) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) del(self.handle)
Updates information about the virtual machine. This information is associated with the VMGuestLibHandle.
def UpdateInfo(self): '''Updates information about the virtual machine. This information is associated with the VMGuestLibHandle. VMGuestLib_UpdateInfo requires similar CPU resources to a system call and therefore can affect performance. If you are concerned about performance, ...
Retrieves the VMSessionID for the current session. Call this function after calling VMGuestLib_UpdateInfo. If VMGuestLib_UpdateInfo has never been called VMGuestLib_GetSessionId returns VMGUESTLIB_ERROR_NO_INFO.
def GetSessionId(self): '''Retrieves the VMSessionID for the current session. Call this function after calling VMGuestLib_UpdateInfo. If VMGuestLib_UpdateInfo has never been called, VMGuestLib_GetSessionId returns VMGUESTLIB_ERROR_NO_INFO.''' sid = c_void_p() ret = vmGuestL...
Retrieves the upperlimit of processor use in MHz available to the virtual machine. For information about setting the CPU limit see Limits and Reservations on page 14.
def GetCpuLimitMHz(self): '''Retrieves the upperlimit of processor use in MHz available to the virtual machine. For information about setting the CPU limit, see "Limits and Reservations" on page 14.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetCpuLimitMHz(self.handl...
Retrieves the minimum processing power in MHz reserved for the virtual machine. For information about setting a CPU reservation see Limits and Reservations on page 14.
def GetCpuReservationMHz(self): '''Retrieves the minimum processing power in MHz reserved for the virtual machine. For information about setting a CPU reservation, see "Limits and Reservations" on page 14.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetCpuReservationM...
Retrieves the number of CPU shares allocated to the virtual machine. For information about how an ESX server uses CPU shares to manage virtual machine priority see the vSphere Resource Management Guide.
def GetCpuShares(self): '''Retrieves the number of CPU shares allocated to the virtual machine. For information about how an ESX server uses CPU shares to manage virtual machine priority, see the vSphere Resource Management Guide.''' counter = c_uint() ret = vmGuestLib.VMGu...
Retrieves the number of milliseconds that the virtual machine was in a ready state ( able to transition to a run state ) but was not scheduled to run.
def GetCpuStolenMs(self): '''Retrieves the number of milliseconds that the virtual machine was in a ready state (able to transition to a run state), but was not scheduled to run.''' counter = c_uint64() ret = vmGuestLib.VMGuestLib_GetCpuStolenMs(self.handle.value, byref(counter)) ...
Retrieves the number of milliseconds during which the virtual machine has used the CPU. This value includes the time used by the guest operating system and the time used by virtualization code for tasks for this virtual machine. You can combine this value with the elapsed time ( VMGuestLib_GetElapsedMs ) to estimate th...
def GetCpuUsedMs(self): '''Retrieves the number of milliseconds during which the virtual machine has used the CPU. This value includes the time used by the guest operating system and the time used by virtualization code for tasks for this virtual machine. You can combine this va...
Retrieves the number of milliseconds that have passed in the virtual machine since it last started running on the server. The count of elapsed time restarts each time the virtual machine is powered on resumed or migrated using VMotion. This value counts milliseconds regardless of whether the virtual machine is using pr...
def GetElapsedMs(self): '''Retrieves the number of milliseconds that have passed in the virtual machine since it last started running on the server. The count of elapsed time restarts each time the virtual machine is powered on, resumed, or migrated using VMotion. This value cou...
Undocumented.
def GetHostCpuUsedMs(self): '''Undocumented.''' counter = c_uint64() ret = vmGuestLib.VMGuestLib_GetHostCpuUsedMs(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
Undocumented.
def GetHostMemKernOvhdMB(self): '''Undocumented.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetHostMemKernOvhdMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
Undocumented.
def GetHostMemMappedMB(self): '''Undocumented.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetHostMemMappedMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
Undocumented.
def GetHostMemPhysFreeMB(self): '''Undocumented.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetHostMemPhysFreeMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
Undocumented.
def GetHostMemPhysMB(self): '''Undocumented.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetHostMemPhysMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
Undocumented.
def GetHostMemSharedMB(self): '''Undocumented.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetHostMemSharedMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
Undocumented.
def GetHostMemSwappedMB(self): '''Undocumented.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetHostMemSwappedMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
Undocumented.
def GetHostMemUnmappedMB(self): '''Undocumented.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetHostMemUnmappedMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
Undocumented.
def GetHostMemUsedMB(self): '''Undocumented.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetHostMemUsedMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
Undocumented.
def GetHostNumCpuCores(self): '''Undocumented.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetHostNumCpuCores(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
Retrieves the speed of the ESX system s physical CPU in MHz.
def GetHostProcessorSpeed(self): '''Retrieves the speed of the ESX system's physical CPU in MHz.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetHostProcessorSpeed(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return co...
Retrieves the amount of memory the virtual machine is actively using its estimated working set size.
def GetMemActiveMB(self): '''Retrieves the amount of memory the virtual machine is actively using its estimated working set size.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetMemActiveMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGue...
Retrieves the amount of memory that has been reclaimed from this virtual machine by the vSphere memory balloon driver ( also referred to as the vmmemctl driver ).
def GetMemBalloonedMB(self): '''Retrieves the amount of memory that has been reclaimed from this virtual machine by the vSphere memory balloon driver (also referred to as the "vmmemctl" driver).''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetMemBalloonedMB(self.handle...
Undocumented.
def GetMemBalloonMaxMB(self): '''Undocumented.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetMemBalloonMaxMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
Undocumented.
def GetMemBalloonTargetMB(self): '''Undocumented.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetMemBalloonTargetMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
Retrieves the upper limit of memory that is available to the virtual machine. For information about setting a memory limit see Limits and Reservations on page 14.
def GetMemLimitMB(self): '''Retrieves the upper limit of memory that is available to the virtual machine. For information about setting a memory limit, see "Limits and Reservations" on page 14.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetMemLimitMB(self.handle.valu...
Undocumented.
def GetMemLLSwappedMB(self): '''Undocumented.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetMemLLSwappedMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
Retrieves the amount of memory that is allocated to the virtual machine. Memory that is ballooned swapped or has never been accessed is excluded.
def GetMemMappedMB(self): '''Retrieves the amount of memory that is allocated to the virtual machine. Memory that is ballooned, swapped, or has never been accessed is excluded.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetMemMappedMB(self.handle.value, byref(counter...
Retrieves the amount of overhead memory associated with this virtual machine that is currently consumed on the host system. Overhead memory is additional memory that is reserved for data structures required by the virtualization layer.
def GetMemOverheadMB(self): '''Retrieves the amount of "overhead" memory associated with this virtual machine that is currently consumed on the host system. Overhead memory is additional memory that is reserved for data structures required by the virtualization layer.''' ...
Retrieves the minimum amount of memory that is reserved for the virtual machine. For information about setting a memory reservation see Limits and Reservations on page 14.
def GetMemReservationMB(self): '''Retrieves the minimum amount of memory that is reserved for the virtual machine. For information about setting a memory reservation, see "Limits and Reservations" on page 14.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetMemReservati...
Retrieves the amount of physical memory associated with this virtual machine that is copy - on - write ( COW ) shared on the host.
def GetMemSharedMB(self): '''Retrieves the amount of physical memory associated with this virtual machine that is copy-on-write (COW) shared on the host.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetMemSharedMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ER...
Retrieves the estimated amount of physical memory on the host saved from copy - on - write ( COW ) shared guest physical memory.
def GetMemSharedSavedMB(self): '''Retrieves the estimated amount of physical memory on the host saved from copy-on-write (COW) shared guest physical memory.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetMemSharedSavedMB(self.handle.value, byref(counter)) if ret != VMGUE...
Retrieves the number of memory shares allocated to the virtual machine. For information about how an ESX server uses memory shares to manage virtual machine priority see the vSphere Resource Management Guide.
def GetMemShares(self): '''Retrieves the number of memory shares allocated to the virtual machine. For information about how an ESX server uses memory shares to manage virtual machine priority, see the vSphere Resource Management Guide.''' counter = c_uint() ret = vmGuestLi...
Retrieves the amount of memory that has been reclaimed from this virtual machine by transparently swapping guest memory to disk.
def GetMemSwappedMB(self): '''Retrieves the amount of memory that has been reclaimed from this virtual machine by transparently swapping guest memory to disk.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetMemSwappedMB(self.handle.value, byref(counter)) if ret != VMGUEST...
Undocumented.
def GetMemSwapTargetMB(self): '''Undocumented.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetMemSwapTargetMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
Retrieves the size of the target memory allocation for this virtual machine.
def GetMemTargetSizeMB(self): '''Retrieves the size of the target memory allocation for this virtual machine.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetMemTargetSizeMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) ...
Retrieves the estimated amount of physical host memory currently consumed for this virtual machine s physical memory.
def GetMemUsedMB(self): '''Retrieves the estimated amount of physical host memory currently consumed for this virtual machine's physical memory.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetMemUsedMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS...
Undocumented.
def GetMemZippedMB(self): '''Undocumented.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetMemZippedMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
Undocumented.
def GetMemZipSavedMB(self): '''Undocumented.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetMemZipSavedMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
Evaluate a B - M - or I - spline with the specified internal knots order and coefficients. deg boundary knots are appended at both sides of the domain. The zeroth order basis functions are modified to ensure continuity at the right - hand boundary. Note that the I - splines include the: math: i = 0 case in order to hav...
def spev(t_int, C, deg, x, cov_C=None, M_spline=False, I_spline=False, n=0): """Evaluate a B-, M- or I-spline with the specified internal knots, order and coefficients. `deg` boundary knots are appended at both sides of the domain. The zeroth order basis functions are modified to ensure continuity...
Build an argparse argument parser to parse the command line.
def parser(subparsers): "Build an argparse argument parser to parse the command line." # create the parser for the version subcommand. parser_version = subparsers.add_parser( 'version', help="Output the version of %(prog)s to the console.") parser_version.set_defaults(func=command_versi...
Find the specified Crispy FormHelper and instantiate it. Handy when you are crispyifying other apps forms.
def wafer_form_helper(context, helper_name): ''' Find the specified Crispy FormHelper and instantiate it. Handy when you are crispyifying other apps' forms. ''' request = context.request module, class_name = helper_name.rsplit('.', 1) if module not in sys.modules: __import__(module) ...
Add page menus.
def page_menus(root_menu): """Add page menus.""" for page in Page.objects.filter(include_in_menu=True): path = page.get_path() menu = path[0] if len(path) > 1 else None try: root_menu.add_item(page.name, page.get_absolute_url(), menu=menu) except MenuError as e: ...
The default destination from logging in redirect to the actual profile URL
def redirect_profile(request): ''' The default destination from logging in, redirect to the actual profile URL ''' if request.user.is_authenticated: return HttpResponseRedirect(reverse('wafer_user_profile', args=(request.user.username,))) else: ...
Returns a badge for the user s reviews of the talk
def reviewed_badge(user, talk): """Returns a badge for the user's reviews of the talk""" context = { 'reviewed': False, } review = None if user and not user.is_anonymous(): review = talk.reviews.filter(reviewer=user).first() if review: context['reviewed'] = True ...
r Warp inputs that are confined to the unit hypercube using the regularized incomplete beta function. Applies separately to each dimension designed for use with: py: class: WarpingFunction. Assumes that your inputs X lie entirely within the unit hypercube [ 0 1 ]. Note that you may experience some issues with constrain...
def beta_cdf_warp(X, d, n, *args): r"""Warp inputs that are confined to the unit hypercube using the regularized incomplete beta function. Applies separately to each dimension, designed for use with :py:class:`WarpingFunction`. Assumes that your inputs `X` lie entirely within the unit hypercub...
r Warp inputs with a linear transformation. Applies the warping.. math:: w ( x ) = \ frac { x - a } { b - a } to each dimension. If you set a = min ( X ) and b = max ( X ) then this is a convenient way to map your inputs to the unit hypercube. Parameters ---------- X: array ( M ) M inputs from dimension d. d: non - neg...
def linear_warp(X, d, n, *args): r"""Warp inputs with a linear transformation. Applies the warping .. math:: w(x) = \frac{x-a}{b-a} to each dimension. If you set `a=min(X)` and `b=max(X)` then this is a convenient way to map your inputs to the unit hypercube. ...
Evaluate the ( possibly recursive ) warping function and its derivatives. Parameters ---------- X: array ( M ) The points ( from dimension d ) to evaluate the warping function at. d: int The dimension to warp. n: int The derivative order to compute. So far only 0 and 1 are supported.
def w_func(self, X, d, n): """Evaluate the (possibly recursive) warping function and its derivatives. Parameters ---------- X : array, (`M`,) The points (from dimension `d`) to evaluate the warping function at. d : int The dimension to warp. ...
Set enforce_bounds for both of the kernels to a new value.
def enforce_bounds(self, v): """Set `enforce_bounds` for both of the kernels to a new value. """ self._enforce_bounds = v self.k.enforce_bounds = v self.w.enforce_bounds = v
Set the free parameters. Note that this bypasses enforce_bounds.
def free_params(self, value): """Set the free parameters. Note that this bypasses enforce_bounds. """ value = scipy.asarray(value, dtype=float) self.K_up_to_date = False self.k.free_params = value[:self.k.num_free_params] self.w.free_params = value[self.k.num_free_params:...
Set the ( free ) hyperparameters. Parameters ---------- new_params:: py: class: Array or other Array - like New values of the free parameters. Raises ------ ValueError If the length of new_params is not consistent with: py: attr: self. params.
def set_hyperparams(self, new_params): """Set the (free) hyperparameters. Parameters ---------- new_params : :py:class:`Array` or other Array-like New values of the free parameters. Raises ------ ValueError If the length o...
Handles GET requests and instantiates blank versions of the form and its inline formsets.
def get(self, request, *args, **kwargs): """ Handles GET requests and instantiates blank versions of the form and its inline formsets. """ # Prepare base if 'pk' in kwargs: self.object = self.get_object() else: self.object = None form_clas...
andles POST requests instantiating a form instance and its inline formsets with the passed POST variables and then checking them for validity.
def post(self, request, *args, **kwargs): """ andles POST requests, instantiating a form instance and its inline formsets with the passed POST variables and then checking them for validity. """ # Prepare base if 'pk' in kwargs: self.object = self.get_object() ...
Called if all forms are valid. Creates a Recipe instance along with associated Ingredients and Instructions and then redirects to a success page.
def form_valid(self, form, forms): """ Called if all forms are valid. Creates a Recipe instance along with associated Ingredients and Instructions and then redirects to a success page. """ if self.object: form.save() for (formobj, linkerfield) in forms: ...
Called if a form is invalid. Re - renders the context data with the data - filled forms and errors.
def form_invalid(self, form, forms, open_tabs, position_form_default): """ Called if a form is invalid. Re-renders the context data with the data-filled forms and errors. """ # return self.render_to_response( self.get_context_data( form = form, forms = forms ) ) return self.rende...
Wrapper for: py: func: fmin_slsqp to allow it to be called with: py: func: minimize - like syntax.
def wrap_fmin_slsqp(fun, guess, opt_kwargs={}): """Wrapper for :py:func:`fmin_slsqp` to allow it to be called with :py:func:`minimize`-like syntax. This is included to enable the code to run with :py:mod:`scipy` versions older than 0.11.0. Accepts `opt_kwargs` in the same format as used by :py:fun...
Implementation of the Pochhammer symbol: math: ( a ) _n which handles negative integer arguments properly. Need conditional statement because scipy s impelementation of the Pochhammer symbol is wrong for negative integer arguments. This function uses the definition from http:// functions. wolfram. com/ GammaBetaErf/ Po...
def fixed_poch(a, n): """Implementation of the Pochhammer symbol :math:`(a)_n` which handles negative integer arguments properly. Need conditional statement because scipy's impelementation of the Pochhammer symbol is wrong for negative integer arguments. This function uses the definition from h...
r Find the derivatives of: math: K_ \ nu ( y^ { 1/ 2 } ). Parameters ---------- nu: float The order of the modified Bessel function of the second kind. y: array of float The values to evaluate at. n: nonnegative int optional The order of derivative to take.
def Kn2Der(nu, y, n=0): r"""Find the derivatives of :math:`K_\nu(y^{1/2})`. Parameters ---------- nu : float The order of the modified Bessel function of the second kind. y : array of float The values to evaluate at. n : nonnegative int, optional The order of derivat...
r Computes the function: math: y^ { \ nu/ 2 } K_ { \ nu } ( y^ { 1/ 2 } ) and its derivatives. Care has been taken to handle the conditions at: math: y = 0. For n = 0 uses a direct evaluation of the expression replacing points where y = 0 with the appropriate value. For n > 0 uses a general sum expression to evaluate t...
def yn2Kn2Der(nu, y, n=0, tol=5e-4, nterms=1, nu_step=0.001): r"""Computes the function :math:`y^{\nu/2} K_{\nu}(y^{1/2})` and its derivatives. Care has been taken to handle the conditions at :math:`y=0`. For `n=0`, uses a direct evaluation of the expression, replacing points where `y=0` with ...
r Recursive evaluation of the incomplete Bell polynomial: math: B_ { n k } ( x ). Evaluates the incomplete Bell polynomial: math: B_ { n k } ( x_1 x_2 \ dots x_ { n - k + 1 } ) also known as the partial Bell polynomial or the Bell polynomial of the second kind. This polynomial is useful in the evaluation of ( the univa...
def incomplete_bell_poly(n, k, x): r"""Recursive evaluation of the incomplete Bell polynomial :math:`B_{n, k}(x)`. Evaluates the incomplete Bell polynomial :math:`B_{n, k}(x_1, x_2, \dots, x_{n-k+1})`, also known as the partial Bell polynomial or the Bell polynomial of the second kind. This polynom...
Generate the restricted growth strings for all of the partitions of an n - member set. Uses Algorithm H from page 416 of volume 4A of Knuth s The Art of Computer Programming. Returns the partitions in lexicographical order. Parameters ---------- n: scalar int non - negative Number of ( unique ) elements in the set to b...
def generate_set_partition_strings(n): """Generate the restricted growth strings for all of the partitions of an `n`-member set. Uses Algorithm H from page 416 of volume 4A of Knuth's `The Art of Computer Programming`. Returns the partitions in lexicographical order. Parameters ---------- ...
Generate all of the partitions of a set. This is a helper function that utilizes the restricted growth strings from: py: func: generate_set_partition_strings. The partitions are returned in lexicographic order. Parameters ---------- set_:: py: class: Array or other Array - like ( m ) The set to find the partitions of. ...
def generate_set_partitions(set_): """Generate all of the partitions of a set. This is a helper function that utilizes the restricted growth strings from :py:func:`generate_set_partition_strings`. The partitions are returned in lexicographic order. Parameters ---------- set_ : :py:...
Returns a copy of arr with duplicate rows removed. From Stackoverflow Find unique rows in numpy. array. Parameters ---------- arr:: py: class: Array ( m n ) The array to find the unique rows of. return_index: bool optional If True the indices of the unique rows in the array will also be returned. I. e. unique = arr [ i...
def unique_rows(arr, return_index=False, return_inverse=False): """Returns a copy of arr with duplicate rows removed. From Stackoverflow "Find unique rows in numpy.array." Parameters ---------- arr : :py:class:`Array`, (`m`, `n`) The array to find the unique rows of. return_ind...
Compute the average statistics ( mean std dev ) for the given values. Parameters ---------- vals: array - like ( M D ) Values to compute the average statistics along the specified axis of. check_nan: bool optional Whether or not to check for ( and exclude ) NaN s. Default is False ( do not attempt to handle NaN s ). ro...
def compute_stats(vals, check_nan=False, robust=False, axis=1, plot_QQ=False, bins=15, name=''): """Compute the average statistics (mean, std dev) for the given values. Parameters ---------- vals : array-like, (`M`, `D`) Values to compute the average statistics along the specified axis of. ...
Make a plot of a mean curve with uncertainty envelopes.
def univariate_envelope_plot(x, mean, std, ax=None, base_alpha=0.375, envelopes=[1, 3], lb=None, ub=None, expansion=10, **kwargs): """Make a plot of a mean curve with uncertainty envelopes. """ if ax is None: f = plt.figure() ax = f.add_subplot(1, 1, 1) elif ax == 'gca': ax = plt...
r Create summary statistics of the flattened chain of the sampler. The confidence regions are computed from the quantiles of the data. Parameters ---------- sampler:: py: class: emcee. Sampler instance or array ( n_temps n_chains n_samp n_dim ) ( n_chains n_samp n_dim ) or ( n_samp n_dim ) The sampler to summarize the ...
def summarize_sampler(sampler, weights=None, burn=0, ci=0.95, chain_mask=None): r"""Create summary statistics of the flattened chain of the sampler. The confidence regions are computed from the quantiles of the data. Parameters ---------- sampler : :py:class:`emcee.Sampler` instance or arr...
Plot the results of MCMC sampler ( posterior and chains ). Loosely based on triangle. py. Provides extensive options to format the plot. Parameters ---------- sampler:: py: class: emcee. Sampler instance or array ( n_temps n_chains n_samp n_dim ) ( n_chains n_samp n_dim ) or ( n_samp n_dim ) The sampler to plot the cha...
def plot_sampler( sampler, suptitle=None, labels=None, bins=50, plot_samples=False, plot_hist=True, plot_chains=True, burn=0, chain_mask=None, temp_idx=0, weights=None, cutoff_weight=None, cmap='gray_r', hist_color='k', chain_alpha=0.1, points=None, covs=None, colors=None, ci=[0....