Exemple #1
0
 def hash_sample(self,sample):
     # if samples have undergone a transformation thier value
     # may not be exactly the same so make hash on samples
     # with fixed precision
     # sample = np.round(sample, self.digits)
     # I = np.where(np.abs(sample)<self.tol)[0]
     # sample[I] = 0.
     key = hash_array(sample)#,decimals=self.digits)
     return key
def get_subspace_values_using_dictionary(values,subspace_poly_indices,
                                         poly_indices_dict):
    num_qoi = values.shape[1]
    num_subspace_samples = subspace_poly_indices.shape[1]
    subspace_values = np.empty((num_subspace_samples,num_qoi),dtype=float)
    for jj in range(num_subspace_samples):
        poly_index = subspace_poly_indices[:,jj]
        # could reduce number of hash based lookups by simply storing
        # replicate of values for each subspace, to reduce data storage
        # I can simply store index into an array which stores the unique values
        key = hash_array(poly_index)
        subspace_values[jj,:] = values[poly_indices_dict[key],:]
    return subspace_values
def get_num_model_evaluations_from_samples(samples,num_config_vars):
    config_vars_dict = dict()
    num_samples = samples.shape[1]
    sample_count = []
    unique_config_vars = []
    for ii in range(num_samples):
        config_vars = samples[-num_config_vars:,ii]
        key = hash_array(config_vars)
        if key in config_vars_dict:
            sample_count[config_vars_dict[key]]+=1
        else:
            config_vars_dict[key]=len(sample_count)
            sample_count.append(1)
            unique_config_vars.append(config_vars)
    unique_config_vars = np.array(unique_config_vars).T
    sample_count = np.array(sample_count)
    I = np.argsort(sample_count)[::-1]
    sample_count = sample_count[I]
    unique_config_vars = unique_config_vars[:,I]
    return np.vstack((sample_count[np.newaxis,:], unique_config_vars))
Exemple #4
0
def compute_downward_closed_indices(num_vars, admissibility_criteria):
    indices = np.zeros((num_vars, 0), dtype=np.int64)
    active_indices = np.zeros((num_vars, 1), dtype=np.int64)
    while active_indices.size > 0:
        new_indices = []
        new_indices_set = set()
        for ii in range(active_indices.shape[1]):
            active_index = active_indices[:, ii]
            neighbour = active_index.copy()
            for dd in range(num_vars):
                neighbour[dd] += 1
                if admissibility_criteria(neighbour):
                    key = hash_array(neighbour)
                    if key not in new_indices_set:
                        new_indices.append(neighbour.copy())
                        new_indices_set.add(key)
                neighbour[dd] -= 1
        indices = np.hstack((indices, active_indices))
        active_indices = np.asarray(new_indices).T
    return indices
Exemple #5
0
def variance_pce_refinement_indicator(subspace_index,
                                      num_new_subspace_samples,
                                      adaptive_pce,
                                      normalize=True,
                                      mean_only=False):
    """
    Set pce coefficients of new subspace poly indices to zero to compute
    previous mean then set them to be non-zero
    """
    key = hash_array(subspace_index)
    ii = adaptive_pce.active_subspace_indices_dict[key]
    II = get_subspace_active_poly_array_indices(adaptive_pce, ii)
    error = np.sum(adaptive_pce.pce.coefficients[II]**2, axis=0)
    indicator = error.copy()

    if normalize:
        msg = """Attempted normalization of variance with values at first grid point close to 0.
        Possible options are:
        - Use a different sample or sampling sequence
          (if random sampling, try a different seed value)
        - Set the `normalize` option to False (see docs for: `variance_pce_refinement_indicator()`)
        """
        assert np.all(np.absolute(adaptive_pce.values[0, :]) > 1e-6), msg
        indicator /= np.absolute(adaptive_pce.values[0, :])**2

    qoi_chosen = np.argmax(indicator)
    indicator = indicator.max()

    cost_per_sample = adaptive_pce.eval_cost_function(
        subspace_index[:, np.newaxis])
    cost = cost_per_sample * num_new_subspace_samples

    # compute marginal benefit
    indicator /= cost

    return -indicator, error[qoi_chosen]
