text:
################################################################################
# Copyright (C) 2011-2014 Jaakko Luttinen
#
# This file is licensed under the MIT License.
################################################################################

"""
General numerical functions and methods.

"""

import itertools
import numpy as np
import scipy as sp
#import scipy.linalg.decomp_cholesky as decomp
import scipy.linalg as linalg
import scipy.special as special
import scipy.optimize as optimize
import scipy.sparse as sparse
#import scikits.sparse.cholmod as cholmod

# THIS IS SOME NEW GENERALIZED UFUNC FOR LINALG FEATURE, NOT IN OFFICIAL NUMPY
# REPO YET
#import numpy.linalg._gufuncs_linalg as gula
#import numpy.core.gufuncs_linalg as gula

from . import misc

def chol(C, ndim=1):
    if sparse.issparse(C):
        if ndim != 1:
            raise NotImplementedError()
        # Sparse Cholesky decomposition (returns a Factor object)
        return cholmod.cholesky(C)
    else:
        # Computes Cholesky decomposition for a collection of matrices.
        # The last 2*ndim axes of C are considered as the matrix.
        if ndim == 0:
            return np.sqrt(C)
        shape_original = np.shape(C)[-ndim:]
        C = (
            C if ndim == 1 else
            misc.flatten_axes(C, ndim, ndim)
        )
        if np.shape(C)[-1] != np.shape(C)[-2]:
            raise ValueError("Not square matrix w.r.t. ndim sense")
        U = np.empty(np.shape(C))
        for i in misc.nested_iterator(np.shape(U)[:-2]):
            try:
                # Handle (0, 0) matrices. See:
                # https://github.com/scipy/scipy/issues/8056
                U[i] = (
                    np.empty((0,0)) if np.size(C[i]) == 0 else
                    linalg.cho_factor(C[i])[0]
                )
            except np.linalg.linalg.LinAlgError:
                raise Exception("Matrix not positive definite")
        return (
            U if ndim == 1 else
            misc.reshape_axes(U, shape_original, shape_original)
        )

def chol_solve(U, b, out=None, matrix=False, ndim=1):
    if isinstance(U, np.ndarray) or np.isscalar(U):
        if sparse.issparse(b):
            b = b.toarray()

        if ndim == 0:
            return (b / U) / U

        shape = np.shape(U)[-ndim:]
        U = (
            U if ndim == 1 else
            misc.flatten_axes(U, ndim, ndim)
        )

        if matrix:
            shape_b = np.shape(b)[-ndim:]
            B = (
                b if ndim == 1 else
                misc.flatten_axes(b, ndim, ndim)
            )
            B = transpose(B, ndim=1)
            U = U[...,None,:,:]
        else:
            B = (
                b if ndim == 1 else
                misc.flatten_axes(b, ndim)
            )

        # Allocate memory
        sh_u = U.shape[:-2]
        sh_b = B.shape[:-1]
        l_u = len(sh_u)
        l_b = len(sh_b)

        # Check which axis are iterated over with B along with U
        ind_b = [slice(None)] * l_b
        l_min = min(l_u, l_b)
        jnd_b = tuple(i for i in range(-l_min,0) if sh_b[i]==sh_u[i])

        if out == None:
            # Shape of the result (broadcasting rules)
            sh = misc.broadcasted_shape(sh_u, sh_b)
            #out = np.zeros(np.shape(B))
            out = np.zeros(sh + B.shape[-1:])

        for i in misc.nested_iterator(np.shape(U)[:-2]):

            # The goal is to run Cholesky solver once for all vectors of B
            # for which the matrices of U are the same (according to the
            # broadcasting rules). Thus, we collect all the axes of B for
            # which U is singleton and form them as a 2-D matrix and then
            # run the solver once.

            # Select those axes of B for which U and B are not singleton
            for j in jnd_b:
                ind_b[j] = i[j]

            # Collect all the axes for which U is singleton
            b = B[tuple(ind_b) + (slice(None),)]

            # Reshape it to a 2-D (or 1-D) array
            orig_shape = b.shape
            if b.ndim > 1:
                b = b.reshape((-1, b.shape[-1]))

            # slice(None) to all preceeding axes and ellipsis for the last
            # axis:
            if len(ind_b) < len(sh):
                ind_out = (slice(None),) + tuple(ind_b) + (slice(None),)
            else:
                ind_out = tuple(ind_b) + (slice(None),)

            out[ind_out] = (
                # Handle (0, 0) matrices. See:
                # https://github.com/scipy/scipy/issues/8056
                np.empty(orig_shape) if np.size(U[i]) == 0 else
                linalg.cho_solve(
                    (U[i], False),
                    b.T
                ).T.reshape(orig_shape)
            )

        if matrix:
            out = transpose(out, ndim=1)
            out = (
                out if ndim == 1 else
                misc.reshape_axes(out, shape, shape_b)
            )
        else:
            out = (
                out if ndim == 1 else
                misc.reshape_axes(out, shape)
            )

        return out

    elif isinstance(U, cholmod.Factor):
        if ndim != 1:
            raise NotImplementedError()
        if matrix:
            raise NotImplementedError()
        if sparse.issparse(b):
            b = b.toarray()
        return U.solve_A(b)
    else:
        raise ValueError("Unknown type of Cholesky factor")

def chol_inv(U, ndim=1):
    if isinstance(U, np.ndarray) or np.isscalar(U):
        if ndim == 0:
            return (1 / U) / U
        shape = np.shape(U)[-ndim:]
        U = (
            U if ndim == 1 else
            misc.flatten_axes(U, ndim, ndim)
        )
        # Allocate memory
        V = np.tile(np.identity(np.shape(U)[-1]), np.shape(U)[:-2]+(1,1))
        for i in misc.nested_iterator(np.shape(U)[:-2]):
            V[i] = (
                # Handle (0, 0) matrices. See:
                # https://github.com/scipy/scipy/issues/8056
                np.empty((0, 0)) if np.size(V[i]) == 0 else
                linalg.cho_solve(
                    (U[i], False),
                    V[i],
                    overwrite_b=True # This would need Fortran order
                )
            )
        V = (
            V if ndim == 1 else
            misc.reshape_axes(V, shape, shape)
        )
        return V

    elif isinstance(U, cholmod.Factor):
        raise NotImplementedError
        if ndim != 1:
            raise NotImplementedError()
    else:
        raise ValueError("Unknown type of Cholesky factor")

def chol_logdet(U, ndim=1):
    if isinstance(U, np.ndarray) or np.isscalar(U):
        if ndim == 0:
            return 2 * np.log(U)
        U = (
            U if ndim == 1 else
            misc.flatten_axes(U, ndim, ndim)
        )
        return 2*np.sum(np.log(np.einsum('...ii->...i',U)), axis=-1)
    elif isinstance(U, cholmod.Factor):
        if ndim != 1:
            raise NotImplementedError()
        return np.sum(np.log(U.D()))
    else:
        raise ValueError("Unknown type of Cholesky factor")

def logdet_chol(U):
    if isinstance(U, np.ndarray):
        # Computes Cholesky decomposition for a collection of matrices.
        return 2*np.sum(np.log(np.einsum('...ii->...i', U)), axis=(-1,))
    elif isinstance(U, cholmod.Factor):
        return np.sum(np.log(U.D()))

def logdet_tri(R):
    """
    Logarithm of the absolute value of the determinant of a triangular matrix.
    """
    return np.sum(np.log(np.abs(np.einsum('...ii->...i', R))))

def logdet_cov(C, ndim=1):
    return chol_logdet(chol(C, ndim=ndim), ndim=ndim)

def solve_triangular(U, B, ndim=1, **kwargs):
    if ndim != 1:
        raise NotImplementedError("Not yet implemented for ndim!=1")
    # Allocate memory
    U = np.atleast_2d(U)
    B = np.atleast_1d(B)
    sh_u = U.shape[:-2]
    sh_b = B.shape[:-1]
    l_u = len(sh_u)
    l_b = len(sh_b)

    # Check which axis are iterated over with B along with U
    ind_b = [slice(None)] * l_b
    l_min = min(l_u, l_b)
    jnd_b = tuple(i for i in range(-l_min,0) if sh_b[i]==sh_u[i])

    # Shape of the result (broadcasting rules)
    sh = misc.broadcasted_shape(sh_u, sh_b)
    out = np.zeros(sh + B.shape[-1:])
    for i in misc.nested_iterator(np.shape(U)[:-2]):

        # The goal is to run triangular solver once for all vectors of
        # B for which the matrices of U are the same (according to the
        # broadcasting rules). Thus, we collect all the axes of B for
        # which U is singleton and form them as a 2-D matrix and then
        # run the solver once.

        # Select those axes of B for which U and B are not singleton
        for j in jnd_b:
            ind_b[j] = i[j]

        # Collect all the axes for which U is singleton
        b = B[tuple(ind_b) + (slice(None),)]

        # Reshape it to a 2-D (or 1-D) array
        orig_shape = b.shape
        if b.ndim > 1:
            b = b.reshape((-1, b.shape[-1]))

        # slice(None) to all preceeding axes and ellipsis for the last
        # axis:
        if len(ind_b) < len(sh):
            ind_out = (slice(None),) + tuple(ind_b) + (slice(None),)
        else:
            ind_out = tuple(ind_b) + (slice(None),)

        out[ind_out] = linalg.solve_triangular(U[i],
                                               b.T,
                                               **kwargs).T.reshape(orig_shape)

    return out

def inner(*args, ndim=1):
    """
    Compute inner product.

    The number of arrays is arbitrary.  The number of dimensions is arbitrary.
    """
    axes = tuple(range(-ndim,0))
    return misc.sum_product(*args, axes_to_sum=axes)

def outer(A, B, ndim=1):
    """
    Computes outer product over the last axes of A and B.

    The other axes are broadcasted. Thus, if A has shape (..., N) and B has
    shape (..., M), then the result has shape (..., N, M).

    Using the argument `ndim` it is possible to change that how many axes
    trailing axes are used for the outer product. For instance, if ndim=3, A and
    B have shapes (...,N1,N2,N3) and (...,M1,M2,M3), the result has shape
    (...,N1,M1,N2,M2,N3,M3).
    """
    if not isinstance(ndim, int) or ndim < 0:
        raise ValueError('ndim must be non-negative integer')
    if ndim > 0:
        if ndim > np.ndim(A):
            raise ValueError('Argument ndim larger than ndim of the first '
                             'parameter')
        if ndim > np.ndim(B):
            raise ValueError('Argument ndim larger than ndim of the second '
                             'parameter')
        shape_A = np.shape(A) + (1,)*ndim
        shape_B = np.shape(B)[:-ndim] + (1,)*ndim + np.shape(B)[-ndim:]
        A = np.reshape(A, shape_A)
        B = np.reshape(B, shape_B)
    return np.asanyarray(A) * np.asanyarray(B)

def _dot(A, B):
    """
    Dot product which handles broadcasting properly.

    Future NumPy will have a better built-in implementation for this.
    """
    A_plates = np.shape(A)[:-2]
    B_plates = np.shape(B)[:-2]
    M = np.shape(A)[-2]
    N = np.shape(B)[-1]
    Y_plates = misc.broadcasted_shape(A_plates, B_plates)
    if Y_plates == ():
        return np.dot(A, B)
    indices = misc.nested_iterator(Y_plates)
    Y_shape = Y_plates + (M, N)
    Y = np.zeros(Y_shape)
    for i in indices:
        Y[i] = np.dot(A[misc.safe_indices(i, A_plates)],
                      B[misc.safe_indices(i, B_plates)])
    return Y

