Check that the convolution mode is consistent with the padding specification
505525
public static void validateConvolutionModePadding(ConvolutionMode mode, int padding) {
        if (mode == ConvolutionMode.Same) {
            boolean nullPadding = true;
            if (padding != 0) nullPadding = false;
            if (!nullPadding)
                throw new IllegalArgumentException("Padding cannot be used when using the `same' convolution mode");

        }
    }
1076689
function conv2(image, kernel) {
    var out = new Float64Array( height * width  )
    var acc = 0
    , row, col, i, j, k
    for ( row = 0; row < height; row++ ) {
      for ( col = 0; col < width; col++ ) {
        for ( i = -1; i <= 1; i++ ) {
          for ( j = -1; j <= 1; j++ ) {
            if( row+i >= 0 && col+j >= 0 &&
                row+i < height && col+j < width) {
              k = image[ (row + i) * width + (col + j)]
              acc += k * kernel[ (1 + i) * 3 + (1 + j)]
            }
          }
        }
        out[ row * width + col] = acc
        acc = 0
      }
    }
    return out
  }
836242
def sepconv_relu_sepconv(inputs,
                         filter_size,
                         output_size,
                         first_kernel_size=(1, 1),
                         second_kernel_size=(1, 1),
                         padding="LEFT",
                         nonpadding_mask=None,
                         dropout=0.0,
                         name=None):
  """"""
  with tf.variable_scope(name, "sepconv_relu_sepconv", [inputs]):
    inputs = maybe_zero_out_padding(inputs, first_kernel_size, nonpadding_mask)
    if inputs.get_shape().ndims == 3:
      is_3d = True
      inputs = tf.expand_dims(inputs, 2)
    else:
      is_3d = False
    h = separable_conv(
        inputs,
        filter_size,
        first_kernel_size,
        activation=tf.nn.relu,
        padding=padding,
        name="conv1")
    if dropout != 0.0:
      h = tf.nn.dropout(h, 1.0 - dropout)
    h = maybe_zero_out_padding(h, second_kernel_size, nonpadding_mask)
    ret = separable_conv(
        h, output_size, second_kernel_size, padding=padding, name="conv2")
    if is_3d:
      ret = tf.squeeze(ret, 2)
    return ret
374979
def check_field_cohesion(self, rec_write_fields, sig_write_fields):
        
        # If there are no signal specification fields, there is nothing to check.
        if self.n_sig>0:

            # The length of all signal specification fields must match n_sig
            # even if some of its elements are None.
            for f in sig_write_fields:
                if len(getattr(self, f)) != self.n_sig:
                    raise ValueError('The length of field: '+f+' must match field n_sig.')

            # Each file_name must correspond to only one fmt, (and only one byte offset if defined).
            datfmts = {}
            for ch in range(self.n_sig):
                if self.file_name[ch] not in datfmts:
                    datfmts[self.file_name[ch]] = self.fmt[ch]
                else:
                    if datfmts[self.file_name[ch]] != self.fmt[ch]:
                        raise ValueError('Each file_name (dat file) specified must have the same fmt')

            datoffsets = {}
            if self.byte_offset is not None:
                # At least one byte offset value exists
                for ch in range(self.n_sig):
                    if self.byte_offset[ch] is None:
                        continue
                    if self.file_name[ch] not in datoffsets:
                        datoffsets[self.file_name[ch]] = self.byte_offset[ch]
                    else:
                        if datoffsets[self.file_name[ch]] != self.byte_offset[ch]:
                            raise ValueError('Each file_name (dat file) specified must have the same byte offset')
