Return example functions in the space.

        Example functions include:

        Zero
        One
        Heaviside function
        Hypercube characteristic function
        Hypersphere characteristic function
        Gaussian
        Linear gradients
552411
def examples(self):
        
        # TODO: adapt for tensor-valued functions

        # Get the points and calculate some statistics on them
        mins = self.domain.min()
        maxs = self.domain.max()
        means = (maxs + mins) / 2.0
        stds = (maxs - mins) / 4.0
        ndim = getattr(self.domain, 'ndim', 0)

        # Zero and One
        yield ('Zero', self.zero())
        yield ('One', self.one())

        # Indicator function in first dimension
        def step_fun(x):
            return (x[0] > means[0])

        yield ('Step', self.element(step_fun))

        # Indicator function on hypercube
        def cube_fun(x):
            result = True
            for points, mean, std in zip(x, means, stds):
                result = np.logical_and(result, points < mean + std)
                result = np.logical_and(result, points > mean - std)
            return result

        yield ('Cube', self.element(cube_fun))

        # Indicator function on a ball
        if ndim > 1:  # Only if ndim > 1, don't duplicate cube
            def ball_fun(x):
                r = sum((xi - mean) ** 2 / std ** 2
                        for xi, mean, std in zip(x, means, stds))
                return r < 1.0

            yield ('Ball', self.element(ball_fun))

        # Gaussian function
        def gaussian_fun(x):
            r2 = sum((xi - mean) ** 2 / (2 * std ** 2)
                     for xi, mean, std in zip(x, means, stds))
            return np.exp(-r2)

        yield ('Gaussian', self.element(gaussian_fun))

        # Gradient in each dimensions
        for axis in range(ndim):
            def gradient_fun(x):
                return (x[axis] - mins[axis]) / (maxs[axis] - mins[axis])

            yield ('Grad {}'.format(axis), self.element(gradient_fun))

        # Gradient in all dimensions
        if ndim > 1:  # Only if ndim > 1, don't duplicate grad 0
            def all_gradient_fun(x):
                return sum((xi - xmin) / (xmax - xmin)
                           for xi, xmin, xmax in zip(x, mins, maxs))

            yield ('Grad all', self.element(all_gradient_fun))
186604
function getUniformSetter( type, location, gl, context ){
  switch( type ){
    case gl.FLOAT_MAT2  :
    case gl.FLOAT_MAT3  :
    case gl.FLOAT_MAT4  :
      return getMatrixSetFunction( type, location, gl, context );

    case gl.SAMPLER_2D  :
    case gl.SAMPLER_CUBE:
    case 0x8B62 : //gl.SAMPLER_2D_SHADOW:
    case 0x8B5F : //gl.SAMPLER_3D:
      return getSamplerSetFunction( type, location, gl, context );

    default  :
      return getUniformSetFunction( type, location, gl, context );
  }
}
154787
def sample_function(self, f, N):
        
        x = self.interpolation_points(N+1)
        return f(x)
1120514
def p_example_field(self, p):
        """"""
        if p[3] is NullToken:
            p[0] = AstExampleField(
                self.path, p.lineno(1), p.lexpos(1), p[1], None)
        else:
            p[0] = AstExampleField(
                self.path, p.lineno(1), p.lexpos(1), p[1], p[3])
182016
def _list_like_func(self, func, axis, *args, **kwargs):
        
        func_prepared = self._prepare_method(
            lambda df: pandas.DataFrame(df.apply(func, axis, *args, **kwargs))
        )
        new_data = self._map_across_full_axis(axis, func_prepared)
        # When the function is list-like, the function names become the index/columns
        new_index = (
            [f if isinstance(f, string_types) else f.__name__ for f in func]
            if axis == 0
            else self.index
        )
        new_columns = (
            [f if isinstance(f, string_types) else f.__name__ for f in func]
            if axis == 1
            else self.columns
        )
        return self.__constructor__(new_data, new_index, new_columns)
753862
def examples(self):
        
        for name, elem in self.fspace.examples:
            yield (name, self.element(elem))
1370818
def _get_example_length(example):
  """"""
  length = tf.maximum(tf.shape(example[0])[0], tf.shape(example[1])[0])
  return length