def dot(*arrays):
    """
    Compute matrix-matrix product.

    You can give multiple arrays, the dot product is computed from left to
    right: A1*A2*A3*...*AN. The dot product is computed over the last two axes
    of each arrays. All other axes must be broadcastable.
    """
    if len(arrays) == 0:
        return 0
    else:
        Y = np.asanyarray(arrays[0])
        for X in arrays[1:]:
            X = np.asanyarray(X)
            if np.ndim(Y) < 2 or np.ndim(X) < 2:
                raise ValueError("Must be at least 2-D arrays")
            if np.shape(Y)[-1] != np.shape(X)[-2]:
                raise ValueError("Dimensions do not match")
            # Replace this with numpy.dot when NumPy implements broadcasting in dot
            Y = _dot(Y, X)
            #Y = np.einsum('...ik,...kj->...ij', Y, X)
            #Y = gula.matrix_multiply(Y, X)
        return Y

def tracedot(A, B):
    """
    Computes trace(A*B).
    """
    return np.einsum('...ij,...ji->...', A, B)

def inv(A, ndim=1):
    """
    General array inversion.

    Supports broadcasting and inversion of multidimensional arrays.  For
    instance, an array with shape (4,3,2,3,2) could mean that there are four
    (3*2) x (3*2) matrices to be inverted. This can be done by inv(A, ndim=2).
    For inverting scalars, ndim=0. For inverting matrices, ndim=1.
    """
    A = np.asanyarray(A)
    if ndim == 0:
        return 1 / A
    elif ndim == 1:
        return np.linalg.inv(A)
    else:
        raise NotImplementedError()

def mvdot(A, b, ndim=1):
    """
    Compute matrix-vector product.

    Applies broadcasting.
    """
    # TODO/FIXME: A bug in inner1d:
    # https://github.com/numpy/numpy/issues/3338
    #
    # b = np.asanyarray(b)
    # return gula.inner1d(A, b[...,np.newaxis,:])
    #
    # Use einsum instead:
    if ndim > 0:
        b = misc.add_axes(b, num=ndim, axis=-1-ndim)

    return inner(A, b, ndim=ndim)
    ## if ndim != 1:
    ##     raise NotImplementedError("mvdot not yet implemented for ndim!=1")

    ## return _dot(A, b[...,None])[...,0]
    ## #return np.einsum('...ik,...k->...i', A, b)

def mmdot(A, B, ndim=1):
    """
    Compute matrix-matrix product.

    Applies broadcasting.
    """
    if ndim == 0:
        return A * B
    elif ndim == 1:
        return _dot(A, B)
    else:
        raise Exception("mmdot not yet implemented for ndim>1")
    #return np.einsum('...ik,...kj->...ij', A, B)

def transpose(X, ndim=1):
    """
    Transpose the matrix.
    """
    for n in range(ndim):
        X = np.swapaxes(X, -1-n, -1-ndim-n)
    return X
    ## if ndim != 1:
    ##     raise Exception("transpose not yet implemented for ndim!=1")
    ## return np.swapaxes(X, -1, -2)

def m_dot(A,b):
    raise DeprecationWarning()
    # Compute matrix-vector product over the last two axes of A and
    # the last axes of b.  Other axes are broadcasted. If A has shape
    # (..., M, N) and b has shape (..., N), then the result has shape
    # (..., M)

    #b = reshape(b, shape(b)[:-1] + (1,) + shape(b)[-1:])
    #return np.dot(A, b)
    return np.einsum('...ik,...k->...i', A, b)
    # TODO: Use einsum!!
    #return np.sum(A*b[...,np.newaxis,:], axis=(-1,))

def block_banded_solve(A, B, y):
    """
    Invert symmetric, banded, positive-definite matrix.

    A contains the diagonal blocks.

    B contains the superdiagonal blocks (their transposes are the
    subdiagonal blocks).

    Shapes:
    A: (...,   N, D, D)
    B: (..., N-1, D, D)
    y: (...,   N,    D)

    The algorithm is basically LU decomposition.

    Computes only the diagonal and super-diagonal blocks of the
    inverse. The true inverse is dense, in general.

    Assume each block has the same size.

    Return:
    * inverse blocks
    * solution to the system
    * log-determinant
    """

    # Number of time instance and dimensionality
    N = np.shape(y)[-2]
    D = np.shape(y)[-1]

    # Check the shape of the diagonal blocks
    if np.shape(A)[-3] != N:
        raise ValueError("The number of diagonal blocks is incorrect")
    if np.shape(A)[-2:] != (D,D):
        raise ValueError("The diagonal blocks have wrong shape")

    # Check the shape of the super-diagonal blocks
    if np.shape(B)[-3] != N-1:
        raise ValueError("The number of super-diagonal blocks is incorrect")
    if np.shape(B)[-2:] != (D,D):
        raise ValueError("The diagonal blocks have wrong shape")

    plates_VC = misc.broadcasted_shape(np.shape(A)[:-3],
                                       np.shape(B)[:-3])
    plates_y = misc.broadcasted_shape(plates_VC,
                                      np.shape(y)[:-2])

    V = np.empty(plates_VC+(N,D,D))
    C = np.empty(plates_VC+(N-1,D,D))
    x = np.empty(plates_y+(N,D))

    #
    # Forward recursion
    #

    # In the forward recursion, store the Cholesky factor in V. So you
    # don't need to recompute them in the backward recursion.

    # TODO: This whole algorithm could be implemented as in-place operation.
    # Might be a nice feature (optional?)

    # TODO/FIXME: chol_solve has quite a high overhead because it uses shape
    # manipulations. Use some more raw method instead.

    x[...,0,:] = y[...,0,:]
    V[...,0,:,:] = chol(A[...,0,:,:])
    ldet = chol_logdet(V[...,0,:,:])
    for n in range(N-1):
        # Compute the solution of the system
        x[...,n+1,:] = (y[...,n+1,:]
                        - mvdot(misc.T(B[...,n,:,:]),
                                chol_solve(V[...,n,:,:],
                                           x[...,n,:])))
        # Compute the superdiagonal block of the inverse
        C[...,n,:,:] = chol_solve(V[...,n,:,:],
                                  B[...,n,:,:],
                                  matrix=True)
        # Compute the diagonal block
        V[...,n+1,:,:] = (A[...,n+1,:,:]
                        - mmdot(misc.T(B[...,n,:,:]), C[...,n,:,:]))
        # Ensure symmetry by 0.5*(V+V.T)
        V[...,n+1,:,:] = 0.5 * (V[...,n+1,:,:] + misc.T(V[...,n+1,:,:]))
        # Compute and store the Cholesky factor of the diagonal block
        V[...,n+1,:,:] = chol(V[...,n+1,:,:])
        # Compute the log-det term here, too
        ldet += chol_logdet(V[...,n+1,:,:])

    #
    # Backward recursion
    #
    x[...,-1,:] = chol_solve(V[...,-1,:,:], x[...,-1,:])
    V[...,-1,:,:] = chol_inv(V[...,-1,:,:])
    for n in reversed(range(N-1)):
        # Compute the solution of the system
        x[...,n,:] = chol_solve(V[...,n,:,:],
                                x[...,n,:] - mvdot(B[...,n,:,:],
                                                   x[...,n+1,:]))
        # Compute the diagonal block of the inverse
        V[...,n,:,:] = (chol_inv(V[...,n,:,:])
                        + mmdot(C[...,n,:,:],
                                mmdot(V[...,n+1,:,:],
                                misc.T(C[...,n,:,:]))))
        C[...,n,:,:] = - mmdot(C[...,n,:,:], V[...,n+1,:,:])
        # Ensure symmetry by 0.5*(V+V.T)
        V[...,n,:,:] = 0.5 * (V[...,n,:,:] + misc.T(V[...,n,:,:]))

    return (V, C, x, ldet)

reason: import numpy,import scipy


text:
import cvxpy as cp
import numpy as np
from numpy.linalg import pinv, inv, norm
from scipy.linalg import eig

def project_L(L0):

    n = L0.shape[0]

    L = cp.Variable((n,n), symmetric=True)

    obj = cp.Minimize(0.5 * cp.norm(L - L0, p='fro')**2)

    constraints = [cp.trace(L) == n]
    constraints += [L >> 0]
    constraints += [L @ np.ones((n)) == np.zeros((n))]
    for i in range(n):
        for j in range(i+1,n):
            constraints += [L[i,j] <= 0]

    prob = cp.Problem(obj, constraints)

    p_star = prob.solve()
    L_proj = L.value
    return L_proj

def proj_grad_descent(X, alpha, beta, L_init, num_iters, eta_L, eta_Y):

    """
    gradients w.r.t. L and Y
    """

    def grad_L(L, Y):
        return alpha * (Y @ Y.T) + 2 * beta * L

    def grad_Y(L, Y):
        return alpha * ((L + L.T) @ Y) - 2 * (X - Y)

    """
    projected gradient descent algorithm
    """

    L_iter = L_init
    Y_iter = X
    obj_old_val = np.inf
    for idx_iter in range(num_iters):

        L_iter = L_iter - eta_L * grad_L(L_iter, Y_iter)
        L_iter = project_L(L_iter)

        Y_iter = Y_iter - eta_Y * grad_Y(L_iter, Y_iter)

        obj_val = norm(X - Y_iter, 'fro')**2 + alpha * np.trace(Y_iter.T @ L_iter @ Y_iter) + beta * (norm(L_iter, 'fro')**2);

        if np.abs(obj_old_val - obj_val) < 1e-4:
            break
        else:
            obj_old_val = obj_val

    print(f"final objective value = {obj_val}")

    return L_iter, Y_iter, obj_val

ext: py

max_stars_repo_name: Eashwar-S/Convex-Optimization

max_issues_repo_name: Eashwar-S/Convex-Optimization

max_forks_repo_name: Eashwar-S/Convex-Optimization

reason: import numpy,from numpy,from scipy,import cvxpy


text:
from numpy.testing import assert_equal
import numpy as np
import skvideo.io
import skvideo.datasets
import sys

if sys.version_info < (2, 7):
    import unittest2 as unittest
else:
    import unittest

def _vreader(backend):
    reader = skvideo.io.vreader(skvideo.datasets.bigbuckbunny(), backend=backend)

    T = 0
    M = 0
    N = 0
    C = 0
    accumulation = 0
    for frame in reader:
        M, N, C = frame.shape
        accumulation += np.sum(frame)
        T += 1

    # check the dimensions of the video

    assert_equal(T, 132)
    assert_equal(M, 720)
    assert_equal(N, 1280)
    assert_equal(C, 3)

    # check the numbers

    assert_equal(109.28332841215979, accumulation / (T * M * N * C))

@unittest.skipIf(not skvideo._HAS_FFMPEG, "FFmpeg required for this test.")
def test_vreader_ffmpeg():
    _vreader("ffmpeg")

@unittest.skipIf(not skvideo._HAS_AVCONV, "LibAV required for this test.")
def test_vreader_libav_version12():
    try:
        if np.int(skvideo._LIBAV_MAJOR_VERSION) < 12:
            return 0
    except:
        return 0

    _vreader("libav")

max_stars_repo_name: mesquitadev/grpc

reason: import numpy,from numpy


text:
# -*- coding: utf-8 -*-

import os
import librosa
import json
import numpy as np
from .data_entry import DataEntry

from collections import Counter

def collection_data(folders=[], training=True):
    total_files = 0
    audios_data = []
    for folder in folders:
        filenames = [f for f in os.listdir(folder) if os.path.isfile(os.path.join(folder, f))]
        for filename in filenames:
            total_files += 1
            filepath = os.path.join(folder, filename)
            entry = {
                'data': DataEntry(filepath),
                'filepath': filepath
            }
            audios_data.append(entry)
    return audios_data