1220250
def _default_verify_function(instance, answer, result_host, atol, verbose):
    """"""

    #first check if the length is the same
    if len(instance.arguments) != len(answer):
        raise TypeError("The length of argument list and provided results do not match.")
    #for each element in the argument list, check if the types match
    for i, arg in enumerate(instance.arguments):
        if answer[i] is not None: #skip None elements in the answer list
            if isinstance(answer[i], numpy.ndarray) and isinstance(arg, numpy.ndarray):
                if answer[i].dtype != arg.dtype:
                    raise TypeError("Element " + str(i)
                                    + " of the expected results list is not of the same dtype as the kernel output: "
                                    + str(answer[i].dtype) + " != " + str(arg.dtype) + ".")
                if answer[i].size != arg.size:
                    raise TypeError("Element " + str(i)
                                    + " of the expected results list has a size different from "
                                    + "the kernel argument: "
                                    + str(answer[i].size) + " != " + str(arg.size) + ".")
            elif isinstance(answer[i], numpy.number) and isinstance(arg, numpy.number):
                if answer[i].dtype != arg.dtype:
                    raise TypeError("Element " + str(i)
                                    + " of the expected results list is not the same as the kernel output: "
                                    + str(answer[i].dtype) + " != " + str(arg.dtype) + ".")
            else:
                #either answer[i] and argument have different types or answer[i] is not a numpy type
                if not isinstance(answer[i], numpy.ndarray) or not isinstance(answer[i], numpy.number):
                    raise TypeError("Element " + str(i)
                                    + " of expected results list is not a numpy array or numpy scalar.")
                else:
                    raise TypeError("Element " + str(i)
                                    + " of expected results list and kernel arguments have different types.")

    def _ravel(a):
        if hasattr(a, 'ravel') and len(a.shape) > 1:
            return a.ravel()
        return a

    def _flatten(a):
        if hasattr(a, 'flatten'):
            return a.flatten()
        return a

    correct = True
    for i, arg in enumerate(instance.arguments):
        expected = answer[i]
        if expected is not None:

            result = _ravel(result_host[i])
            expected = _flatten(expected)
            output_test = numpy.allclose(expected, result, atol=atol)

            if not output_test and verbose:
                print("Error: " + util.get_config_string(instance.params) + " detected during correctness check")
                print("this error occured when checking value of the %oth kernel argument" % (i,))
                print("Printing kernel output and expected result, set verbose=False to suppress this debug print")
                numpy.set_printoptions(edgeitems=50)
                print("Kernel output:")
                print(result)
                print("Expected:")
                print(expected)
            correct = correct and output_test

    if not correct:
        logging.debug('correctness check has found a correctness issue')
        raise Exception("Error: " + util.get_config_string(instance.params) + " failed correctness check")

    return correct
549473
def verify(self, x):
        
        if type(x) != type(self.data):
            raise TypeError("Input expected to be of type %s, got %s." %
                            (type(self.data).__name__, type(x).__name__))
        elif isinstance(x, np.ndarray):
            if x.ndim != 2:
                raise ValueError('Streamed array data must be two-dimensional')
            elif x.shape[1] != self.data.shape[1]:
                raise ValueError("Streamed array data expeced to have %d columns, "
                                 "got %d." % (self.data.shape[1], x.shape[1]))
        elif util.pd and isinstance(x, util.pd.DataFrame) and list(x.columns) != list(self.data.columns):
            raise IndexError("Input expected to have columns %s, got %s" %
                             (list(self.data.columns), list(x.columns)))
        elif isinstance(x, dict):
            if any(c not in x for c in self.data):
                raise IndexError("Input expected to have columns %s, got %s" %
                                 (sorted(self.data.keys()), sorted(x.keys())))
            elif len(set(len(v) for v in x.values())) > 1:
                raise ValueError("Input columns expected to have the "
                                 "same number of rows.")
494842
def has_valid_padding(value, bits=7):
        """"""

        assert bits <= 8

        mask = (((1 << (8 - bits)) - 1) << bits)

        if isinstance(value, integer_types):
            while value:
                if value & mask:
                    return False
                value >>= 8
        elif isinstance(value, bytes):
            for byte in bytearray(value):
                if byte & mask:
                    return False
        else:
            raise TypeError

        return True
967466
def check(self, feature):
        """"""
        assert hasattr(feature.transformer, 'fit')
        assert hasattr(feature.transformer, 'transform')
        assert hasattr(feature.transformer, 'fit_transform')
