Return the svd-filtered signal using only the selected mode

    Provide the indices of the modes desired
505463
def filter_svd(data, lapack_driver='gesdd', modes=[]):
    
    # Check input
    modes = np.asarray(modes,dtype=int)
    assert modes.ndim==1
    assert modes.size>=1, "No modes selected !"

    u, s, v = scplin.svd(data, full_matrices=False, compute_uv=True,
                         overwrite_a=False, check_finite=True,
                         lapack_driver=lapack_driver)
    indout = np.arange(0,s.size)
    indout = np.delete(indout, modes)

    data_in = np.dot(u[:,modes]*s[modes],v[modes,:])
    data_out = np.dot(u[:,indout]*s[indout],v[indout,:])
    return data_in, data_out
1070265
def _jordan_wigner_mode(n):
        
        a = []
        for i in range(n):
            xv = np.asarray([1] * i + [0] + [0] * (n - i - 1))
            xw = np.asarray([0] * i + [1] + [0] * (n - i - 1))
            yv = np.asarray([1] * i + [1] + [0] * (n - i - 1))
            yw = np.asarray([0] * i + [1] + [0] * (n - i - 1))
            a.append((Pauli(xv, xw), Pauli(yv, yw)))
        return a
1107735
def get_scipy_eig_vec(self):
    
    if not self.params['has_conv']:
      matrix_m = self.sess.run(self.dual_object.matrix_m)
      min_eig_vec_val, estimated_eigen_vector = eigs(matrix_m, k=1, which='SR',
                                                     tol=1E-4)
      min_eig_vec_val = np.reshape(np.real(min_eig_vec_val), [1, 1])
      return np.reshape(estimated_eigen_vector, [-1, 1]), min_eig_vec_val
    else:
      dim = self.dual_object.matrix_m_dimension
      input_vector = tf.placeholder(tf.float32, shape=(dim, 1))
      output_vector = self.dual_object.get_psd_product(input_vector)

      def np_vector_prod_fn(np_vector):
        np_vector = np.reshape(np_vector, [-1, 1])
        output_np_vector = self.sess.run(output_vector, feed_dict={input_vector:np_vector})
        return output_np_vector
      linear_operator = LinearOperator((dim, dim), matvec=np_vector_prod_fn)
      # Performing shift invert scipy operation when eig val estimate is available
      min_eig_vec_val, estimated_eigen_vector = eigs(linear_operator,
                                                     k=1, which='SR', tol=1E-4)
      min_eig_vec_val = np.reshape(np.real(min_eig_vec_val), [1, 1])
      return np.reshape(estimated_eigen_vector, [-1, 1]), min_eig_vec_val
403428
def bandpass_filter(rate=None, low=None, high=None, order=None):
    """"""
    assert low < high
    assert order >= 1
    return signal.butter(order,
                         (low / (rate / 2.), high / (rate / 2.)),
                         'pass')
509553
def ecuc_extract_signal(signal_node, ns):
    # type: (_Element, str) -> canmatrix.Signal
    """"""
    attributes = signal_node.findall(".//" + ns + "DEFINITION-REF")  # type: typing.Sequence[_Element]
    start_bit = None
    size = 0
    is_little = False
    # endianness = None
    # init_value = 0
    # signal_type = None
    # timeout = 0
    for attribute in attributes:
        if attribute.text.endswith("ComBitPosition"):
            start_bit = int(attribute.getparent().find(".//" + ns + "VALUE").text)
        if attribute.text.endswith("ComBitSize"):
            size = int(attribute.getparent().find(".//" + ns + "VALUE").text)
        if attribute.text.endswith("ComSignalEndianness"):
            endianness = attribute.getparent().find(".//" + ns + "VALUE").text
            is_little = "LITTLE_ENDIAN" in endianness
        if attribute.text.endswith("ComSignalInitValue"):
            init_value = int(attribute.getparent().find(".//" + ns + "VALUE").text)
        if attribute.text.endswith("ComSignalType"):
            signal_type = attribute.getparent().find(".//" + ns + "VALUE").text
        if attribute.text.endswith("ComTimeout"):
            timeout = int(attribute.getparent().find(".//" + ns + "VALUE").text)
    return canmatrix.Signal(get_element_name(signal_node, ns), start_bit=start_bit, size=size, is_little_endian=is_little)
914848
def svd(self):
        
        try:
            svdPath = self._info.debugs[0].attrib['svd']
            return self._pack.get_file(svdPath)
        except (KeyError, IndexError):
            return None
408799
def tf_min_eig_vec(self):
    """"""
    # Full eigen decomposition requires the explicit psd matrix M
    _, matrix_m = self.dual_object.get_full_psd_matrix()
    [eig_vals, eig_vectors] = tf.self_adjoint_eig(matrix_m)
    index = tf.argmin(eig_vals)
    return tf.reshape(
        eig_vectors[:, index], shape=[eig_vectors.shape[0].value, 1])