def output_classifier_results(results, filename='results.json'):
    if os.path.isfile(filename):
        os.remove(filename)
    with open(filename, 'w') as outfile:
        json.dump(results, outfile, indent=4, separators=(',', ': '))

def basic_statistics(collection=[]):
    all_audios_length = list(map(lambda x: x['data'].audio_length, collection))
    all_characters = list(map(lambda x: x['data'].characters, collection))
    audios_characters_counter = Counter(np.array(all_characters).flatten())

    return {
        'mean_audio_length': np.mean(all_audios_length),
        'smallest_audio_length': np.min(all_audios_length),
        'largest_audio_length': np.max(all_audios_length),
        'audios_characters_counter': audios_characters_counter
    }

max_stars_repo_name: earaujoassis/captchalyzer

max_issues_repo_name: earaujoassis/captchalyzer

max_forks_repo_name: earaujoassis/captchalyzer

reason: import numpy


text:
# coding: utf-8
# /*##########################################################################
# Copyright (C) 2016-2020 European Synchrotron Radiation Facility
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# ############################################################################*/
""" I/O utility functions"""

__authors__ = ["P. Knobel", "V. Valls"]
__license__ = "MIT"
__date__ = "25/09/2020"

import enum
import os.path
import sys
import time
import logging
import collections

import numpy
import six

from silx.utils.proxy import Proxy
import silx.io.url

import h5py
import h5py.h5t
import h5py.h5a

try:
    import h5pyd
except ImportError as e:
    h5pyd = None

logger = logging.getLogger(__name__)

NEXUS_HDF5_EXT = [".h5", ".nx5", ".nxs", ".hdf", ".hdf5", ".cxi"]
"""List of possible extensions for HDF5 file formats."""

class H5Type(enum.Enum):
    """Identify a set of HDF5 concepts"""
    DATASET = 1
    GROUP = 2
    FILE = 3
    SOFT_LINK = 4
    EXTERNAL_LINK = 5
    HARD_LINK = 6

_CLASSES_TYPE = None
"""Store mapping between classes and types"""

string_types = (basestring,) if sys.version_info[0] == 2 else (str,)  # noqa

builtin_open = open

def supported_extensions(flat_formats=True):
    """Returns the list file extensions supported by `silx.open`.

    The result filter out formats when the expected module is not available.

    :param bool flat_formats: If true, also include flat formats like npy or
        edf (while the expected module is available)
    :returns: A dictionary indexed by file description and containing a set of
        extensions (an extension is a string like "\\*.ext").
    :rtype: Dict[str, Set[str]]
    """
    formats = collections.OrderedDict()
    formats["HDF5 files"] = set(["*.h5", "*.hdf", "*.hdf5"])
    formats["NeXus files"] = set(["*.nx", "*.nxs", "*.h5", "*.hdf", "*.hdf5"])
    formats["NeXus layout from spec files"] = set(["*.dat", "*.spec", "*.mca"])
    if flat_formats:
        try:
            from silx.io import fabioh5
        except ImportError:
            fabioh5 = None
        if fabioh5 is not None:
            formats["NeXus layout from fabio files"] = set(fabioh5.supported_extensions())

    extensions = ["*.npz"]
    if flat_formats:
        extensions.append("*.npy")

    formats["Numpy binary files"] = set(extensions)
    formats["Coherent X-Ray Imaging files"] = set(["*.cxi"])
    return formats

def save1D(fname, x, y, xlabel=None, ylabels=None, filetype=None,
           fmt="%.7g", csvdelim=";", newline="\n", header="",
           footer="", comments="#", autoheader=False):
    """Saves any number of curves to various formats: `Specfile`, `CSV`,
    `txt` or `npy`. All curves must have the same number of points and share
    the same ``x`` values.

    :param fname: Output file path, or file handle open in write mode.
        If ``fname`` is a path, file is opened in ``w`` mode. Existing file
        with a same name will be overwritten.
    :param x: 1D-Array (or list) of abscissa values.
    :param y: 2D-array (or list of lists) of ordinates values. First index
        is the curve index, second index is the sample index. The length
        of the second dimension (number of samples) must be equal to
        ``len(x)``. ``y`` can be a 1D-array in case there is only one curve
        to be saved.
    :param filetype: Filetype: ``"spec", "csv", "txt", "ndarray"``.
        If ``None``, filetype is detected from file name extension
        (``.dat, .csv, .txt, .npy``).
    :param xlabel: Abscissa label
    :param ylabels: List of `y` labels
    :param fmt: Format string for data. You can specify a short format
        string that defines a single format for both ``x`` and ``y`` values,
        or a list of two different format strings (e.g. ``["%d", "%.7g"]``).
        Default is ``"%.7g"``.
        This parameter does not apply to the `npy` format.
    :param csvdelim: String or character separating columns in `txt` and
        `CSV` formats. The user is responsible for ensuring that this
        delimiter is not used in data labels when writing a `CSV` file.
    :param newline: String or character separating lines/records in `txt`
        format (default is line break character ``\\n``).
    :param header: String that will be written at the beginning of the file in
        `txt` format.
    :param footer: String that will be written at the end of the file in `txt`
         format.
    :param comments: String that will be prepended to the ``header`` and
        ``footer`` strings, to mark them as comments. Default: ``#``.
    :param autoheader: In `CSV` or `txt`, ``True`` causes the first header
         line to be written as a standard CSV header line with column labels
         separated by the specified CSV delimiter.

    When saving to Specfile format, each curve is saved as a separate scan
    with two data columns (``x`` and ``y``).

    `CSV` and `txt` formats are similar, except that the `txt` format allows
    user defined header and footer text blocks, whereas the `CSV` format has
    only a single header line with columns labels separated by field
    delimiters and no footer. The `txt` format also allows defining a record
    separator different from a line break.

    The `npy` format is written with ``numpy.save`` and can be read back with
    ``numpy.load``. If ``xlabel`` and ``ylabels`` are undefined, data is saved
    as a regular 2D ``numpy.ndarray`` (contatenation of ``x`` and ``y``). If
    both ``xlabel`` and ``ylabels`` are defined, the data is saved as a
    ``numpy.recarray`` after being transposed and having labels assigned to
    columns.
    """

    available_formats = ["spec", "csv", "txt", "ndarray"]

    if filetype is None:
        exttypes = {".dat": "spec",
                    ".csv": "csv",
                    ".txt": "txt",
                    ".npy": "ndarray"}
        outfname = (fname if not hasattr(fname, "name") else
                    fname.name)
        fileext = os.path.splitext(outfname)[1]
        if fileext in exttypes:
            filetype = exttypes[fileext]
        else:
            raise IOError("File type unspecified and could not be " +
                          "inferred from file extension (not in " +
                          "txt, dat, csv, npy)")
    else:
        filetype = filetype.lower()

    if filetype not in available_formats:
        raise IOError("File type %s is not supported" % (filetype))

    # default column headers
    if xlabel is None:
        xlabel = "x"
    if ylabels is None:
        if numpy.array(y).ndim > 1:
            ylabels = ["y%d" % i for i in range(len(y))]
        else:
            ylabels = ["y"]
    elif isinstance(ylabels, (list, tuple)):
        # if ylabels is provided as a list, every element must
        # be a string
        ylabels = [ylabel if isinstance(ylabel, string_types) else "y%d" % i
                   for ylabel in ylabels]

    if filetype.lower() == "spec":
        # Check if we have regular data:
        ref = len(x)
        regular = True
        for one_y in y:
            regular &= len(one_y) == ref
        if regular:
            if isinstance(fmt, (list, tuple)) and len(fmt) < (len(ylabels) + 1):
                fmt = fmt + [fmt[-1] * (1 + len(ylabels) - len(fmt))]
            specf = savespec(fname, x, y, xlabel, ylabels, fmt=fmt,
                     scan_number=1, mode="w", write_file_header=True,
                     close_file=False)
        else:
            y_array = numpy.asarray(y)
            # make sure y_array is a 2D array even for a single curve
            if y_array.ndim == 1:
                y_array.shape = 1, -1
            elif y_array.ndim not in [1, 2]:
                raise IndexError("y must be a 1D or 2D array")

            # First curve
            specf = savespec(fname, x, y_array[0], xlabel, ylabels[0], fmt=fmt,
                             scan_number=1, mode="w", write_file_header=True,
                             close_file=False)
            # Other curves
            for i in range(1, y_array.shape[0]):
                specf = savespec(specf, x, y_array[i], xlabel, ylabels[i],
                                 fmt=fmt, scan_number=i + 1, mode="w",
                                 write_file_header=False, close_file=False)

        # close file if we created it
        if not hasattr(fname, "write"):
            specf.close()

    else:
        autoheader_line = xlabel + csvdelim + csvdelim.join(ylabels)
        if xlabel is not None and ylabels is not None and filetype == "csv":
            # csv format: optional single header line with labels, no footer
            if autoheader:
                header = autoheader_line + newline
            else:
                header = ""
            comments = ""
            footer = ""
            newline = "\n"
        elif filetype == "txt" and autoheader:
            # Comments string is added at the beginning of header string in
            # savetxt(). We add another one after the first header line and
            # before the rest of the header.
            if header:
                header = autoheader_line + newline + comments + header
            else:
                header = autoheader_line + newline

        # Concatenate x and y in a single 2D array
        X = numpy.vstack((x, y))

        if filetype.lower() in ["csv", "txt"]:
            X = X.transpose()
            savetxt(fname, X, fmt=fmt, delimiter=csvdelim,
                    newline=newline, header=header, footer=footer,
                    comments=comments)

        elif filetype.lower() == "ndarray":
            if xlabel is not None and ylabels is not None:
                labels = [xlabel] + ylabels

                # .transpose is needed here because recarray labels
                # apply to columns
                X = numpy.core.records.fromrecords(X.transpose(),
                                                   names=labels)
            numpy.save(fname, X)

# Replace with numpy.savetxt when dropping support of numpy < 1.7.0
def savetxt(fname, X, fmt="%.7g", delimiter=";", newline="\n",
            header="", footer="", comments="#"):
    """``numpy.savetxt`` backport of header and footer arguments from
    numpy=1.7.0.

    See ``numpy.savetxt`` help:
    http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.savetxt.html
    """
    if not hasattr(fname, "name"):
        ffile = builtin_open(fname, 'wb')
    else:
        ffile = fname

    if header:
        if sys.version_info[0] >= 3:
            header = header.encode("utf-8")
        ffile.write(header)

    numpy.savetxt(ffile, X, fmt, delimiter, newline)

    if footer:
        footer = (comments + footer.replace(newline, newline + comments) +
                  newline)
        if sys.version_info[0] >= 3:
            footer = footer.encode("utf-8")
        ffile.write(footer)

    if not hasattr(fname, "name"):
        ffile.close()