883182
def sample_vMF(mu, kappa, num_samples):
    
    dim = len(mu)
    result = np.zeros((num_samples, dim))
    for nn in range(num_samples):
        # sample offset from center (on sphere) with spread kappa
        w = _sample_weight(kappa, dim)

        # sample a point v on the unit sphere that's orthogonal to mu
        v = _sample_orthonormal_to(mu)

        # compute new point
        result[nn, :] = v * np.sqrt(1. - w ** 2) + w * mu

    return result
1089058
def example():
    ''''''

    # 1a8d is an example from the loops benchmark
    # 1lfa contains hydrogens
    b = Bonsai.retrieve('1lfa', cache_dir='/tmp')
    search_radius = 10.0

    atom_of_interest = b.get_atom(1095)
    nearby_atoms = b.find_atoms_near_atom(atom_of_interest, search_radius)
    for na in nearby_atoms:
        assert(na - atom_of_interest <= search_radius)
    for fa in b.get_atom_set_complement(nearby_atoms):
        assert(fa - atom_of_interest > search_radius)

    # Get all heavy atoms within the radius (including HETATM)
    nearby_heavy_atoms = b.find_heavy_atoms_near_atom(atom_of_interest, search_radius)

    # Get all C-alpha atoms within the radius
    nearby_ca_atoms = b.find_atoms_near_atom(atom_of_interest, search_radius, atom_names_to_include = ['CA'])

    # Get all carbon atoms within the radius
    nearby_c_atoms = b.find_atoms_near_atom(atom_of_interest, search_radius, atom_names_to_include = b.get_atom_names_by_group(['C']))
688424
def get_functions(self):
        
        if isinstance(self.model, BayesianModel):
            cpds = self.model.get_cpds()
            cpds.sort(key=lambda x: x.variable)
            variables = sorted(self.domain.items(), key=lambda x: (x[1], x[0]))
            functions = []
            for cpd in cpds:
                child_var = cpd.variable
                evidence = cpd.variables[:0:-1]
                function = [str(variables.index((var, self.domain[var]))) for var in evidence]
                function.append(str(variables.index((child_var, self.domain[child_var]))))
                functions.append(function)
            return functions
        elif isinstance(self.model, MarkovModel):
            factors = self.model.get_factors()
            functions = []
            variables = sorted(self.domain.items(), key=lambda x: (x[1], x[0]))
            for factor in factors:
                scope = factor.scope()
                function = [str(variables.index((var, self.domain[var]))) for var in scope]
                functions.append(function)
            return functions
        else:
            raise TypeError("Model must be an instance of Markov or Bayesian model.")
83034
def simplify_scalar(self, func=sympy.simplify):
        
        return SLH(
            self.S.simplify_scalar(func=func),
            self.L.simplify_scalar(func=func),
            self.H.simplify_scalar(func=func))
673452
def exampleSignals(std=1, dur1=1, dur2=3, dur3=0.2,
                          n1=0.5, n2=0.5, n3=2):
    '''
    
    '''
    np.random.seed(123)
    t = np.linspace(0, 10, 100)

    f0 = _flux(t, n1, dur1, std, offs=0)
    f1 = _flux(t, n2, dur2, std, offs=0)
    f2 = _flux(t, n3, dur3, std, offs=0)
    return t,f0,f1,f2
773564
def get_samples_with_constraints(self, init_points_count):
        
        samples = np.empty((0, self.space.dimensionality))

        while samples.shape[0] < init_points_count:
            domain_samples = self.get_samples_without_constraints(init_points_count)
            valid_indices = (self.space.indicator_constraints(domain_samples) == 1).flatten()
            if sum(valid_indices) > 0:
                valid_samples = domain_samples[valid_indices,:]
                samples = np.vstack((samples,valid_samples))

        return samples[0:init_points_count,:]
971332
def lib_examples(lib):
    
    d = lib_examples_dir(lib)
    if not d.exists():
        return []
    ls = d.dirs()
    ls = [x.name for x in ls]
    ls.sort()
    return ls
