Generate symbolic graph for adversarial examples and return.

    :param x: The model's symbolic inputs.
    :param kwargs: See `parse_params`
358759
def generate(self, x, **kwargs):
    
    # Parse and save attack-specific parameters
    assert self.parse_params(**kwargs)

    if self.symbolic_impl:
      # Create random targets if y_target not provided
      if self.y_target is None:
        from random import randint

        def random_targets(gt):
          result = gt.copy()
          nb_s = gt.shape[0]
          nb_classes = gt.shape[1]

          for i in range(nb_s):
            result[i, :] = np.roll(result[i, :],
                                   randint(1, nb_classes - 1))

          return result

        labels, nb_classes = self.get_or_guess_labels(x, kwargs)
        self.y_target = tf.py_func(random_targets, [labels],
                                   self.tf_dtype)
        self.y_target.set_shape([None, nb_classes])

      x_adv = jsma_symbolic(
          x,
          model=self.model,
          y_target=self.y_target,
          theta=self.theta,
          gamma=self.gamma,
          clip_min=self.clip_min,
          clip_max=self.clip_max)
    else:
      raise NotImplementedError("The jsma_batch function has been removed."
                                " The symbolic_impl argument to SaliencyMapMethod will be removed"
                                " on 2019-07-18 or after. Any code that depends on the non-symbolic"
                                " implementation of the JSMA should be revised. Consider using"
                                " SaliencyMapMethod.generate_np() instead.")

    return x_adv
362295
def get_input_nodes(G: nx.DiGraph) -> List[str]:
    
    return [n for n, d in G.in_degree() if d == 0]
199001
def gradients_X(self, dL_dK, X, X2, target):
        """"""
        if X2==None or X2 is X:
            dL_dKdiag = dL_dK.flat[::dL_dK.shape[0]+1]
            self.dKdiag_dX(dL_dKdiag, X, target)
518611
def generate(self, x, **kwargs):
    
    assert self.sess is not None, \
        'Cannot use `generate` when no `sess` was provided'
    self.parse_params(**kwargs)

    if self.y_target is None:
      self.y_target, nb_classes = self.get_or_guess_labels(x, kwargs)
      self.targeted_attack = False
    else:
      _, nb_classes = self.get_or_guess_labels(x, kwargs)
      self.targeted_attack = True

    attack = LBFGS_impl(
        self.sess, x, self.model.get_logits(x),
        self.y_target, self.targeted_attack,
        self.binary_search_steps, self.max_iterations, self.initial_const,
        self.clip_min, self.clip_max, nb_classes, self.batch_size)

    def lbfgs_wrap(x_val, y_val):
      """
      Wrapper creating TensorFlow interface for use with py_func
      """
      return np.array(attack.attack(x_val, y_val), dtype=self.np_dtype)

    wrap = tf.py_func(lbfgs_wrap, [x, self.y_target], self.tf_dtype)
    wrap.set_shape(x.get_shape())

    return wrap
1224812
def fprop(self, x):
    
    logits = tf.py_func(self.fprop_np, [x], tf.float32)
    return {self.O_LOGITS: logits}
812034
def transform(self, X):
        
        assert np.shape(X)[0] == len(self._weights), (
            'BlendingOptimizer: Number of models to blend its predictions and weights does not match: '
            'n_models={}, weights_len={}'.format(np.shape(X)[0], len(self._weights)))
        blended_predictions = np.average(np.power(X, self._power),
                                         weights=self._weights,
                                         axis=0) ** (1.0 / self._power)

        return {'y_pred': blended_predictions}
1254357
def convert_argmax(node, **kwargs):
    
    name, input_nodes, attrs = get_inputs(node, kwargs)

    axis = int(attrs.get("axis"))
    keepdims = get_boolean_attribute_value(attrs, "keepdims")

    node = onnx.helper.make_node(
        'ArgMax',
        inputs=input_nodes,
        axis=axis,
        keepdims=keepdims,
        outputs=[name],
        name=name
    )
    return [node]