def savespec(specfile, x, y, xlabel="X", ylabel="Y", fmt="%.7g",
             scan_number=1, mode="w", write_file_header=True,
             close_file=False):
    """Saves one curve to a SpecFile.

    The curve is saved as a scan with two data columns. To save multiple
    curves to a single SpecFile, call this function for each curve by
    providing the same file handle each time.

    :param specfile: Output SpecFile name, or file handle open in write
        or append mode. If a file name is provided, a new file is open in
        write mode (existing file with the same name will be lost)
    :param x: 1D-Array (or list) of abscissa values
    :param y: 1D-array (or list), or list of them of ordinates values.
        All dataset must have the same length as x
    :param xlabel: Abscissa label (default ``"X"``)
    :param ylabel: Ordinate label, may be a list of labels when multiple curves
        are to be saved together.
    :param fmt: Format string for data. You can specify a short format
        string that defines a single format for both ``x`` and ``y`` values,
        or a list of two different format strings (e.g. ``["%d", "%.7g"]``).
        Default is ``"%.7g"``.
    :param scan_number: Scan number (default 1).
    :param mode: Mode for opening file: ``w`` (default), ``a``,  ``r+``,
        ``w+``, ``a+``. This parameter is only relevant if ``specfile`` is a
        path.
    :param write_file_header: If ``True``, write a file header before writing
        the scan (``#F`` and ``#D`` line).
    :param close_file: If ``True``, close the file after saving curve.
    :return: ``None`` if ``close_file`` is ``True``, else return the file
        handle.
    """
    # Make sure we use binary mode for write
    # (issue with windows: write() replaces \n with os.linesep in text mode)
    if "b" not in mode:
        first_letter = mode[0]
        assert first_letter in "rwa"
        mode = mode.replace(first_letter, first_letter + "b")

    x_array = numpy.asarray(x)
    y_array = numpy.asarray(y)
    if y_array.ndim > 2:
        raise IndexError("Y columns must have be packed as 1D")

    if y_array.shape[-1] != x_array.shape[0]:
        raise IndexError("X and Y columns must have the same length")

    if y_array.ndim == 2:
        assert isinstance(ylabel, (list, tuple))
        assert y_array.shape[0] == len(ylabel)
        labels = (xlabel, *ylabel)
    else:
        labels = (xlabel, ylabel)
    data = numpy.vstack((x_array, y_array))
    ncol = data.shape[0]
    assert len(labels) == ncol

    print(xlabel, ylabel, fmt, ncol, x_array, y_array)
    if isinstance(fmt, string_types) and fmt.count("%") == 1:
        full_fmt_string = "  ".join([fmt] * ncol)
    elif isinstance(fmt, (list, tuple)) and len(fmt) == ncol:
        full_fmt_string = "  ".join(fmt)
    else:
        raise ValueError("`fmt` must be a single format string or a list of " +
                         "format strings with as many format as ncolumns")

    if not hasattr(specfile, "write"):
        f = builtin_open(specfile, mode)
    else:
        f = specfile

    current_date = "#D %s" % (time.ctime(time.time()))
    if write_file_header:
        lines = [ "#F %s" % f.name, current_date, ""]
    else:
        lines = [""]

    lines += [  "#S %d %s" % (scan_number, labels[1]),
                current_date,
                "#N %d" % ncol,
                "#L " + "  ".join(labels)]

    for i in data.T:
        lines.append(full_fmt_string % tuple(i))
    lines.append("")
    output = "\n".join(lines)
    f.write(output.encode())

    if close_file:
        f.close()
        return None
    return f

def h5ls(h5group, lvl=0):
    """Return a simple string representation of a HDF5 tree structure.

    :param h5group: Any :class:`h5py.Group` or :class:`h5py.File` instance,
        or a HDF5 file name
    :param lvl: Number of tabulations added to the group. ``lvl`` is
        incremented as we recursively process sub-groups.
    :return: String representation of an HDF5 tree structure

    Group names and dataset representation are printed preceded by a number of
    tabulations corresponding to their depth in the tree structure.
    Datasets are represented as :class:`h5py.Dataset` objects.

    Example::

        >>> print(h5ls("Downloads/sample.h5"))
        +fields
            +fieldB
                <HDF5 dataset "z": shape (256, 256), type "<f4">
            +fieldE
                <HDF5 dataset "x": shape (256, 256), type "<f4">
                <HDF5 dataset "y": shape (256, 256), type "<f4">

    .. note:: This function requires `h5py <http://www.h5py.org/>`_ to be
        installed.
    """
    h5repr = ''
    if is_group(h5group):
        h5f = h5group
    elif isinstance(h5group, string_types):
        h5f = open(h5group)  # silx.io.open
    else:
        raise TypeError("h5group must be a hdf5-like group object or a file name.")

    for key in h5f.keys():
        # group
        if hasattr(h5f[key], 'keys'):
            h5repr += '\t' * lvl + '+' + key
            h5repr += '\n'
            h5repr += h5ls(h5f[key], lvl + 1)
        # dataset
        else:
            h5repr += '\t' * lvl
            h5repr += str(h5f[key])
            h5repr += '\n'

    if isinstance(h5group, string_types):
        h5f.close()

    return h5repr

def _open_local_file(filename):
    """
    Load a file as an `h5py.File`-like object.

    Format supported:
    - h5 files, if `h5py` module is installed
    - SPEC files exposed as a NeXus layout
    - raster files exposed as a NeXus layout (if `fabio` is installed)
    - Numpy files ('npy' and 'npz' files)

    The file is opened in read-only mode.

    :param str filename: A filename
    :raises: IOError if the file can't be loaded as an h5py.File like object
    :rtype: h5py.File
    """
    if not os.path.isfile(filename):
        raise IOError("Filename '%s' must be a file path" % filename)

    debugging_info = []
    try:
        _, extension = os.path.splitext(filename)

        if extension in [".npz", ".npy"]:
            try:
                from . import rawh5
                return rawh5.NumpyFile(filename)
            except (IOError, ValueError) as e:
                debugging_info.append((sys.exc_info(),
                                      "File '%s' can't be read as a numpy file." % filename))

        if h5py.is_hdf5(filename):
            try:
                return h5py.File(filename, "r")
            except OSError:
                return h5py.File(filename, "r", libver='latest', swmr=True)

        try:
            from . import fabioh5
            return fabioh5.File(filename)
        except ImportError:
            debugging_info.append((sys.exc_info(), "fabioh5 can't be loaded."))
        except Exception:
            debugging_info.append((sys.exc_info(),
                                   "File '%s' can't be read as fabio file." % filename))

        try:
            from . import spech5
            return spech5.SpecH5(filename)
        except ImportError:
            debugging_info.append((sys.exc_info(),
                                   "spech5 can't be loaded."))
        except IOError:
            debugging_info.append((sys.exc_info(),
                                   "File '%s' can't be read as spec file." % filename))
    finally:
        for exc_info, message in debugging_info:
            logger.debug(message, exc_info=exc_info)

    raise IOError("File '%s' can't be read as HDF5" % filename)

class _MainNode(Proxy):
    """A main node is a sub node of the HDF5 tree which is responsible of the
    closure of the file.

    It is a proxy to the sub node, plus support context manager and `close`
    method usually provided by `h5py.File`.

    :param h5_node: Target to the proxy.
    :param h5_file: Main file. This object became the owner of this file.
    """

    def __init__(self, h5_node, h5_file):
        super(_MainNode, self).__init__(h5_node)
        self.__file = h5_file
        self.__class = get_h5_class(h5_node)

    @property
    def h5_class(self):
        """Returns the HDF5 class which is mimicked by this class.

        :rtype: H5Type
        """
        return self.__class

    @property
    def h5py_class(self):
        """Returns the h5py classes which is mimicked by this class. It can be
        one of `h5py.File, h5py.Group` or `h5py.Dataset`.

        :rtype: h5py class
        """
        return h5type_to_h5py_class(self.__class)

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.close()

    def close(self):
        """Close the file"""
        self.__file.close()
        self.__file = None

def open(filename):  # pylint:disable=redefined-builtin
    """
    Open a file as an `h5py`-like object.

    Format supported:
    - h5 files, if `h5py` module is installed
    - SPEC files exposed as a NeXus layout
    - raster files exposed as a NeXus layout (if `fabio` is installed)
    - Numpy files ('npy' and 'npz' files)

    The filename can be trailled an HDF5 path using the separator `::`. In this
    case the object returned is a proxy to the target node, implementing the
    `close` function and supporting `with` context.

    The file is opened in read-only mode.

    :param str filename: A filename which can containt an HDF5 path by using
        `::` separator.
    :raises: IOError if the file can't be loaded or path can't be found
    :rtype: h5py-like node
    """
    url = silx.io.url.DataUrl(filename)

    if url.scheme() in [None, "file", "silx"]:
        # That's a local file
        if not url.is_valid():
            raise IOError("URL '%s' is not valid" % filename)
        h5_file = _open_local_file(url.file_path())
    elif url.scheme() in ["fabio"]:
        raise IOError("URL '%s' containing fabio scheme is not supported" % filename)
    else:
        # That's maybe an URL supported by h5pyd
        uri = six.moves.urllib.parse.urlparse(filename)
        if h5pyd is None:
            raise IOError("URL '%s' unsupported. Try to install h5pyd." % filename)
        path = uri.path
        endpoint = "%s://%s" % (uri.scheme, uri.netloc)
        if path.startswith("/"):
            path = path[1:]
        return h5pyd.File(path, 'r', endpoint=endpoint)

    if url.data_slice():
        raise IOError("URL '%s' containing slicing is not supported" % filename)

    if url.data_path() in [None, "/", ""]:
        # The full file is requested
        return h5_file
    else:
        # Only a children is requested
        if url.data_path() not in h5_file:
            msg = "File '%s' does not contain path '%s'." % (filename, url.data_path())
            raise IOError(msg)
        node = h5_file[url.data_path()]
        proxy = _MainNode(node, h5_file)
        return proxy

def _get_classes_type():
    """Returns a mapping between Python classes and HDF5 concepts.

    This function allow an lazy initialization to avoid recurssive import
    of modules.
    """
    global _CLASSES_TYPE
    from . import commonh5

    if _CLASSES_TYPE is not None:
        return _CLASSES_TYPE

    _CLASSES_TYPE = collections.OrderedDict()

    _CLASSES_TYPE[commonh5.Dataset] = H5Type.DATASET
    _CLASSES_TYPE[commonh5.File] = H5Type.FILE
    _CLASSES_TYPE[commonh5.Group] = H5Type.GROUP
    _CLASSES_TYPE[commonh5.SoftLink] = H5Type.SOFT_LINK

    _CLASSES_TYPE[h5py.Dataset] = H5Type.DATASET
    _CLASSES_TYPE[h5py.File] = H5Type.FILE
    _CLASSES_TYPE[h5py.Group] = H5Type.GROUP
    _CLASSES_TYPE[h5py.SoftLink] = H5Type.SOFT_LINK
    _CLASSES_TYPE[h5py.HardLink] = H5Type.HARD_LINK
    _CLASSES_TYPE[h5py.ExternalLink] = H5Type.EXTERNAL_LINK

    if h5pyd is not None:
        _CLASSES_TYPE[h5pyd.Dataset] = H5Type.DATASET
        _CLASSES_TYPE[h5pyd.File] = H5Type.FILE
        _CLASSES_TYPE[h5pyd.Group] = H5Type.GROUP
        _CLASSES_TYPE[h5pyd.SoftLink] = H5Type.SOFT_LINK
        _CLASSES_TYPE[h5pyd.HardLink] = H5Type.HARD_LINK
        _CLASSES_TYPE[h5pyd.ExternalLink] = H5Type.EXTERNAL_LINK

    return _CLASSES_TYPE

def get_h5_class(obj=None, class_=None):
    """
    Returns the HDF5 type relative to the object or to the class.

    :param obj: Instance of an object
    :param class_: A class
    :rtype: H5Type
    """
    if class_ is None:
        class_ = obj.__class__

    classes = _get_classes_type()
    t = classes.get(class_, None)
    if t is not None:
        return t

    if obj is not None:
        if hasattr(obj, "h5_class"):
            return obj.h5_class

    for referencedClass_, type_ in classes.items():
        if issubclass(class_, referencedClass_):
            classes[class_] = type_
            return type_

    classes[class_] = None
    return None