384457
private void CheckGrayscaleImage(IfdTags metadata, int n) {
    // Bits per Sample
    long bps = metadata.get(TiffTags.getTagId("BitsPerSample")).getFirstNumericValue();
    // if (bps != 4 && bps != 8)
    if (bps < 1)
      validation.addError("Invalid Bits per Sample", "IFD" + n, bps);

    // Compression
    long comp = metadata.get(TiffTags.getTagId("Compression")).getFirstNumericValue();
    // if (comp != 1 && comp != 32773)
    if (comp < 1)
      validation.addError("Invalid Compression", "IFD" + n, comp);
  }
539438
public static void convolve(Kernel2D_S32 kernel, InterleavedS32 src, InterleavedS32 dst ) {
		InputSanityCheck.checkSameShapeB(src, dst);

		boolean processed = BOverrideConvolveImageNormalized.invokeNativeConvolve(kernel,src,dst);
		
		if( !processed ) {
			if( kernel.width >= src.width || kernel.width >= src.height ) {
				ConvolveNormalizedNaive_IL.convolve(kernel, src, dst);
			} else {
				ConvolveImageNoBorder.convolve(kernel, src, dst, kernel.computeSum());
				ConvolveNormalized_JustBorder_IL.convolve(kernel, src, dst);
			}
		}
	}
381042
def check_config(config, data):
    '''
    '''
    if 'tolerance' not in config.keys() or not config['tolerance']:
        config['tolerance'] = 1E-5

    if not config.get('maximum_iterations', None):
        config['maximum_iterations'] = 1000

    mmin_obs = np.min(data['magnitude'])
    if config.get('input_mmin', 0) < mmin_obs:
        config['input_mmin'] = mmin_obs

    if fabs(config['b-value']) < 1E-7:
        config['b-value'] = 1E-7

    return config
886794
def validate_regular_sampling(values, rtol=10e-6):
    
    diffs = np.diff(values)
    return (len(diffs) < 1) or abs(diffs.min()-diffs.max()) < abs(diffs.min()*rtol)
880520
def multi_conv_res(x, padding, name, layers, hparams, mask=None, source=None):
  """"""
  with tf.variable_scope(name):
    padding_bias = None
    if mask is not None:
      padding_bias = (1.0 - mask) * -1e9  # Bias to not attend to padding.
      if padding == "LEFT":  # Do not mask anything when left-padding.
        mask = None
    if (hparams.kernel_scheme in _KERNEL_SCHEMES and
        hparams.dilation_scheme in _DILATION_SCHEMES):
      kernels = _KERNEL_SCHEMES[hparams.kernel_scheme]
      dilations = _DILATION_SCHEMES[hparams.dilation_scheme]
      dilations_and_kernels = list(zip(dilations, kernels))
      dilations_and_kernels1 = dilations_and_kernels[:2]
      dilations_and_kernels2 = dilations_and_kernels[2:]
    else:
      k = (hparams.kernel_height, hparams.kernel_width)
      k2 = (hparams.large_kernel_size, 1)
      dilations_and_kernels1 = [((1, 1), k), ((1, 1), k)]
      dilations_and_kernels2 = [((1, 1), k2), ((4, 4), k2)]
    separabilities1 = [hparams.separability, hparams.separability]
    separabilities2 = [hparams.separability] * len(dilations_and_kernels2)
    if hparams.separability < 0:
      separabilities1 = [hparams.separability - 1, hparams.separability]
      separabilities2 = [
          hparams.separability - i
          for i in reversed(range(len(dilations_and_kernels2)))
      ]

    def norm_fn(x, name):
      with tf.variable_scope(name, default_name="norm"):
        return common_layers.apply_norm(
            x, hparams.norm_type, hparams.hidden_size, hparams.norm_epsilon)

    for layer in range(layers):
      with tf.variable_scope("layer_%d" % layer):
        y = common_layers.subseparable_conv_block(
            x,
            hparams.hidden_size,
            dilations_and_kernels1,
            normalizer_fn=norm_fn,
            padding=padding,
            mask=mask,
            separabilities=separabilities1,
            name="residual1")
        x += common_layers.subseparable_conv_block(
            x + y,
            hparams.hidden_size,
            dilations_and_kernels2,
            normalizer_fn=norm_fn,
            padding=padding,
            mask=mask,
            separabilities=separabilities2,
            name="residual2") + y
        if source is not None and hparams.attention_type != "none":
          x += attention(x, source, norm_fn, hparams, bias=padding_bias)
        if mask is not None:
          x *= mask
    return tf.nn.dropout(x, 1.0 - hparams.dropout)