def get_sparse_grid_samples_and_weights(num_vars,level,
                                        quad_rules,
                                        growth_rules,
                                        sparse_grid_subspace_indices=None):
    """
    Compute the quadrature weights and samples of a isotropic sparse grid.

    Parameters
    ----------
    num_vars : integer
        The number of variables in (dimension of) the sparse grid
    
    level : integer
        The level of the isotropic sparse grid.

    quad_rules : callable univariate quadrature_rule(ll) or list
        Function used to compute univariate quadrature samples and weights 
        for a given level (ll). The weights and samples must be returned
        with polynomial ordering. If list then argument is list of quadrature
        rules

    growth_rules :callable growth_rules(ll) or list
        Function that returns the number of samples in the univariate
        quadrature rule of a given level (ll). If list then argument if list
        of growth rules.

    Return
    ------
    samples : np.ndarray (num_vars x num_sparse_grid_samples)
        The unique samples of the sparse grid.

    weights : np.ndarray (num_sparse_grid_samples)
        The quadrature weights of the sparse grid.
    """
    #subspace_indices = []
    #subspace_coefficients = []

    if callable(quad_rules):
        quad_rules = [quad_rules]*num_vars
        growth_rules = [growth_rules]*num_vars

    assert len(quad_rules)==len(growth_rules)
    assert len(quad_rules)==num_vars
    
    samples_1d, weights_1d = get_1d_samples_weights(
        quad_rules,growth_rules,[level]*num_vars)
    
    poly_indices_dict = dict()
    num_sparse_grid_samples = 0
    weights = []
    poly_indices = []
    sparse_grid_subspace_poly_indices_list = []
    sparse_grid_subspace_values_indices_list = []

    if sparse_grid_subspace_indices is None:
        sparse_grid_subspace_indices, smolyak_coefficients =\
            get_isotropic_sparse_grid_subspace_indices(num_vars,level)
    else:
        smolyak_coefficients= get_smolyak_coefficients(
            sparse_grid_subspace_indices)
        I = np.where(np.absolute(smolyak_coefficients)>1e-8)[0]
        smolyak_coefficients = smolyak_coefficients[I]
        sparse_grid_subspace_indices = sparse_grid_subspace_indices[:,I] 

    for ii in range(sparse_grid_subspace_indices.shape[1]):
        subspace_index = sparse_grid_subspace_indices[:,ii]
        subspace_poly_indices = get_subspace_polynomial_indices(
            subspace_index, growth_rules)
        sparse_grid_subspace_poly_indices_list.append(subspace_poly_indices)
        subspace_weights = get_subspace_weights(
                subspace_index,weights_1d)*smolyak_coefficients[ii]
        assert subspace_weights.shape[0]==subspace_poly_indices.shape[1]
        subspace_values_indices = np.empty(
            (subspace_poly_indices.shape[1]),dtype=int)
        for jj in range(subspace_poly_indices.shape[1]):
            poly_index = subspace_poly_indices[:,jj]
            key = hash_array(poly_index)
            if key in poly_indices_dict:
                weights[poly_indices_dict[key]]+=subspace_weights[jj]
                subspace_values_indices[jj]=poly_indices_dict[key]
            else:
                poly_indices.append(poly_index)
                poly_indices_dict[key] = num_sparse_grid_samples
                weights.append(subspace_weights[jj])
                subspace_values_indices[jj]=num_sparse_grid_samples
                num_sparse_grid_samples += 1
        sparse_grid_subspace_values_indices_list.append(
            subspace_values_indices)

    # get list of unique polynomial indices
    poly_indices = np.asarray(poly_indices).T
    samples = get_sparse_grid_samples(poly_indices,samples_1d)
    data_structures = [poly_indices_dict, poly_indices,
        sparse_grid_subspace_indices, np.asarray(smolyak_coefficients),\
        sparse_grid_subspace_poly_indices_list,samples_1d,weights_1d,
        sparse_grid_subspace_values_indices_list]
    # subspace_poly_indices can be recomputed but return here to save
    # computations at the expense of more memory
    return samples, np.asarray(weights), data_structures