def h5type_to_h5py_class(type_):
    """
    Returns an h5py class from an H5Type. None if nothing found.

    :param H5Type type_:
    :rtype: H5py class
    """
    if type_ == H5Type.FILE:
        return h5py.File
    if type_ == H5Type.GROUP:
        return h5py.Group
    if type_ == H5Type.DATASET:
        return h5py.Dataset
    if type_ == H5Type.SOFT_LINK:
        return h5py.SoftLink
    if type_ == H5Type.HARD_LINK:
        return h5py.HardLink
    if type_ == H5Type.EXTERNAL_LINK:
        return h5py.ExternalLink
    return None

def get_h5py_class(obj):
    """Returns the h5py class from an object.

    If it is an h5py object or an h5py-like object, an h5py class is returned.
    If the object is not an h5py-like object, None is returned.

    :param obj: An object
    :return: An h5py object
    """
    if hasattr(obj, "h5py_class"):
        return obj.h5py_class
    type_ = get_h5_class(obj)
    return h5type_to_h5py_class(type_)

def is_file(obj):
    """
    True is the object is an h5py.File-like object.

    :param obj: An object
    """
    t = get_h5_class(obj)
    return t == H5Type.FILE

def is_group(obj):
    """
    True if the object is a h5py.Group-like object. A file is a group.

    :param obj: An object
    """
    t = get_h5_class(obj)
    return t in [H5Type.GROUP, H5Type.FILE]

def is_dataset(obj):
    """
    True if the object is a h5py.Dataset-like object.

    :param obj: An object
    """
    t = get_h5_class(obj)
    return t == H5Type.DATASET

def is_softlink(obj):
    """
    True if the object is a h5py.SoftLink-like object.

    :param obj: An object
    """
    t = get_h5_class(obj)
    return t == H5Type.SOFT_LINK

def is_externallink(obj):
    """
    True if the object is a h5py.ExternalLink-like object.

    :param obj: An object
    """
    t = get_h5_class(obj)
    return t == H5Type.EXTERNAL_LINK

def is_link(obj):
    """
    True if the object is a h5py link-like object.

    :param obj: An object
    """
    t = get_h5_class(obj)
    return t in {H5Type.SOFT_LINK, H5Type.EXTERNAL_LINK}

def get_data(url):
    """Returns a numpy data from an URL.

    Examples:

    >>> # 1st frame from an EDF using silx.io.open
    >>> data = silx.io.get_data("silx:/users/foo/image.edf::/scan_0/instrument/detector_0/data[0]")

    >>> # 1st frame from an EDF using fabio
    >>> data = silx.io.get_data("fabio:/users/foo/image.edf::[0]")

    Yet 2 schemes are supported by the function.

    - If `silx` scheme is used, the file is opened using
        :meth:`silx.io.open`
        and the data is reach using usually NeXus paths.
    - If `fabio` scheme is used, the file is opened using :meth:`fabio.open`
        from the FabIO library.
        No data path have to be specified, but each frames can be accessed
        using the data slicing.
        This shortcut of :meth:`silx.io.open` allow to have a faster access to
        the data.

    .. seealso:: :class:`silx.io.url.DataUrl`

    :param Union[str,silx.io.url.DataUrl]: A data URL
    :rtype: Union[numpy.ndarray, numpy.generic]
    :raises ImportError: If the mandatory library to read the file is not
        available.
    :raises ValueError: If the URL is not valid or do not match the data
    :raises IOError: If the file is not found or in case of internal error of
        :meth:`fabio.open` or :meth:`silx.io.open`. In this last case more
        informations are displayed in debug mode.
    """
    if not isinstance(url, silx.io.url.DataUrl):
        url = silx.io.url.DataUrl(url)

    if not url.is_valid():
        raise ValueError("URL '%s' is not valid" % url.path())

    if not os.path.exists(url.file_path()):
        raise IOError("File '%s' not found" % url.file_path())

    if url.scheme() == "silx":
        data_path = url.data_path()
        data_slice = url.data_slice()

        with open(url.file_path()) as h5:
            if data_path not in h5:
                raise ValueError("Data path from URL '%s' not found" % url.path())
            data = h5[data_path]

            if not silx.io.is_dataset(data):
                raise ValueError("Data path from URL '%s' is not a dataset" % url.path())

            if data_slice is not None:
                data = h5py_read_dataset(data, index=data_slice)
            else:
                # works for scalar and array
                data = h5py_read_dataset(data)

    elif url.scheme() == "fabio":
        import fabio
        data_slice = url.data_slice()
        if data_slice is None:
            data_slice = (0,)
        if data_slice is None or len(data_slice) != 1:
            raise ValueError("Fabio slice expect a single frame, but %s found" % data_slice)
        index = data_slice[0]
        if not isinstance(index, int):
            raise ValueError("Fabio slice expect a single integer, but %s found" % data_slice)

        try:
            fabio_file = fabio.open(url.file_path())
        except Exception:
            logger.debug("Error while opening %s with fabio", url.file_path(), exc_info=True)
            raise IOError("Error while opening %s with fabio (use debug for more information)" % url.path())

        if fabio_file.nframes == 1:
            if index != 0:
                raise ValueError("Only a single frame available. Slice %s out of range" % index)
            data = fabio_file.data
        else:
            data = fabio_file.getframe(index).data

        # There is no explicit close
        fabio_file = None

    else:
        raise ValueError("Scheme '%s' not supported" % url.scheme())

    return data

def rawfile_to_h5_external_dataset(bin_file, output_url, shape, dtype,
                                   overwrite=False):
    """
    Create a HDF5 dataset at `output_url` pointing to the given vol_file.

    Either `shape` or `info_file` must be provided.

    :param str bin_file: Path to the .vol file
    :param DataUrl output_url: HDF5 URL where to save the external dataset
    :param tuple shape: Shape of the volume
    :param numpy.dtype dtype: Data type of the volume elements (default: float32)
    :param bool overwrite: True to allow overwriting (default: False).
    """
    assert isinstance(output_url, silx.io.url.DataUrl)
    assert isinstance(shape, (tuple, list))
    v_majeur, v_mineur, v_micro = h5py.version.version.split('.')
    if v_majeur <= '2' and v_mineur < '9':
        raise Exception('h5py >= 2.9 should be installed to access the '
                        'external feature.')

    with h5py.File(output_url.file_path(), mode="a") as _h5_file:
        if output_url.data_path() in _h5_file:
            if overwrite is False:
                raise ValueError('data_path already exists')
            else:
                logger.warning('will overwrite path %s' % output_url.data_path())
                del _h5_file[output_url.data_path()]
        external = [(bin_file, 0, h5py.h5f.UNLIMITED)]
        _h5_file.create_dataset(output_url.data_path(),
                                shape,
                                dtype=dtype,
                                external=external)

def vol_to_h5_external_dataset(vol_file, output_url, info_file=None,
                               vol_dtype=numpy.float32, overwrite=False):
    """
    Create a HDF5 dataset at `output_url` pointing to the given vol_file.

    If the vol_file.info containing the shape is not on the same folder as the
     vol-file then you should specify her location.

    :param str vol_file: Path to the .vol file
    :param DataUrl output_url: HDF5 URL where to save the external dataset
    :param Union[str,None] info_file:
        .vol.info file name written by pyhst and containing the shape information
    :param numpy.dtype vol_dtype: Data type of the volume elements (default: float32)
    :param bool overwrite: True to allow overwriting (default: False).
    :raises ValueError: If fails to read shape from the .vol.info file
    """
    _info_file = info_file
    if _info_file is None:
        _info_file = vol_file + '.info'
        if not os.path.exists(_info_file):
            logger.error('info_file not given and %s does not exists, please'
                         'specify .vol.info file' % _info_file)
            return

    def info_file_to_dict():
        ddict = {}
        with builtin_open(info_file, "r") as _file:
            lines = _file.readlines()
            for line in lines:
                if not '=' in line:
                    continue
                l = line.rstrip().replace(' ', '')
                l = l.split('#')[0]
                key, value = l.split('=')
                ddict[key.lower()] = value
        return ddict

    ddict = info_file_to_dict()
    if 'num_x' not in ddict or 'num_y' not in ddict or 'num_z' not in ddict:
        raise ValueError(
            'Unable to retrieve volume shape from %s' % info_file)

    dimX = int(ddict['num_x'])
    dimY = int(ddict['num_y'])
    dimZ = int(ddict['num_z'])
    shape = (dimZ, dimY, dimX)

    return rawfile_to_h5_external_dataset(bin_file=vol_file,
                                          output_url=output_url,
                                          shape=shape,
                                          dtype=vol_dtype,
                                          overwrite=overwrite)

def h5py_decode_value(value, encoding="utf-8", errors="surrogateescape"):
    """Keep bytes when value cannot be decoded

    :param value: bytes or array of bytes
    :param encoding str:
    :param errors str:
    """
    try:
        if numpy.isscalar(value):
            return value.decode(encoding, errors=errors)
        str_item = [b.decode(encoding, errors=errors) for b in value.flat]
        return numpy.array(str_item, dtype=object).reshape(value.shape)
    except UnicodeDecodeError:
        return value

def h5py_encode_value(value, encoding="utf-8", errors="surrogateescape"):
    """Keep string when value cannot be encoding

    :param value: string or array of strings
    :param encoding str:
    :param errors str:
    """
    try:
        if numpy.isscalar(value):
            return value.encode(encoding, errors=errors)
        bytes_item = [s.encode(encoding, errors=errors) for s in value.flat]
        return numpy.array(bytes_item, dtype=object).reshape(value.shape)
    except UnicodeEncodeError:
        return value

class H5pyDatasetReadWrapper:
    """Wrapper to handle H5T_STRING decoding on-the-fly when reading
    a dataset. Uniform behaviour for h5py 2.x and h5py 3.x

    h5py abuses H5T_STRING with ASCII character set
    to store `bytes`: dset[()] = b"..."
    Therefore an H5T_STRING with ASCII encoding is not decoded by default.
    """

    H5PY_AUTODECODE_NONASCII = int(h5py.version.version.split(".")[0]) < 3

    def __init__(self, dset, decode_ascii=False):
        """
        :param h5py.Dataset dset:
        :param bool decode_ascii:
        """
        try:
            string_info = h5py.h5t.check_string_dtype(dset.dtype)
        except AttributeError:
            # h5py < 2.10
            try:
                idx = dset.id.get_type().get_cset()
            except AttributeError:
                # Not an H5T_STRING
                encoding = None
            else:
                encoding = ["ascii", "utf-8"][idx]
        else:
            # h5py >= 2.10
            try:
                encoding = string_info.encoding
            except AttributeError:
                # Not an H5T_STRING
                encoding = None
        if encoding == "ascii" and not decode_ascii:
            encoding = None
        if encoding != "ascii" and self.H5PY_AUTODECODE_NONASCII:
            # Decoding is already done by the h5py library
            encoding = None
        if encoding == "ascii":
            # ASCII can be decoded as UTF-8
            encoding = "utf-8"
        self._encoding = encoding
        self._dset = dset

    def __getitem__(self, args):
        value = self._dset[args]
        if self._encoding:
            return h5py_decode_value(value, encoding=self._encoding)
        else:
            return value