1106800
def derivatives(self, **kwargs):
        
        # Call parent method
        super(CurveEvaluator2, self).derivatives(**kwargs)

        param = kwargs.get('parameter')
        deriv_order = kwargs.get('deriv_order', 0)
        degree = kwargs.get('degree')
        knotvector = kwargs.get('knotvector')
        ctrlpts = kwargs.get('ctrlpts')
        dimension = kwargs.get('dimension')

        # Algorithm A3.4
        du = min(degree, deriv_order)

        CK = [[0.0 for _ in range(dimension)] for _ in range(deriv_order + 1)]

        span = self._span_func(degree, knotvector, len(ctrlpts), param)
        bfuns = helpers.basis_function_all(degree, tuple(knotvector), span, param)

        # "derivatives_ctrlpts" is a static method that could be called like below
        PK = CurveEvaluator2.derivatives_ctrlpts(r1=(span - degree), r2=span,
                                                 degree=degree,
                                                 knotvector=knotvector,
                                                 ctrlpts=ctrlpts,
                                                 dimension=dimension,
                                                 deriv_order=du)

        for k in range(0, du + 1):
            for j in range(0, degree - k + 1):
                CK[k][:] = [elem + (bfuns[j][degree - k] * drv_ctl_p) for elem, drv_ctl_p in
                            zip(CK[k], PK[k][j])]

        # Return the derivatives
        return CK
1000671
def fn_x(i, dfs_data):
    """"""
    try:
        return R(i, dfs_data)['x']
    except Exception as e:
        # Page 17 states that if Ri is empty, then we take xi to be n
        return dfs_data['graph'].num_nodes()
1277252
def generate(self, x, **kwargs):
    
    assert self.sess is not None, \
        'Cannot use `generate` when no `sess` was provided'
    from cleverhans.utils_tf import jacobian_graph

    # Parse and save attack-specific parameters
    assert self.parse_params(**kwargs)

    # Define graph wrt to this input placeholder
    logits = self.model.get_logits(x)
    self.nb_classes = logits.get_shape().as_list()[-1]
    assert self.nb_candidate <= self.nb_classes, \
        'nb_candidate should not be greater than nb_classes'
    preds = tf.reshape(
        tf.nn.top_k(logits, k=self.nb_candidate)[0],
        [-1, self.nb_candidate])
    # grads will be the shape [batch_size, nb_candidate, image_size]
    grads = tf.stack(jacobian_graph(preds, x, self.nb_candidate), axis=1)

    # Define graph
    def deepfool_wrap(x_val):
      """deepfool function for py_func"""
      return deepfool_batch(self.sess, x, preds, logits, grads, x_val,
                            self.nb_candidate, self.overshoot,
                            self.max_iter, self.clip_min, self.clip_max,
                            self.nb_classes)

    wrap = tf.py_func(deepfool_wrap, [x], self.tf_dtype)
    wrap.set_shape(x.get_shape())
    return wrap
286887
def infer_x(self, y, sigma=None, k=None, **kwargs):
        
        assert len(y) == self.fmodel.dim_y, "Wrong dimension for y. Expected %i, got %i" % (self.fmodel.dim_y, len(y))
        k = k or self.k
        sigma = sigma or self.sigma
        x_guess = self._guess_x(y, k = k)[0]
        dists, index = self.fmodel.dataset.nn_x(x_guess, k = k)
        w = self._weights(index, dists, sigma*sigma,  y)
        return [np.sum([wi*self.fmodel.dataset.get_x(idx)
                for wi, idx in zip(w, index)], axis = 0)]
656058
def plot(self, xmin, xmax, idx_input=0, idx_output=0, points=100,
             **kwargs) -> None:
        
        for toy, ann_ in self:
            ann_.plot(xmin, xmax,
                      idx_input=idx_input, idx_output=idx_output,
                      points=points,
                      label=str(toy),
                      **kwargs)
        pyplot.legend()
983577
def _get_named_graph(context):
    
    if context is None:
        return None

    return models.NamedGraph.objects.get_or_create(identifier=context.identifier)[0]