191540
def conv(self,
             num_out_channels,
             k_height,
             k_width,
             d_height=1,
             d_width=1,
             mode="SAME",
             input_layer=None,
             num_channels_in=None,
             use_batch_norm=None,
             stddev=None,
             activation="relu",
             bias=0.0):
        """"""
        if input_layer is None:
            input_layer = self.top_layer
        if num_channels_in is None:
            num_channels_in = self.top_size
        kernel_initializer = None
        if stddev is not None:
            kernel_initializer = tf.truncated_normal_initializer(stddev=stddev)
        name = "conv" + str(self.counts["conv"])
        self.counts["conv"] += 1
        with tf.variable_scope(name):
            strides = [1, d_height, d_width, 1]
            if self.data_format == "NCHW":
                strides = [strides[0], strides[3], strides[1], strides[2]]
            if mode != "SAME_RESNET":
                conv = self._conv2d_impl(
                    input_layer,
                    num_channels_in,
                    num_out_channels,
                    kernel_size=[k_height, k_width],
                    strides=[d_height, d_width],
                    padding=mode,
                    kernel_initializer=kernel_initializer)
            else:  # Special padding mode for ResNet models
                if d_height == 1 and d_width == 1:
                    conv = self._conv2d_impl(
                        input_layer,
                        num_channels_in,
                        num_out_channels,
                        kernel_size=[k_height, k_width],
                        strides=[d_height, d_width],
                        padding="SAME",
                        kernel_initializer=kernel_initializer)
                else:
                    rate = 1  # Unused (for 'a trous' convolutions)
                    kernel_height_effective = k_height + (k_height - 1) * (
                        rate - 1)
                    pad_h_beg = (kernel_height_effective - 1) // 2
                    pad_h_end = kernel_height_effective - 1 - pad_h_beg
                    kernel_width_effective = k_width + (k_width - 1) * (
                        rate - 1)
                    pad_w_beg = (kernel_width_effective - 1) // 2
                    pad_w_end = kernel_width_effective - 1 - pad_w_beg
                    padding = [[0, 0], [pad_h_beg, pad_h_end],
                               [pad_w_beg, pad_w_end], [0, 0]]
                    if self.data_format == "NCHW":
                        padding = [
                            padding[0], padding[3], padding[1], padding[2]
                        ]
                    input_layer = tf.pad(input_layer, padding)
                    conv = self._conv2d_impl(
                        input_layer,
                        num_channels_in,
                        num_out_channels,
                        kernel_size=[k_height, k_width],
                        strides=[d_height, d_width],
                        padding="VALID",
                        kernel_initializer=kernel_initializer)
            if use_batch_norm is None:
                use_batch_norm = self.use_batch_norm
            if not use_batch_norm:
                if bias is not None:
                    biases = self.get_variable(
                        "biases", [num_out_channels],
                        self.variable_dtype,
                        self.dtype,
                        initializer=tf.constant_initializer(bias))
                    biased = tf.reshape(
                        tf.nn.bias_add(
                            conv, biases, data_format=self.data_format),
                        conv.get_shape())
                else:
                    biased = conv
            else:
                self.top_layer = conv
                self.top_size = num_out_channels
                biased = self.batch_norm(**self.batch_norm_config)
            if activation == "relu":
                conv1 = tf.nn.relu(biased)
            elif activation == "linear" or activation is None:
                conv1 = biased
            elif activation == "tanh":
                conv1 = tf.nn.tanh(biased)
            else:
                raise KeyError("Invalid activation type \"%s\"" % activation)
            self.top_layer = conv1
            self.top_size = num_out_channels
            return conv1