class H5pyAttributesReadWrapper:
    """Wrapper to handle H5T_STRING decoding on-the-fly when reading
    an attribute. Uniform behaviour for h5py 2.x and h5py 3.x

    h5py abuses H5T_STRING with ASCII character set
    to store `bytes`: dset[()] = b"..."
    Therefore an H5T_STRING with ASCII encoding is not decoded by default.
    """

    H5PY_AUTODECODE = int(h5py.version.version.split(".")[0]) >= 3

    def __init__(self, attrs, decode_ascii=False):
        """
        :param h5py.Dataset dset:
        :param bool decode_ascii:
        """
        self._attrs = attrs
        self._decode_ascii = decode_ascii

    def __getitem__(self, args):
        value = self._attrs[args]

        # Get the string encoding (if a string)
        try:
            dtype = self._attrs.get_id(args).dtype
        except AttributeError:
            # h5py < 2.10
            attr_id = h5py.h5a.open(self._attrs._id, self._attrs._e(args))
            try:
                idx = attr_id.get_type().get_cset()
            except AttributeError:
                # Not an H5T_STRING
                return value
            else:
                encoding = ["ascii", "utf-8"][idx]
        else:
            # h5py >= 2.10
            try:
                encoding = h5py.h5t.check_string_dtype(dtype).encoding
            except AttributeError:
                # Not an H5T_STRING
                return value

        if self.H5PY_AUTODECODE:
            if encoding == "ascii" and not self._decode_ascii:
                # Undo decoding by the h5py library
                return h5py_encode_value(value, encoding="utf-8")
        else:
            if encoding == "ascii" and self._decode_ascii:
                # Decode ASCII as UTF-8 for consistency
                return h5py_decode_value(value, encoding="utf-8")

        # Decoding is already done by the h5py library
        return value

    def items(self):
        for k in self._attrs.keys():
            yield k, self[k]

def h5py_read_dataset(dset, index=tuple(), decode_ascii=False):
    """Read data from dataset object. UTF-8 strings will be
    decoded while ASCII strings will only be decoded when
    `decode_ascii=True`.

    :param h5py.Dataset dset:
    :param index: slicing (all by default)
    :param bool decode_ascii:
    """
    return H5pyDatasetReadWrapper(dset, decode_ascii=decode_ascii)[index]

def h5py_read_attribute(attrs, name, decode_ascii=False):
    """Read data from attributes. UTF-8 strings will be
    decoded while ASCII strings will only be decoded when
    `decode_ascii=True`.

    :param h5py.AttributeManager attrs:
    :param str name: attribute name
    :param bool decode_ascii:
    """
    return H5pyAttributesReadWrapper(attrs, decode_ascii=decode_ascii)[name]

def h5py_read_attributes(attrs, decode_ascii=False):
    """Read data from attributes. UTF-8 strings will be
    decoded while ASCII strings will only be decoded when
    `decode_ascii=True`.

    :param h5py.AttributeManager attrs:
    :param bool decode_ascii:
    """
    return dict(H5pyAttributesReadWrapper(attrs, decode_ascii=decode_ascii).items())

max_stars_repo_name: sanjaymsh/silx

max_issues_repo_name: sanjaymsh/silx

max_forks_repo_name: sanjaymsh/silx


text:
import numpy as np
from scipy.optimize import curve_fit
import iminuit

__all__ = [
    "ext_max_llhd",
    "NormBackground",
]

def ext_max_llhd(x, func, guess, guess_err=None, limits=None):
    """
    Routine for finding the Extended Unbinned Maximum Likelihood of an
    inputted spectrum, giving an inputted (arbitrary) function.

    Parameters
    ----------
    x : array_like
        The energies of each inputted event.
    func : FunctionType
        The negative log-likelihood for the normalized PDF, see Notes.
    guess : array_like
        Guesses for the true values of each parameter.
    guess_err : array_like, optional
        Guess for the errors of each parameter. Default is to
        simply use the guesses.
    limits : array_like, optional
        The limits to set on each parameter. Default is to set no
        limits. Should be of form:
            [(lower0, upper0), (lower1, upper1), ...]

    Returns
    -------
    m : iminuit.Minuit
        The Minuit object that contains all information on the fit,
        after the MINUIT algorithm has completed.

    Notes
    -----
    For a normalized PDF of form f(x, p) / Norm(p), where p is a vector
    of the fit parameters, the negative-log likelihood for the Extended
    Unbinned Maximum Likelihood method is:

        -log(L) = Norm(p) - sum(log(f(x, p)))

    """

    if guess_err is None:
        guess_err = [g for ii, g in enumerate(guess)]

    if limits is None:
        limits = [(-np.inf, np.inf) for ii in range(len(guess))]

    m = iminuit.Minuit(
        lambda p: func(x, p),
        guess,
        name=[f'p{ii}' for ii in range(len(guess))],
    )
    m.limits = limits
    m.errors = guess_err
    m.errordef = 1

    m.migrad()
    m.hesse()

    return m

class NormBackground(object):
    """
    Class for calculating a normalized spectrum from specified
    background shapes.

    """

    def __init__(self, lwrbnd, uprbnd, flatbkgd=True, nexpbkgd=0,
                 ngaussbkgd=0):
        """
        Initalization of the NormBackground class.

        Parameters
        ----------
        lwrbnd : float
            The lower bound of the background spectra, in energy.
        uprbnd : float
            The upper bound of the background spectra, in energy.
        flatbkgd : bool, optional
            If True, then the background spectrum will have a flat
            background component. If False, there will not be one.
            Default is True.
        nexpbkgd : int, optional
            The number of exponential spectra in the background
            spectrum. Default is 0.
        ngaussbkgd : int, optional
            The number of Gaussian spectra in the background spectrum.
            Default is 0.

        """

        self._lwrbnd = lwrbnd
        self._uprbnd = uprbnd
        self._bool_flatbkgd = flatbkgd
        self._nexpbkgd = nexpbkgd
        self._ngaussbkgd = ngaussbkgd

        self._nparams = flatbkgd + nexpbkgd * 2 + ngaussbkgd * 3

    @staticmethod
    def _flatbkgd(x, *p):
        """Hidden method to calculate a flat spectrum."""

        if np.isscalar(x):
            return p[0]

        return p[0] * np.ones(len(x))

    @staticmethod
    def _expbkgd(x, *p):
        """Hidden method to calculate an exponential spectrum."""

        return p[0] * np.exp(-x / p[1])

    @staticmethod
    def _gaussbkgd(x, *p):
        """Hidden method to calculate a Gaussian spectrum."""

        return p[0] * np.exp(-(x - p[1])**2 / (2 * p[2]**2))

    def background(self, x, p):
        """
        Method for calculating the differential background (in units of
        1 / [energy]) given the inputted parameters and initialized
        background shape.

        Parameters
        ----------
        x : ndarray
            The energies at which the background will be calculated.
        p : array_like
            The parameters that determine the shape of each component
            of the background. See Notes for order of parameters.

        Returns
        -------
        output : ndarray
            The differential background spectrum at each `x` value,
            given the inputted shape parameters `p`. Units of
            1 / [energy].

        Notes
        -----
        The order of parameters should be

            1) The flat background rate (if there is one, otherwise
                skip)
            2) The exponential shape parameters for each exponential
                background (if nonzero):
                    (amplitude, exponential coefficient)
            3) The Gaussian shape parameters for each Gaussian
                background (if nonzero):
                    (ampltiude, mean, standard deviation)

        """

        if len(p) != self._nparams:
            raise ValueError(
                'Length of p does not match expected number of parameters'
            )

        output = np.zeros(len(x))
        ii = 0

        if self._bool_flatbkgd:
            output += self._flatbkgd(x, *(p[ii], ))
            ii += 1

        for jj in range(self._nexpbkgd):
            output += self._expbkgd(x, *(p[ii], p[ii + 1]))
            ii += 2

        for jj in range(self._ngaussbkgd):
            output += self._gaussbkgd(x, *(p[ii], p[ii + 1], p[ii + 2]))
            ii += 3

        return output

    def _normalization(self, p):
        """
        Hidden method for calculating the normalization of the
        background spectrum.

        """

        norm = 0
        ii = 0

        if self._bool_flatbkgd:
            norm += self._flatbkgd(
                0, *(p[ii], ),
            ) * (self._uprbnd - self._lwrbnd)
            ii += 1

        for jj in range(self._nexpbkgd):
            norm += p[ii + 1] * (
                self._expbkgd(
                    self._lwrbnd, *(p[ii], p[ii + 1]),
                ) - self._expbkgd(
                    self._uprbnd, *(p[ii], p[ii + 1]),
                )
            )
            ii += 2

        for jj in range(self._ngaussbkgd):
            norm += p[ii] * np.sqrt(2 * np.pi * p[ii + 2]**2)
            ii += 3

        return norm

    def neglogllhd(self, x, p):
        """
        Method for calculating the negative log-likelihood for use with
        an extended maximum likelihood method, e.g.
        `rqpy.ext_max_llhd`.

        Parameters
        ----------
        x : ndarray
            The energies at which the background will be calculated.
        p : array_like
            The parameters that determine the shape of each component
            of the background. See Notes for order of parameters.

        Returns
        -------
        out : float
            The extended maximum likelihood for inputted spectrum
            parameters.

        Notes
        -----
        The order of parameters should be

            1) The flat background rate (if there is one, otherwise
                skip)
            2) The exponential shape parameters for each exponential
                background (if nonzero):
                    (amplitude, exponential coefficient)
            3) The Gaussian shape parameters for each Gaussian
                background (if nonzero):
                    (ampltiude, mean, standard deviation)

        """

        return -sum(np.log(self.background(x, p))) + self._normalization(p)

max_stars_repo_name: slwatkins/detprocess

max_issues_repo_name: slwatkins/detprocess

max_forks_repo_name: slwatkins/detprocess

reason: import numpy,from scipy


text:
# Copyright 2020 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================

# coding: utf-8
# for more details about the yolo darknet weights file, refer to
# https://itnext.io/implementing-yolo-v3-in-tensorflow-tf-slim-c3c55ff59dbe

from __future__ import division, print_function

import os
import sys
import tensorflow as tf
import numpy as np

from model import yolov3
from utils.misc_utils import parse_anchors, load_weights

num_class = 80
img_size = 416
weight_path = './data/darknet_weights/darknet53.conv.74'
save_path = './data/darknet_weights/darknet53.ckpt'
anchors = parse_anchors('./data/yolo_anchors.txt')

model = yolov3(num_class, anchors)
with tf.Session() as sess:
    inputs = tf.placeholder(tf.float32, [1, img_size, img_size, 3])

    with tf.variable_scope('yolov3'):
        feature_map = model.forward(inputs)

    saver = tf.train.Saver(var_list=tf.global_variables(scope='yolov3'))

    load_ops = load_weights(tf.global_variables(scope='yolov3'), weight_path)

    sess.run(tf.global_variables_initializer())
    sess.run(load_ops)
    saver.save(sess, save_path=save_path)
    print('TensorFlow model checkpoint has been saved to {}'.format(save_path))

max_stars_repo_name: Ascend/modelzoo

max_issues_repo_name: Ascend/modelzoo

max_forks_repo_name: Ascend/modelzoo


text:
import numpy as np

def l2_regularization(W, reg_strength):
    """
    Computes L2 regularization loss on weights and its gradient

    Arguments:
      W, np array - weights
      reg_strength - float value

    Returns:
      loss, single value - l2 regularization loss
      gradient, np.array same shape as W - gradient of weight by l2 loss
    """
    # TODO: Copy from the previous assignment
    loss = reg_strength * np.sum(np.power(W, 2))
    grad = W * 2 * reg_strength

    return loss, grad

def softmax(predictions):
    '''
    Computes probabilities from scores

    Arguments:
      predictions, np array, shape is either (N) or (batch_size, N) -
        classifier output

    Returns:
      probs, np array of the same shape as predictions -
        probability for every class, 0..1
    '''
    # TODO implement softmax
    # Your final implementation shouldn't have any loops

    if (predictions.ndim == 1):
        predictions_stab = predictions - np.max(predictions)
        prob = np.exp(predictions_stab) / np.sum(np.exp(predictions_stab))
    else:  # for batches
        predictions_stab = predictions - np.max(predictions, -1)[:, None]
        prob = np.exp(predictions_stab) / np.sum(np.exp(predictions_stab), -1)[:, None]

    return prob