883429
def distance_function_match(l1, l2, thresh, dist_fn, norm_funcs=[]):
    """"""
    common = []
    # We will keep track of the global index in the source list as we
    # will successively reduce their sizes.
    l1 = list(enumerate(l1))
    l2 = list(enumerate(l2))

    # Use the distance function and threshold on hints given by normalization.
    # See _match_by_norm_func for implementation details.
    # Also wrap the list element function function to ignore the global list
    # index computed above.
    for norm_fn in norm_funcs:
        new_common, l1, l2 = _match_by_norm_func(
                l1, l2,
                lambda a: norm_fn(a[1]),
                lambda a1, a2: dist_fn(a1[1], a2[1]),
                thresh)
        # Keep only the global list index in the end result.
        common.extend((c1[0], c2[0]) for c1, c2 in new_common)

    # Take any remaining umatched entries and try to match them using the
    # Munkres algorithm.
    dist_matrix = [[dist_fn(e1, e2) for i2, e2 in l2] for i1, e1 in l1]

    # Call Munkres on connected components on the remaining bipartite graph.
    # An edge links an element from l1 with an element from l2 only if
    # the distance between the elements is less (or equal) than the theshold.
    components = BipartiteConnectedComponents()
    for l1_i in range(len(l1)):
        for l2_i in range(len(l2)):
            if dist_matrix[l1_i][l2_i] > thresh:
                continue
            components.add_edge(l1_i, l2_i)

    for l1_indices, l2_indices in components.get_connected_components():
        # Build a partial distance matrix for each connected component.
        part_l1 = [l1[i] for i in l1_indices]
        part_l2 = [l2[i] for i in l2_indices]

        part_dist_matrix = [[dist_matrix[l1_i][l2_i] for l2_i in l2_indices]
                            for l1_i in l1_indices]
        part_cmn = _match_munkres(part_l1, part_l2, part_dist_matrix, thresh)

        common.extend((c1[0], c2[0]) for c1, c2 in part_cmn)

    return common
702658
def gradient_factory(name):
    """"""

    if name == 'sin':
        def gradient(self):
            """Return the gradient operator."""
            return cos(self.domain)
    elif name == 'cos':
        def gradient(self):
            """Return the gradient operator."""
            return -sin(self.domain)
    elif name == 'tan':
        def gradient(self):
            """Return the gradient operator."""
            return 1 + square(self.domain) * self
    elif name == 'sqrt':
        def gradient(self):
            """Return the gradient operator."""
            return FunctionalQuotient(ConstantFunctional(self.domain, 0.5),
                                      self)
    elif name == 'square':
        def gradient(self):
            """Return the gradient operator."""
            return ScalingFunctional(self.domain, 2.0)
    elif name == 'log':
        def gradient(self):
            """Return the gradient operator."""
            return reciprocal(self.domain)
    elif name == 'exp':
        def gradient(self):
            """Return the gradient operator."""
            return self
    elif name == 'reciprocal':
        def gradient(self):
            """Return the gradient operator."""
            return FunctionalQuotient(ConstantFunctional(self.domain, -1.0),
                                      square(self.domain))
    elif name == 'sinh':
        def gradient(self):
            """Return the gradient operator."""
            return cosh(self.domain)
    elif name == 'cosh':
        def gradient(self):
            """Return the gradient operator."""
            return sinh(self.domain)
    else:
        # Fallback to default
        gradient = Functional.gradient

    return gradient
324877
def gradient(self):
        
        functional = self

        if self.exponent == 1:
            class L1Gradient(Operator):

                """The gradient operator of this functional."""

                def __init__(self):
                    """Initialize a new instance."""
                    super(L1Gradient, self).__init__(
                        functional.domain, functional.domain, linear=False)

                def _call(self, x):
                    """Apply the gradient operator to the given point."""
                    return x.ufuncs.sign()

                def derivative(self, x):
                    """Derivative is a.e. zero."""
                    return ZeroOperator(self.domain)

            return L1Gradient()

        elif self.exponent == 2:
            class L2Gradient(Operator):

                """The gradient operator of this functional."""

                def __init__(self):
                    """Initialize a new instance."""
                    super(L2Gradient, self).__init__(
                        functional.domain, functional.domain, linear=False)

                def _call(self, x):
                    """Apply the gradient operator to the given point.

                    The gradient is not defined in 0.
                    """
                    norm_of_x = x.norm()
                    if norm_of_x == 0:
                        return self.domain.zero()
                    else:
                        return x / norm_of_x

            return L2Gradient()

        else:
            raise NotImplementedError('`gradient` only implemented for p=1 '
                                      'and p=2')