1242754
def savgol_filter(x, window_length, polyorder, deriv=0, delta=1.0, axis=-1, mode='interp', cval=0.0):
    '''
    
    '''
    # linearly interpolate missing values before filtering
    x = np.ma.masked_invalid(pd.Series(x).interpolate())

    try:
        # start filtering from the first non-zero value since these won't be addressed by
        # the interpolation above
        ind = np.isfinite(x).nonzero()[0][0]
        x[ind:] = signal.savgol_filter(x[ind:], window_length, polyorder, deriv,
                                       delta, axis, mode, cval)
    except IndexError:
        pass
    return np.ma.masked_invalid(x)
36256
def get_spectral_index(src, egy):
    """"""
    delta = 1E-5
    f0 = src.spectrum()(pyLike.dArg(egy * (1 - delta)))
    f1 = src.spectrum()(pyLike.dArg(egy * (1 + delta)))

    if f0 > 0 and f1 > 0:
        gamma = np.log10(f0 / f1) / np.log10((1 - delta) / (1 + delta))
    else:
        gamma = np.nan

    return gamma
46975
def psd(ts, nperseg=1500, noverlap=1200, plot=True):
    """"""
    ts = ts.squeeze()
    if ts.ndim is 1:
        ts = ts.reshape((-1, 1))
    fs = (len(ts) - 1.0) / (ts.tspan[-1] - ts.tspan[0])
    window = signal.hamming(nperseg, sym=False)
    nfft = max(256, 2**np.int(np.log2(nperseg) + 1))
    freqs, pxx = signal.welch(ts, fs, window, nperseg, noverlap, nfft,
                              detrend='linear', axis=0)
    # Discard estimates for freq bins that are too low for the window size.
    # (require two full cycles to fit within the window)
    index = np.nonzero(freqs >= 2.0*fs/nperseg)[0][0]
    if index > 0:
        freqs = freqs[index:]
        pxx = pxx[index:]
    # Discard estimate for last freq bin as too high for Nyquist frequency:
    freqs = freqs[:-1]
    pxx = pxx[:-1]
    if plot is True:
        _plot_psd(ts, freqs, pxx)
    return freqs, pxx
243955
def filter_indices(self, options, verbosity, *args, **kwargs):
        """"""
        index_name_map = {
            index.__class__.__name__: index
            for index in index_builder.indexes
        }

        # Process includes.
        if options['index']:
            indices = set(options['index'])
        else:
            indices = set(index_name_map.keys())

        # Process excludes.
        for index_name in options['exclude']:
            if index_name not in index_name_map:
                self.invalid_index(index_name)
                return

            indices.discard(index_name)

        # Execute action for each remaining index.
        for index_name in indices:
            try:
                index = index_name_map[index_name]
            except KeyError:
                self.invalid_index(index_name)
                return

            if verbosity > 0:
                self.stdout.write("Processing index '{}'...".format(index_name))
            self.handle_index(index, *args, **kwargs)
305581
def get_layer_timing_signal_sinusoid_1d(channels, layer, num_layers):
  

  signal = get_timing_signal_1d(num_layers, channels)
  layer_signal = tf.expand_dims(signal[:, layer, :], axis=1)

  return layer_signal
1100434
def FibreMode(gridSize,modeDiameter):
    
    rmode=modeDiameter/2
    return np.exp(-(RadiusGrid(gridSize)/rmode)**2)/(np.sqrt(np.pi/2)*rmode)
956023
def _call(self, x):
        """"""

        # Convert to array with most
        arr = self._asarray(x)
        svd_diag = np.linalg.svd(arr, compute_uv=False)

        # Rotate the axes so the svd-direction is first
        s_reordered = moveaxis(svd_diag, -1, 0)

        # Return nuclear norm
        return self.outernorm(self.pwisenorm(s_reordered))
413490
def mode(series):
    
    if series.notnull().sum() == 0:
        return np.nan
    else:
        return series.value_counts().idxmax()
54959
def susvd(x, x_obs, rho, penalties):
    

    assert type(x) == Tensor, "Input array must be a Tensor"

    while True:

        # proximal operator for the Fro. norm
        x = squared_error(x, rho, x_obs)

        # sequential singular value thresholding
        for ix, penalty in enumerate(penalties):
            x = x.unfold(ix).svt(penalty / rho).fold()

        yield x
23366
def get_mode(self, old_mode=None):
        
        if self.mode is not None:
            return self.mode
        assert self.can_write, "This format does not have a supported output mode."
        if old_mode is None:
            return self.output_modes[0]
        if old_mode in self.output_modes:
            return old_mode
        # now let's get best mode available from supported
        try:
            idx = PILLOW_MODES.index(old_mode)
        except ValueError:
            # maybe some unknown or uncommon mode
            return self.output_modes[0]
        for mode in PILLOW_MODES[idx+1:]:
            if mode in self.output_modes:
                return mode
        # since there is no better one, lets' look for closest one in opposite direction
        opposite = PILLOW_MODES[:idx]
        opposite.reverse()
        for mode in opposite:
            if mode in self.output_modes:
                return mode