520731
def _check_input(image, init_level_set):
    """"""
    if not image.ndim in [2, 3]:
        raise ValueError("`image` must be a 2 or 3-dimensional array.")

    if len(image.shape) != len(init_level_set.shape):
        raise ValueError("The dimensions of the initial level set do not "
                         "match the dimensions of the image.")
949587
def check_sig_cohesion(self, write_fields, expanded):
        
        # Using list of arrays e_d_signal
        if expanded:
            # Set default samps_per_frame
            spf = self.samps_per_frame
            for ch in range(len(spf)):
                if spf[ch] is None:
                    spf[ch] = 1

            # Match the actual signal shape against stated length and number of channels
            if self.n_sig != len(self.e_d_signal):
                raise ValueError('n_sig does not match the length of e_d_signal')
            for ch in range(self.n_sig):
                if len(self.e_d_signal[ch]) != spf[ch]*self.sig_len:
                    raise ValueError('Length of channel '+str(ch)+'does not match samps_per_frame['+str(ch+']*sig_len'))

            # For each channel (if any), make sure the digital format has no values out of bounds
            for ch in range(self.n_sig):
                fmt = self.fmt[ch]
                dmin, dmax = _digi_bounds(self.fmt[ch])

                chmin = min(self.e_d_signal[ch])
                chmax = max(self.e_d_signal[ch])
                if (chmin < dmin) or (chmax > dmax):
                    raise IndexError("Channel "+str(ch)+" contain values outside allowed range ["+str(dmin)+", "+str(dmax)+"] for fmt "+str(fmt))

            # Ensure that the checksums and initial value fields match the digital signal (if the fields are present)
            if self.n_sig > 0:
                if 'checksum' in write_fields:
                    realchecksum = self.calc_checksum(expanded)
                    if self.checksum != realchecksum:
                        print("The actual checksum of e_d_signal is: ", realchecksum)
                        raise ValueError("checksum field does not match actual checksum of e_d_signal")
                if 'init_value' in write_fields:
                    realinit_value = [self.e_d_signal[ch][0] for ch in range(self.n_sig)]
                    if self.init_value != realinit_value:
                        print("The actual init_value of e_d_signal is: ", realinit_value)
                        raise ValueError("init_value field does not match actual init_value of e_d_signal")

        # Using uniform d_signal
        else:
            # Match the actual signal shape against stated length and number of channels
            if (self.sig_len, self.n_sig) != self.d_signal.shape:
                print('sig_len: ', self.sig_len)
                print('n_sig: ', self.n_sig)
                print('d_signal.shape: ', self.d_signal.shape)
                raise ValueError('sig_len and n_sig do not match shape of d_signal')

            # For each channel (if any), make sure the digital format has no values out of bounds
            for ch in range(self.n_sig):
                fmt = self.fmt[ch]
                dmin, dmax = _digi_bounds(self.fmt[ch])

                chmin = min(self.d_signal[:,ch])
                chmax = max(self.d_signal[:,ch])
                if (chmin < dmin) or (chmax > dmax):
                    raise IndexError("Channel "+str(ch)+" contain values outside allowed range ["+str(dmin)+", "+str(dmax)+"] for fmt "+str(fmt))

            # Ensure that the checksums and initial value fields match the digital signal (if the fields are present)
            if self.n_sig>0:
                if 'checksum' in write_fields:
                    realchecksum = self.calc_checksum()
                    if self.checksum != realchecksum:
                        print("The actual checksum of d_signal is: ", realchecksum)
                        raise ValueError("checksum field does not match actual checksum of d_signal")
                if 'init_value' in write_fields:
                    realinit_value = list(self.d_signal[0,:])
                    if self.init_value != realinit_value:
                        print("The actual init_value of d_signal is: ", realinit_value)
                        raise ValueError("init_value field does not match actual init_value of d_signal")
557128
def get_padding_value(dtype):
  """"""
  padding_value = None
  if dtype == np.uint8:
    padding_value = np.uint8(0)
  elif dtype == np.uint16:
    padding_value = np.uint16(0)
  elif dtype == np.float32:
    padding_value = 0.0
  else:
    padding_value = 0
  assert padding_value is not None
  return padding_value