def cross_entropy_loss(probs, target_index):
    '''
    Computes cross-entropy loss

    Arguments:
      probs, np array, shape is either (N) or (batch_size, N) -
        probabilities for every class
      target_index: np array of int, shape is (1) or (batch_size) -
        index of the true class for given sample(s)

    Returns:
      loss: single value
    '''
    # TODO implement cross-entropy
    # Your final implementation shouldn't have any loops
    with np.errstate(divide="ignore"):
        if (probs.ndim == 1):
            loss = -np.log(probs[target_index][0])
        else:  # for batches
            loss = np.mean(-np.log(probs[np.arange(probs.shape[0]), target_index]))
    if np.isinf(loss):
        loss = 0

    return loss

def softmax_with_cross_entropy(preds, target_index):
    """
    Computes softmax and cross-entropy loss for model predictions,
    including the gradient

    Arguments:
      predictions, np array, shape is either (N) or (batch_size, N) -
        classifier output
      target_index: np array of int, shape is (1) or (batch_size) -
        index of the true class for given sample(s)

    Returns:
      loss, single value - cross-entropy loss
      dprediction, np array same shape as predictions - gradient of predictions by loss value
    """
    # TODO: Copy from the previous assignment
    if (preds.ndim == 1):
        batch_size = 1
    else:
        batch_size = preds.shape[0]
    probs = softmax(preds)
    loss = cross_entropy_loss(probs, target_index)
    grad = probs.copy()
    if (grad.ndim == 1):
        grad[target_index] -= 1
    else:  # for batches
        grad[np.arange(batch_size), target_index] -= 1
    grad = grad / batch_size

    return loss, grad

class Param:
    """
    Trainable parameter of the model
    Captures both parameter value and the gradient
    """

    def __init__(self, value):
        self.value = value
        self.grad = None
        self.grad_clear()

    def grad_clear(self):
        self.grad = np.zeros_like(self.value)

class ReLULayer:
    def __init__(self):
        self.X = None
        self.id = "RELU"

    def forward(self, X):
        # TODO_: Implement forward pass
        # Hint: you'll need to save some information about X
        # to use it later in the backward pass
        result = np.maximum(X, 0)
        self.X = X
        return result

    def backward(self, d_out):
        """
        Backward pass

        Arguments:
        d_out, np array (batch_size, num_features) - gradient
           of loss function with respect to output

        Returns:
        d_result: np array (batch_size, num_features) - gradient
          with respect to input
        """
        # TODO_: Implement backward pass
        # Your final implementation shouldn't have any loops
        d_X = (self.X > 0) * d_out
        return d_X

    def params(self):
        # ReLU Doesn't have any parameters
        return {}

    def params_grad_clear(self):
        # ReLU Doesn't have any parameters
        pass

class FullyConnectedLayer:
    def __init__(self, n_input, n_output):
        self.W = Param(0.001 * np.random.randn(n_input, n_output))
        self.B = Param(0.001 * np.random.randn(1, n_output))
        self.X = None
        self.id = "FC"

    def forward(self, X):
        # TODO: Implement forward pass
        # Your final implementation shouldn't have any loops
        self.X = X.copy()

        l_result = np.dot(X, self.W.value) + self.B.value

        return l_result

    def backward(self, d_out):
        """
        Backward pass
        Computes gradient with respect to input and
        accumulates gradients within self.W and self.B

        Arguments:
        d_out, np array (batch_size, n_output) - gradient
           of loss function with respect to output

        Returns:
        d_result: np array (batch_size, n_input) - gradient
          with respect to input
        """
        # TODO: Implement backward pass
        # Compute both gradient with respect to input
        # and gradients with respect to W and B
        # Add gradients of W and B to their `grad` attribute

        # It should be pretty similar to linear classifier from
        # the previous assignment

        # Calculate W and B gradients
        self.B.grad = np.dot(np.ones((self.X.shape[0], 1)).T, d_out)
        self.W.grad = np.dot(self.X.T, d_out)

        # Calculate X gradients
        d_input = np.dot(d_out, self.W.value.T)

        return d_input

    def params(self):
        return {'W': self.W, 'B': self.B}

    def params_grad_clear(self):
        self.W.grad_clear()
        self.B.grad_clear()

class ConvolutionalLayer:
    def __init__(self, in_channels, out_channels,
                 filter_size, padding):
        '''
        Initializes the layer

        Arguments:
        in_channels, int - number of input channels
        out_channels, int - number of output channels
        filter_size, int - size of the conv filter
        padding, int - number of 'pixels' to pad on each side
        '''

        self.filter_size = filter_size
        self.in_channels = in_channels
        self.out_channels = out_channels
        self.X = None
        self.id = "CONV"

        self.W = Param(
            np.random.randn(filter_size, filter_size,
                            in_channels, out_channels)
        )

        self.B = Param(np.zeros(out_channels))

        self.padding = padding

    def forward(self, X):
        batch_size, height, width, channels = X.shape

        out_height = height - self.filter_size + 2 * self.padding + 1  # stride is 1
        out_width = width - self.filter_size + 2 * self.padding + 1  # stride is 1

        # TODO: Implement forward pass
        # Hint: setup variables that hold the result
        # and one x/y location at a time in the loop below
        self.X = X.copy()
        p = self.padding
        X_padded = np.pad(X, ((0, 0), (p, p), (p, p), (0, 0)), constant_values=0)

        # It's ok to use loops for going over width and height
        # but try to avoid having any other loops
        f = self.filter_size
        l_result = np.zeros((batch_size, out_height, out_width, self.out_channels))
        W_flat = self.W.value.reshape(-1, self.W.value.shape[-1])
        for y in range(out_height):
            for x in range(out_width):
                X_flat = X_padded[:, y:y + f, x:x + f, :].reshape(X_padded.shape[0], -1)  # flatten part of the input
                l_result[:, y, x] = np.dot(X_flat, W_flat) + self.B.value

        return l_result

    def backward(self, d_out):
        # Hint: Forward pass was reduced to matrix multiply
        # You already know how to backprop through that
        # when you implemented FullyConnectedLayer
        # Just do it the same number of times and accumulate gradients

        batch_size, height, width, channels = self.X.shape
        _, out_height, out_width, out_channels = d_out.shape

        # TODO: Implement backward pass
        # Same as forward, setup variables of the right shape that
        # aggregate input gradient and fill them for every location
        # of the output

        # Try to avoid having any other loops here too
        f = self.filter_size
        W_flat = self.W.value.reshape(-1, self.W.value.shape[-1])
        p = self.padding
        X_padded = np.pad(self.X, ((0, 0), (p, p), (p, p), (0, 0)), constant_values=0)
        d_padded = np.zeros_like(X_padded)
        for y in range(out_height):
            for x in range(out_width):
                # TODO: Implement backward pass for specific location
                # Aggregate gradients for both the input and
                # the parameters (W and B)
                # Calculate W and B gradients
                X_flat = X_padded[:, y:y + f, x:x + f, :].reshape(X_padded.shape[0], -1)  # flatten part of the input
                self.B.grad += np.dot(np.ones((X_flat.shape[0], 1)).T, d_out[:, y, x, :]).reshape(self.B.grad.shape)
                self.W.grad += np.dot(X_flat.T, d_out[:, y, x, :]).reshape(self.W.grad.shape)

                # Calculate X gradients
                d_padded[:, y:y + f, x:x + f, :] += np.dot(d_out[:, y, x, :], W_flat.T).reshape(d_padded[:, y:y + f, x:x + f, :].shape)

        d_input = d_padded[:, p:-p, p:-p, :] if p else d_padded
        return d_input

    def params(self):
        return { 'W': self.W, 'B': self.B }

    def params_grad_clear(self):
        self.W.grad_clear()
        self.B.grad_clear()