1326020
def get_model_parser(top_rule, comments_model, **kwargs):
    

    class TextXModelParser(Parser):
        """
        Parser created from textual textX language description.
        Semantic actions for this parser will construct object
        graph representing model on the given language.
        """

        def __init__(self, *args, **kwargs):
            super(TextXModelParser, self).__init__(*args, **kwargs)

            # By default first rule is starting rule
            # and must be followed by the EOF
            self.parser_model = Sequence(
                nodes=[top_rule, EOF()], rule_name='Model', root=True)
            self.comments_model = comments_model

            # Stack for metaclass instances
            self._inst_stack = []

            # Dict for cross-ref resolving
            # { id(class): { obj.name: obj}}
            self._instances = {}

            # List to keep track of all cross-ref that need to be resolved
            # Contained elements are tuples: (instance, metaattr, cross-ref)
            self._crossrefs = []

        def clone(self):
            """
            Responsibility: create a clone in order to parse a separate file.
            It must be possible that more than one clone exist in parallel,
            without being influenced by other parser clones.

            Returns:
                A clone of this parser
            """
            import copy
            the_clone = copy.copy(self)  # shallow copy

            # create new objects for parse-dependent data
            the_clone._inst_stack = []
            the_clone._instances = {}
            the_clone._crossrefs = []

            # TODO self.memoization = memoization
            the_clone.comments = []
            the_clone.comment_positions = {}
            the_clone.sem_actions = {}

            return the_clone

        def _parse(self):
            try:
                return self.parser_model.parse(self)
            except NoMatch as e:
                line, col = e.parser.pos_to_linecol(e.position)
                raise TextXSyntaxError(message=text(e),
                                       line=line,
                                       col=col,
                                       expected_rules=e.rules)

        def get_model_from_file(self, file_name, encoding, debug,
                                pre_ref_resolution_callback=None,
                                is_main_model=True):
            """
            Creates model from the parse tree from the previous parse call.
            If file_name is given file will be parsed before model
            construction.
            """
            with codecs.open(file_name, 'r', encoding) as f:
                model_str = f.read()

            model = self.get_model_from_str(
                model_str, file_name=file_name, debug=debug,
                pre_ref_resolution_callback=pre_ref_resolution_callback,
                is_main_model=is_main_model, encoding=encoding)

            return model

        def get_model_from_str(self, model_str, file_name=None, debug=None,
                               pre_ref_resolution_callback=None,
                               is_main_model=True, encoding='utf-8'):
            """
            Parses given string and creates model object graph.
            """
            old_debug_state = self.debug

            try:
                if debug is not None:
                    self.debug = debug

                if self.debug:
                    self.dprint("*** PARSING MODEL ***")

                self.parse(model_str, file_name=file_name)
                # Transform parse tree to model. Skip root node which
                # represents the whole file ending in EOF.
                model = parse_tree_to_objgraph(
                    self, self.parse_tree[0], file_name=file_name,
                    pre_ref_resolution_callback=pre_ref_resolution_callback,
                    is_main_model=is_main_model, encoding=encoding)
            finally:
                if debug is not None:
                    self.debug = old_debug_state

            try:
                model._tx_metamodel = self.metamodel
            except AttributeError:
                # model is some primitive python type (e.g. str)
                pass
            return model

    return TextXModelParser(**kwargs)
674737
def ai(x, context=None):
    
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_ai,
        (BigFloat._implicit_convert(x),),
        context,
    )
538070
def bind_graph(graph=None):
    
    if graph is None:
        graph = Graph()
    for prefix, ns in GRAPH_BINDINGS.items():
        graph.bind(prefix, ns, True)
    return graph
465296
def jacobian_graph(predictions, x, nb_classes):
  

  # This function will return a list of TF gradients
  list_derivatives = []

  # Define the TF graph elements to compute our derivatives for each class
  for class_ind in xrange(nb_classes):
    derivatives, = tf.gradients(predictions[:, class_ind], x)
    list_derivatives.append(derivatives)

  return list_derivatives