class MaxPoolingLayer:
    def __init__(self, pool_size, stride):
        '''
        Initializes the max pool

        Arguments:
        pool_size, int - area to pool
        stride, int - step size between pooling windows
        '''
        self.pool_size = pool_size
        self.stride = stride
        self.X = None
        self.id = "MAXPOOL"

    def forward(self, X):
        batch_size, height, width, channels = X.shape
        # TODO: Implement maxpool forward pass
        # Hint: Similarly to Conv layer, loop on
        # output x/y dimension

        s = self.stride
        f = self.pool_size

        out_height = ((height - f) // s) + 1
        out_width = ((width - f) // s) + 1

        # TODO: Implement forward pass
        # Hint: setup variables that hold the result
        # and one x/y location at a time in the loop below
        self.X = X.copy()

        l_result = np.zeros((batch_size, out_height, out_width, channels))

        for y in range(out_height):
            for x in range(out_width):
                X_window = X[:, y * s:np.minimum(y * s + f, height), x * s:np.minimum(x * s + f, width), :]
                l_result[:, y, x, :] = X_window.max(axis=(1, 2))

        return l_result

    def backward(self, d_out):
        # TODO: Implement maxpool backward pass
        batch_size, height, width, channels = self.X.shape
        _, out_height, out_width, out_channels = d_out.shape

        s = self.stride
        f = self.pool_size

        d_input = np.zeros_like(self.X)
        for b in range(batch_size):
            for c in range(channels):
                for y in range(out_height):
                    for x in range(out_width):
                        X_window = self.X[b, y * s:np.minimum(y * s + f, height), x * s:np.minimum(x * s + f, width), c]
                        d_input_argmax = np.unravel_index(np.argmax(X_window, axis=None), X_window.shape)
                        d_input_pool = np.zeros_like(X_window)
                        d_input_pool[d_input_argmax] = d_out[b, y, x, c]
                        d_input[b, y * s:np.minimum(y * s + f, height), x * s:np.minimum(x * s + f, width), c] += d_input_pool

        return d_input

    def params(self):
        return {}

    def params_grad_clear(self):
        # No params!
        pass

class Flattener:
    def __init__(self):
        self.X_shape = None
        self.id = "FLATTENER"

    def forward(self, X):
        batch_size, height, width, channels = X.shape

        # TODO: Implement forward pass
        # Layer should return array with dimensions
        # [batch_size, hight*width*channels]
        self.X_shape = X.shape
        return X.reshape(batch_size, -1)

    def backward(self, d_out):
        # TODO: Implement backward pass
        return d_out.reshape(self.X_shape)

    def params(self):
        # No params!
        return {}

    def params_grad_clear(self):
        # No params!
        pass


text:
"""
Distributed under the terms of the MIT License.

The full license is in the file LICENSE, distributed with this software.

Copyright (C) Jun Zhu. All rights reserved.
"""
import numpy as np

def quick_min_max(x, q=None):
    """Estimate the min/max values of input by down-sampling.

    :param numpy.ndarray x: data, 2D array for now.
    :param float/None q: quantile when calculating the min/max, which
        must be within [0, 1].

    :return tuple: (min, max)
    """
    if not isinstance(x, np.ndarray):
        raise TypeError("Input must be a numpy.ndarray!")

    if x.ndim != 2:
        raise ValueError("Input must be a 2D array!")

    while x.size > 1e5:
        sl = [slice(None)] * x.ndim
        sl[np.argmax(x.shape)] = slice(None, None, 2)
        x = x[tuple(sl)]

    if q is None:
        return np.nanmin(x), np.nanmax(x)

    if q < 0.5:
        q = 1 - q

    # Let np.nanquantile to handle the case when q is outside [0, 1]
    # caveat: nanquantile is about 30 times slower than nanmin/nanmax
    return (np.nanquantile(x, 1 - q, interpolation='nearest'),
            np.nanquantile(x, q, interpolation='nearest'))


text:
import os
import argparse
from argparse import Namespace

from tqdm import tqdm
import time
import numpy as np
import torch
from PIL import Image
from torch.utils.data import DataLoader
import sys

sys.path.append(".")
sys.path.append("..")

from configs import data_configs
from datasets.inference_dataset import InferenceDataset
from utils.common import tensor2im, log_input_image
from options.test_options import TestOptions
from models.psp import pSp

def run(test_opts):
    # test_opts = TestOptions().parse()

    if test_opts.resize_factors is not None:
        assert len(
            test_opts.resize_factors.split(',')) == 1, "When running inference, provide a single downsampling factor!"
        out_path_results = os.path.join(test_opts.exp_dir, 'inference_results',
                                        'downsampling_{}'.format(test_opts.resize_factors))
        out_path_coupled = os.path.join(test_opts.exp_dir, 'inference_coupled',
                                        'downsampling_{}'.format(test_opts.resize_factors))
    else:
        out_path_results = os.path.join(test_opts.exp_dir, 'inference_results')
        out_path_coupled = os.path.join(test_opts.exp_dir, 'inference_coupled')

    os.makedirs(out_path_results, exist_ok=True)
    os.makedirs(out_path_coupled, exist_ok=True)
    args = test_opts

    # update test options with options used during training
    ckpt = torch.load(test_opts.checkpoint_path, map_location='cpu')
    opts = ckpt['opts']
    opts.update(vars(test_opts))
    if 'learn_in_w' not in opts:
        opts['learn_in_w'] = False
    if 'output_size' not in opts:
        opts['output_size'] = 1024
    opts = Namespace(**opts)

    net = pSp(opts)
    net.eval()
    net.cuda()

    print('Loading dataset for {}'.format(opts.dataset_type))
    dataset_args = data_configs.DATASETS[opts.dataset_type]
    transforms_dict = dataset_args['transforms'](opts).get_transforms()
    dataset = InferenceDataset(root=opts.data_path,
                               transform=transforms_dict['transform_inference'],
                               opts=opts)
    dataloader = DataLoader(dataset,
                            batch_size=opts.test_batch_size,
                            shuffle=False,
                            num_workers=int(opts.test_workers),
                            drop_last=True)

    if opts.n_images is None:
        opts.n_images = len(dataset)

    # Check if latents exist
    latents_file_path = os.path.join(args.exp_dir, 'latents.pt')
    opts.latents_file_path = latents_file_path
    if args.inter_num != 0:
        if not os.path.exists(latents_file_path):
            latent_codes = get_all_latents(net, dataloader, args.n_images, is_cars=False)
            torch.save(latent_codes, latents_file_path)
        else:
            latent_codes = torch.load(latents_file_path).to(device)
        inter_num = args.inter_num + 2
        n = latent_codes.shape[0]
        new_latent_codes = torch.zeros((n * int(inter_num / 2), latent_codes.shape[1], latent_codes.shape[2])).to(device)
        count = 0
        for i in range(0, n, 2):
            j = i + 1
            for w in np.linspace(0, 1, inter_num):
                x = torch.lerp(latent_codes[i], latent_codes[j], w)
                new_latent_codes[count] = x
                count += 1
        latent_codes = new_latent_codes
        args.n_sample = count
        # TODO: use those latent codes to generate images
        generator = net.decoder
        generator.eval()
        generate_inversions(args, generator, latent_codes, is_cars=False)
        # and then we return
        return

    global_i = 0
    global_time = []
    for input_batch in tqdm(dataloader):
        if global_i >= opts.n_images:
            break
        with torch.no_grad():
            input_cuda = input_batch.cuda().float()
            tic = time.time()
            result_batch = run_on_batch(input_cuda, net, opts)
            toc = time.time()
            global_time.append(toc - tic)

        for i in range(opts.test_batch_size):
            result = tensor2im(result_batch[i])
            im_path = dataset.paths[global_i]

            if opts.couple_outputs or global_i % 100 == 0:
                input_im = log_input_image(input_batch[i], opts)
                resize_amount = (256, 256) if opts.resize_outputs else (opts.output_size, opts.output_size)
                if opts.resize_factors is not None:
                    # for super resolution, save the original, down-sampled, and output
                    source = Image.open(im_path)
                    res = np.concatenate([np.array(source.resize(resize_amount)),
                                          np.array(input_im.resize(resize_amount, resample=Image.NEAREST)),
                                          np.array(result.resize(resize_amount))], axis=1)
                else:
                    # otherwise, save the original and output
                    res = np.concatenate([np.array(input_im.resize(resize_amount)),
                                          np.array(result.resize(resize_amount))], axis=1)
                Image.fromarray(res).save(os.path.join(out_path_coupled, os.path.basename(im_path)))

            im_save_path = os.path.join(out_path_results, os.path.basename(im_path))
            Image.fromarray(np.array(result)).save(im_save_path)

            global_i += 1

    stats_path = os.path.join(opts.exp_dir, 'stats.txt')
    result_str = 'Runtime {:.4f}+-{:.4f}'.format(np.mean(global_time), np.std(global_time))
    print(result_str)

    with open(stats_path, 'w') as f:
        f.write(result_str)

def run_on_batch(inputs, net, opts):
    if opts.latent_mask is None:
        result_batch = net(inputs, randomize_noise=False, resize=opts.resize_outputs)
    else:
        latent_mask = [int(l) for l in opts.latent_mask.split(",")]
        result_batch = []
        for image_idx, input_image in enumerate(inputs):
            # get latent vector to inject into our input image
            vec_to_inject = np.random.randn(1, 512).astype('float32')
            _, latent_to_inject = net(torch.from_numpy(vec_to_inject).to("cuda"),
                                      input_code=True,
                                      return_latents=True)
            # get output image with injected style vector
            res = net(input_image.unsqueeze(0).to("cuda").float(),
                      latent_mask=latent_mask,
                      inject_latent=latent_to_inject,
                      alpha=opts.mix_alpha,
                      resize=opts.resize_outputs)
            result_batch.append(res)
        result_batch = torch.cat(result_batch, dim=0)
    return result_batch

def get_latents(net, x, is_cars=False):
    codes = net.encoder(x)
    if net.opts.start_from_latent_avg:
        if codes.ndim == 2:
            codes = codes + net.latent_avg.repeat(codes.shape[0], 1, 1)[:, 0, :]
        else:
            codes = codes + net.latent_avg.repeat(codes.shape[0], 1, 1)
    if codes.shape[1] == 18 and is_cars:
        codes = codes[:, :16, :]
    return codes

def get_all_latents(net, data_loader, n_images=None, is_cars=False):
    all_latents = []
    i = 0
    with torch.no_grad():
        for batch in data_loader:
            if n_images is not None and i > n_images:
                break
            x = batch
            inputs = x.to(device).float()
            latents = get_latents(net, inputs, is_cars)
            all_latents.append(latents)
            i += len(latents)
    return torch.cat(all_latents)

def save_image(img, save_dir, idx):
    result = tensor2im(img)
    im_save_path = os.path.join(save_dir, f"{idx:05d}.jpg")
    Image.fromarray(np.array(result)).save(im_save_path)

@torch.no_grad()
def generate_inversions(args, g, latent_codes, is_cars=False):
    print('Saving inversion images')
    inversions_directory_path = os.path.join(args.exp_dir, 'inversions')
    os.makedirs(inversions_directory_path, exist_ok=True)
    for i in range(args.n_sample):
        imgs, _ = g([latent_codes[i].unsqueeze(0)], input_is_latent=True, randomize_noise=False, return_latents=True)
        if is_cars:
            imgs = imgs[:, :, 64:448, :]
        save_image(imgs[0], inversions_directory_path, i + 1)

if __name__ == '__main__':
    device = "cuda"
    parser = argparse.ArgumentParser(description="Inference")
    parser.add_argument('--exp_dir', type=str, default="./results/ffhq", help='Path to experiment output directory')
    parser.add_argument('--inter_num', type=int, default=8, help='if not 0, interpolate mode')
    parser.add_argument('--checkpoint_path', default="./pretrained_models/psp_ffhq_encode.pt", type=str, help='Path to pSp model checkpoint')
    parser.add_argument('--data_path', type=str, default='./ffhq-10', help='Path to directory of images to evaluate')
    parser.add_argument('--couple_outputs', action='store_true', help='Whether to also save inputs + outputs side-by-side')
    parser.add_argument('--resize_outputs', action='store_true', help='Whether to resize outputs to 256x256 or keep at 1024x1024')

    parser.add_argument('--test_batch_size', default=5, type=int, help='Batch size for testing and inference')
    parser.add_argument('--test_workers', default=1, type=int, help='Number of test/inference dataloader workers')

    # arguments for style-mixing script
    parser.add_argument('--n_images', type=int, default=None, help='Number of images to output. If None, run on all data')
    parser.add_argument('--n_outputs_to_generate', type=int, default=5, help='Number of outputs to generate per input image.')
    parser.add_argument('--mix_alpha', type=float, default=None, help='Alpha value for style-mixing')
    parser.add_argument('--latent_mask', type=str, default=None, help='Comma-separated list of latents to perform style-mixing with')

    # arguments for super-resolution
    parser.add_argument('--resize_factors', type=str, default=None,
                                help='Downsampling factor for super-res (should be a single value for inference).')
    args = parser.parse_args()
    run(args)


text:
import numpy as np
from plugins.core.logger import logger

from plugins.core.base_plugin_opt import BasePluginOptimizer

class PluginOptimizer(BasePluginOptimizer):

    def __init__(self, name, hyper_parameters, **kwargs):
        super(PluginOptimizer, self).__init__(name, hyper_parameters, **kwargs)
        logger.info("all tuning hyper parameters: \n{}".format(hyper_parameters))
        self._hyper_parameters = hyper_parameters
        self.cubeIndex = 0
        self.gridCube = self._buildGridCube()
        logger.info("grid cube size: \n{}".format(len(self.gridCube)))

    def _buildGridCube(self):
        hpdict = {}
        for hp in self._hyper_parameters:
            name = hp.get('name')
            type = hp.get('type')
            dataType = hp.get('dataType')
            if type == 'Discrete':
                if dataType == 'DOUBLE':
                    hpdict[name] = hp.get('discreteDbVal')
                if dataType == 'INT':
                    hpdict[name] = hp.get('discreteIntVal')
                if dataType == 'STR':
                    hpdict[name] = hp.get('discreateStrVal')

            if type == 'Range':
                if dataType == 'DOUBLE':
                    hpdict[name] = np.arange(hp.get('minDbVal'),hp.get('maxDbVal'), 0.01)
                if dataType == 'INT':
                    hpdict[name] = list(range(hp.get('minIntVal'), hp.get('maxIntVal'), 1))
        logger.info(hpdict)
        items = sorted(hpdict.items())
        keys, values = zip(*items)
        logger.info(keys)
        logger.info(values)

        grids = []
        from itertools import product
        for v in product(*values):
            params = dict(zip(keys, v))
            grids.append(params)
        return grids

    def search(self, number_samples, last_exp_results=None):

        if self.cubeIndex + number_samples <= len(self.gridCube) - 1:
            suggestions = self.gridCube[self.cubeIndex: self.cubeIndex + number_samples]
            self.cubeIndex += number_samples
        elif self.cubeIndex < len(self.gridCube) - 1:
            suggestions = self.gridCube[self.cubeIndex:]
            self.cubeIndex = len(self.gridCube) - 1
        else:
            suggestions = []

        return suggestions