text:
# Copyright 2018 The Cirq Developers
#
# 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
#
#     https://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.

import numpy as np
import pytest

import cirq

@pytest.mark.parametrize('num_qubits', [1, 2, 4])
def test_measure_init(num_qubits):
    assert cirq.MeasurementGate(num_qubits).num_qubits() == num_qubits
    assert cirq.MeasurementGate(num_qubits, key='a').key == 'a'
    assert cirq.MeasurementGate(num_qubits, key='a').mkey == cirq.MeasurementKey('a')
    assert cirq.MeasurementGate(num_qubits, key=cirq.MeasurementKey('a')).key == 'a'
    assert cirq.MeasurementGate(num_qubits, key=cirq.MeasurementKey('a')) == cirq.MeasurementGate(
        num_qubits, key='a'
    )
    assert cirq.MeasurementGate(num_qubits, invert_mask=(True,)).invert_mask == (True,)
    assert cirq.qid_shape(cirq.MeasurementGate(num_qubits)) == (2,) * num_qubits
    assert cirq.qid_shape(cirq.MeasurementGate(3, qid_shape=(1, 2, 3))) == (1, 2, 3)
    assert cirq.qid_shape(cirq.MeasurementGate(qid_shape=(1, 2, 3))) == (1, 2, 3)
    with pytest.raises(ValueError, match='len.* >'):
        cirq.MeasurementGate(5, invert_mask=(True,) * 6)
    with pytest.raises(ValueError, match='len.* !='):
        cirq.MeasurementGate(5, qid_shape=(1, 2))
    with pytest.raises(ValueError, match='Specify either'):
        cirq.MeasurementGate()

@pytest.mark.parametrize('num_qubits', [1, 2, 4])
def test_has_stabilizer_effect(num_qubits):
    assert cirq.has_stabilizer_effect(cirq.MeasurementGate(num_qubits))

def test_measurement_eq():
    eq = cirq.testing.EqualsTester()
    eq.make_equality_group(
        lambda: cirq.MeasurementGate(1, ''),
        lambda: cirq.MeasurementGate(1, '', invert_mask=()),
        lambda: cirq.MeasurementGate(1, '', qid_shape=(2,)),
    )
    eq.add_equality_group(cirq.MeasurementGate(1, 'a'))
    eq.add_equality_group(cirq.MeasurementGate(1, 'a', invert_mask=(True,)))
    eq.add_equality_group(cirq.MeasurementGate(1, 'a', invert_mask=(False,)))
    eq.add_equality_group(cirq.MeasurementGate(1, 'b'))
    eq.add_equality_group(cirq.MeasurementGate(2, 'a'))
    eq.add_equality_group(cirq.MeasurementGate(2, ''))
    eq.add_equality_group(
        cirq.MeasurementGate(3, 'a'), cirq.MeasurementGate(3, 'a', qid_shape=(2, 2, 2))
    )
    eq.add_equality_group(cirq.MeasurementGate(3, 'a', qid_shape=(1, 2, 3)))

def test_measurement_full_invert_mask():
    assert cirq.MeasurementGate(1, 'a').full_invert_mask() == (False,)
    assert cirq.MeasurementGate(2, 'a', invert_mask=(False, True)).full_invert_mask() == (
        False,
        True,
    )
    assert cirq.MeasurementGate(2, 'a', invert_mask=(True,)).full_invert_mask() == (True, False)

@pytest.mark.parametrize('use_protocol', [False, True])
@pytest.mark.parametrize(
    'gate',
    [
        cirq.MeasurementGate(1, 'a'),
        cirq.MeasurementGate(1, 'a', invert_mask=(True,)),
        cirq.MeasurementGate(1, 'a', qid_shape=(3,)),
        cirq.MeasurementGate(2, 'a', invert_mask=(True, False), qid_shape=(2, 3)),
    ],
)
def test_measurement_with_key(use_protocol, gate):
    if use_protocol:
        gate1 = cirq.with_measurement_key_mapping(gate, {'a': 'b'})
    else:
        gate1 = gate.with_key('b')
    assert gate1.key == 'b'
    assert gate1.num_qubits() == gate.num_qubits()
    assert gate1.invert_mask == gate.invert_mask
    assert cirq.qid_shape(gate1) == cirq.qid_shape(gate)
    if use_protocol:
        gate2 = cirq.with_measurement_key_mapping(gate, {'a': 'a'})
    else:
        gate2 = gate.with_key('a')
    assert gate2 == gate

@pytest.mark.parametrize(
    'num_qubits, mask, bits, flipped',
    [
        (1, (), [0], (True,)),
        (3, (False,), [1], (False, True)),
        (3, (False, False), [0, 2], (True, False, True)),
    ],
)
def test_measurement_with_bits_flipped(num_qubits, mask, bits, flipped):
    gate = cirq.MeasurementGate(num_qubits, key='a', invert_mask=mask, qid_shape=(3,) * num_qubits)

    gate1 = gate.with_bits_flipped(*bits)
    assert gate1.key == gate.key
    assert gate1.num_qubits() == gate.num_qubits()
    assert gate1.invert_mask == flipped
    assert cirq.qid_shape(gate1) == cirq.qid_shape(gate)

    # Flipping bits again restores the mask (but may have extended it).
    gate2 = gate1.with_bits_flipped(*bits)
    assert gate2.full_invert_mask() == gate.full_invert_mask()

def test_qudit_measure_qasm():
    assert (
        cirq.qasm(
            cirq.measure(cirq.LineQid(0, 3), key='a'),
            args=cirq.QasmArgs(),
            default='not implemented',
        )
        == 'not implemented'
    )

def test_qudit_measure_quil():
    q0 = cirq.LineQid(0, 3)
    qubit_id_map = {q0: '0'}
    assert (
        cirq.quil(
            cirq.measure(q0, key='a'),
            formatter=cirq.QuilFormatter(qubit_id_map=qubit_id_map, measurement_id_map={}),
        )
        == None
    )

def test_measurement_gate_diagram():
    # Shows key.
    assert cirq.circuit_diagram_info(cirq.MeasurementGate(1)) == cirq.CircuitDiagramInfo(("M('')",))
    assert cirq.circuit_diagram_info(
        cirq.MeasurementGate(1, key='test')
    ) == cirq.CircuitDiagramInfo(("M('test')",))

    # Uses known qubit count.
    assert (
        cirq.circuit_diagram_info(
            cirq.MeasurementGate(3),
            cirq.CircuitDiagramInfoArgs(
                known_qubits=None,
                known_qubit_count=3,
                use_unicode_characters=True,
                precision=None,
                qubit_map=None,
            ),
        )
        == cirq.CircuitDiagramInfo(("M('')", 'M', 'M'))
    )

    # Shows invert mask.
    assert cirq.circuit_diagram_info(
        cirq.MeasurementGate(2, invert_mask=(False, True))
    ) == cirq.CircuitDiagramInfo(("M('')", "!M"))

    # Omits key when it is the default.
    a = cirq.NamedQubit('a')
    b = cirq.NamedQubit('b')
    cirq.testing.assert_has_diagram(
        cirq.Circuit(cirq.measure(a, b)),
        """
a: ───M───
      │
b: ───M───
""",
    )
    cirq.testing.assert_has_diagram(
        cirq.Circuit(cirq.measure(a, b, invert_mask=(True,))),
        """
a: ───!M───
      │
b: ───M────
""",
    )
    cirq.testing.assert_has_diagram(
        cirq.Circuit(cirq.measure(a, b, key='test')),
        """
a: ───M('test')───
      │
b: ───M───────────
""",
    )

def test_measurement_channel():
    np.testing.assert_allclose(
        cirq.kraus(cirq.MeasurementGate(1)),
        (np.array([[1, 0], [0, 0]]), np.array([[0, 0], [0, 1]])),
    )
    # yapf: disable
    np.testing.assert_allclose(
            cirq.kraus(cirq.MeasurementGate(2)),
            (np.array([[1, 0, 0, 0],
                       [0, 0, 0, 0],
                       [0, 0, 0, 0],
                       [0, 0, 0, 0]]),
             np.array([[0, 0, 0, 0],
                       [0, 1, 0, 0],
                       [0, 0, 0, 0],
                       [0, 0, 0, 0]]),
             np.array([[0, 0, 0, 0],
                       [0, 0, 0, 0],
                       [0, 0, 1, 0],
                       [0, 0, 0, 0]]),
             np.array([[0, 0, 0, 0],
                       [0, 0, 0, 0],
                       [0, 0, 0, 0],
                       [0, 0, 0, 1]])))
    np.testing.assert_allclose(
            cirq.kraus(cirq.MeasurementGate(2, qid_shape=(2, 3))),
            (np.diag([1, 0, 0, 0, 0, 0]),
             np.diag([0, 1, 0, 0, 0, 0]),
             np.diag([0, 0, 1, 0, 0, 0]),
             np.diag([0, 0, 0, 1, 0, 0]),
             np.diag([0, 0, 0, 0, 1, 0]),
             np.diag([0, 0, 0, 0, 0, 1])))
    # yapf: enable

def test_measurement_qubit_count_vs_mask_length():
    a = cirq.NamedQubit('a')
    b = cirq.NamedQubit('b')
    c = cirq.NamedQubit('c')

    _ = cirq.MeasurementGate(num_qubits=1, invert_mask=(True,)).on(a)
    _ = cirq.MeasurementGate(num_qubits=2, invert_mask=(True, False)).on(a, b)
    _ = cirq.MeasurementGate(num_qubits=3, invert_mask=(True, False, True)).on(a, b, c)
    with pytest.raises(ValueError):
        _ = cirq.MeasurementGate(num_qubits=1, invert_mask=(True, False)).on(a)
    with pytest.raises(ValueError):
        _ = cirq.MeasurementGate(num_qubits=3, invert_mask=(True, False, True)).on(a, b)

def test_consistent_protocols():
    for n in range(1, 5):
        gate = cirq.MeasurementGate(num_qubits=n)
        cirq.testing.assert_implements_consistent_protocols(gate)

        gate = cirq.MeasurementGate(num_qubits=n, qid_shape=(3,) * n)
        cirq.testing.assert_implements_consistent_protocols(gate)

def test_op_repr():
    a, b = cirq.LineQubit.range(2)
    assert repr(cirq.measure(a)) == 'cirq.measure(cirq.LineQubit(0))'
    assert repr(cirq.measure(a, b)) == ('cirq.measure(cirq.LineQubit(0), cirq.LineQubit(1))')
    assert repr(cirq.measure(a, b, key='out', invert_mask=(False, True))) == (
        "cirq.measure(cirq.LineQubit(0), cirq.LineQubit(1), "
        "key='out', "
        "invert_mask=(False, True))"
    )
    assert repr(
        cirq.measure(
            a, b, key=cirq.MeasurementKey(name='out', path=('a', 'b')), invert_mask=(False, True)
        )
    ) == (
        "cirq.measure(cirq.LineQubit(0), cirq.LineQubit(1), "
        "key=cirq.MeasurementKey(path=('a', 'b'), name='out'), "
        "invert_mask=(False, True))"
    )

def test_act_on_state_vector():
    a, b = [cirq.LineQubit(3), cirq.LineQubit(1)]
    m = cirq.measure(a, b, key='out', invert_mask=(True,))

    args = cirq.ActOnStateVectorArgs(
        target_tensor=cirq.one_hot(shape=(2, 2, 2, 2, 2), dtype=np.complex64),
        available_buffer=np.empty(shape=(2, 2, 2, 2, 2)),
        qubits=cirq.LineQubit.range(5),
        prng=np.random.RandomState(),
        log_of_measurement_results={},
    )
    cirq.act_on(m, args)
    assert args.log_of_measurement_results == {'out': [1, 0]}

    args = cirq.ActOnStateVectorArgs(
        target_tensor=cirq.one_hot(
            index=(0, 1, 0, 0, 0), shape=(2, 2, 2, 2, 2), dtype=np.complex64
        ),
        available_buffer=np.empty(shape=(2, 2, 2, 2, 2)),
        qubits=cirq.LineQubit.range(5),
        prng=np.random.RandomState(),
        log_of_measurement_results={},
    )
    cirq.act_on(m, args)
    assert args.log_of_measurement_results == {'out': [1, 1]}

    args = cirq.ActOnStateVectorArgs(
        target_tensor=cirq.one_hot(
            index=(0, 1, 0, 1, 0), shape=(2, 2, 2, 2, 2), dtype=np.complex64
        ),
        available_buffer=np.empty(shape=(2, 2, 2, 2, 2)),
        qubits=cirq.LineQubit.range(5),
        prng=np.random.RandomState(),
        log_of_measurement_results={},
    )
    cirq.act_on(m, args)
    assert args.log_of_measurement_results == {'out': [0, 1]}

    with pytest.raises(ValueError, match="already logged to key"):
        cirq.act_on(m, args)

def test_act_on_clifford_tableau():
    a, b = [cirq.LineQubit(3), cirq.LineQubit(1)]
    m = cirq.measure(a, b, key='out', invert_mask=(True,))
    # The below assertion does not fail since it ignores non-unitary operations
    cirq.testing.assert_all_implemented_act_on_effects_match_unitary(m)

    args = cirq.ActOnCliffordTableauArgs(
        tableau=cirq.CliffordTableau(num_qubits=5, initial_state=0),
        qubits=cirq.LineQubit.range(5),
        prng=np.random.RandomState(),
        log_of_measurement_results={},
    )
    cirq.act_on(m, args)
    assert args.log_of_measurement_results == {'out': [1, 0]}

    args = cirq.ActOnCliffordTableauArgs(
        tableau=cirq.CliffordTableau(num_qubits=5, initial_state=8),
        qubits=cirq.LineQubit.range(5),
        prng=np.random.RandomState(),
        log_of_measurement_results={},
    )

    cirq.act_on(m, args)
    assert args.log_of_measurement_results == {'out': [1, 1]}

    args = cirq.ActOnCliffordTableauArgs(
        tableau=cirq.CliffordTableau(num_qubits=5, initial_state=10),
        qubits=cirq.LineQubit.range(5),
        prng=np.random.RandomState(),
        log_of_measurement_results={},
    )
    cirq.act_on(m, args)
    assert args.log_of_measurement_results == {'out': [0, 1]}

    with pytest.raises(ValueError, match="already logged to key"):
        cirq.act_on(m, args)

def test_act_on_stabilizer_ch_form():
    a, b = [cirq.LineQubit(3), cirq.LineQubit(1)]
    m = cirq.measure(a, b, key='out', invert_mask=(True,))
    # The below assertion does not fail since it ignores non-unitary operations
    cirq.testing.assert_all_implemented_act_on_effects_match_unitary(m)

    args = cirq.ActOnStabilizerCHFormArgs(
        state=cirq.StabilizerStateChForm(num_qubits=5, initial_state=0),
        qubits=cirq.LineQubit.range(5),
        prng=np.random.RandomState(),
        log_of_measurement_results={},
    )
    cirq.act_on(m, args)
    assert args.log_of_measurement_results == {'out': [1, 0]}

    args = cirq.ActOnStabilizerCHFormArgs(
        state=cirq.StabilizerStateChForm(num_qubits=5, initial_state=8),
        qubits=cirq.LineQubit.range(5),
        prng=np.random.RandomState(),
        log_of_measurement_results={},
    )

    cirq.act_on(m, args)
    assert args.log_of_measurement_results == {'out': [1, 1]}

    args = cirq.ActOnStabilizerCHFormArgs(
        state=cirq.StabilizerStateChForm(num_qubits=5, initial_state=10),
        qubits=cirq.LineQubit.range(5),
        prng=np.random.RandomState(),
        log_of_measurement_results={},
    )
    cirq.act_on(m, args)
    assert args.log_of_measurement_results == {'out': [0, 1]}

    with pytest.raises(ValueError, match="already logged to key"):
        cirq.act_on(m, args)

def test_act_on_qutrit():
    a, b = [cirq.LineQid(3, dimension=3), cirq.LineQid(1, dimension=3)]
    m = cirq.measure(a, b, key='out', invert_mask=(True,))

    args = cirq.ActOnStateVectorArgs(
        target_tensor=cirq.one_hot(
            index=(0, 2, 0, 2, 0), shape=(3, 3, 3, 3, 3), dtype=np.complex64
        ),
        available_buffer=np.empty(shape=(3, 3, 3, 3, 3)),
        qubits=cirq.LineQid.range(5, dimension=3),
        prng=np.random.RandomState(),
        log_of_measurement_results={},
    )
    cirq.act_on(m, args)
    assert args.log_of_measurement_results == {'out': [2, 2]}

    args = cirq.ActOnStateVectorArgs(
        target_tensor=cirq.one_hot(
            index=(0, 1, 0, 2, 0), shape=(3, 3, 3, 3, 3), dtype=np.complex64
        ),
        available_buffer=np.empty(shape=(3, 3, 3, 3, 3)),
        qubits=cirq.LineQid.range(5, dimension=3),
        prng=np.random.RandomState(),
        log_of_measurement_results={},
    )
    cirq.act_on(m, args)
    assert args.log_of_measurement_results == {'out': [2, 1]}

    args = cirq.ActOnStateVectorArgs(
        target_tensor=cirq.one_hot(
            index=(0, 2, 0, 1, 0), shape=(3, 3, 3, 3, 3), dtype=np.complex64
        ),
        available_buffer=np.empty(shape=(3, 3, 3, 3, 3)),
        qubits=cirq.LineQid.range(5, dimension=3),
        prng=np.random.RandomState(),
        log_of_measurement_results={},
    )
    cirq.act_on(m, args)
    assert args.log_of_measurement_results == {'out': [0, 2]}

max_stars_repo_name: stubbi/Cirq

max_issues_repo_name: stubbi/Cirq

max_forks_repo_name: stubbi/Cirq


text:
import numpy as np
import scipy.special as ss
import matplotlib.pyplot as plt
from matplotlib import colors as mcolors
from cycler import cycler

def fccolorblind(number_of_plots):
    prop_cycle=plt.rcParams['axes.prop_cycle']
    clist=prop_cycle.by_key()['color']

    if(number_of_plots<=4):
        colorscheme=['#4477AA','#CC6677','#DDCC77','#117733']
        plt.rcParams['axes.prop_cycle'] = cycler('color', colorscheme)
    elif(number_of_plots>4 and number_of_plots<=12):
        colorscheme=['#332288','#88CCEE','#117733','#DDCC77','#CC6677','#AA4499','#44AA99','#999933','#882255','#661100','#6699CC','#AA4466']
        plt.rcParams['axes.prop_cycle'] = cycler('color', colorscheme)
    else:
        colorscheme=clist
        print("OUT OF RANGE[1-12] : COLORBLIND MODE DEACTIVATED ---> DEFAULT MODE")
    return(colorscheme)

def huescale(number_of_plots, *option):
    #SET DEFAULT VALUES IF NO OPTIONAL ARGUMENT
    hue='None'
    #OPTIONS
    for argument in option:
        if argument=='blue':
            hue='blue'
        if argument=='bluegreen':
            hue='bluegreen'
        if argument=='green':
            hue='green'
        if argument=='gold':
            hue='gold'
        if argument=='brown':
            hue='brown'
        if argument=='rose':
            hue='rose'
        if argument=='purple':
            hue='purple'

    if(number_of_plots<=3):
        if hue=='blue':
            colorscheme=['#114477','#4477AA','#77AADD']
            plt.rcParams['axes.prop_cycle'] = cycler('color', colorscheme)
        if hue=='bluegreen':
            colorscheme=['#117777','#44AAAA','#77CCCC']
            plt.rcParams['axes.prop_cycle'] = cycler('color', colorscheme)
        if hue=='green':
            colorscheme=['#117744','#44AA77','#88CCAA']
            plt.rcParams['axes.prop_cycle'] = cycler('color', colorscheme)
        if hue=='gold':
            colorscheme=['#777711','#AAAA44','#DDDD77']
            plt.rcParams['axes.prop_cycle'] = cycler('color', colorscheme)
        if hue=='brown':
            colorscheme=['#774411','#AA7744','#DDAA77']
            plt.rcParams['axes.prop_cycle'] = cycler('color', colorscheme)
        if hue=='rose':
            colorscheme=['#771122','#AA4455','#DD7788']
            plt.rcParams['axes.prop_cycle'] = cycler('color', colorscheme)
        if hue=='purple':
            colorscheme=['#771155','#AA4488','#CC99BB']
            plt.rcParams['axes.prop_cycle'] = cycler('color', colorscheme)
        if hue=='None':
            colorscheme=['#D95F0E','#FEC44F','#FFF7BC']
            plt.rcParams['axes.prop_cycle'] = cycler('color', colorscheme)

    prop_cycle=plt.rcParams['axes.prop_cycle']
    clist=prop_cycle.by_key()['color']

    if(number_of_plots==4):
        colorscheme=['#CC4C02','#FB9A29','#FED98E','#FFFBD5']
        plt.rcParams['axes.prop_cycle'] = cycler('color', colorscheme)
    if(number_of_plots==5):
        colorscheme=['#993404','#D95F0E','#FB9A29','#FED98E','#FFFBD5']
        plt.rcParams['axes.prop_cycle'] = cycler('color', colorscheme)
    if(number_of_plots==6):
        colorscheme=['#993404','#D95F0E','#FB9A29','#FEC44F','#FEE391','#FFFBD5']
        plt.rcParams['axes.prop_cycle'] = cycler('color', colorscheme)
    if(number_of_plots==7):
        colorscheme=['#8C2D04','#CC4C02','#EC7014','#FB9A29','#FEC44F','#FEE391','#FFFBD5']
        plt.rcParams['axes.prop_cycle'] = cycler('color', colorscheme)
    if(number_of_plots==8):
        colorscheme=['#8C2D04','#CC4C02','#EC7014','#FB9A29','#FEC44F','#FEE391','#FFF7BC','#FFFFE5']
        plt.rcParams['axes.prop_cycle'] = cycler('color', colorscheme)
    if(number_of_plots==9):
        colorscheme=['#662506','#993404','#CC4C02','#EC7014','#FB9A29','#FEC44F','#FEE391','#FFF7BC','#FFFFE5']
        plt.rcParams['axes.prop_cycle'] = cycler('color', colorscheme)
    if(number_of_plots>3 and number_of_plots<=9 and hue!='None'):
        print("ONLY OCHERSCALE FOR MORE THAN 3 PLOTS")
    if(number_of_plots>9):
        colorscheme=clist
        print("OUT OF RANGE[1-9] : COLORBLIND MODE DEACTIVATED ---> DEFAULT MODE")
    return(colorscheme)

def rbscale(number_of_plots):
    prop_cycle=plt.rcParams['axes.prop_cycle']
    clist=prop_cycle.by_key()['color']

    if(number_of_plots==3):
        colorscheme=['#99C7EC','#FFFAD2','#F5A275']
        plt.rcParams['axes.prop_cycle'] = cycler('color', colorscheme)
    elif(number_of_plots==4):
        colorscheme=['#008BCE','#B4DDF7','#F9BD7E','#D03232']
        plt.rcParams['axes.prop_cycle'] = cycler('color', colorscheme)
    elif(number_of_plots==5):
        colorscheme=['#008BCE','#B4DDF7','#FFFAD2','#F9BD7E','#D03232']
        plt.rcParams['axes.prop_cycle'] = cycler('color', colorscheme)
    elif(number_of_plots==6):
        colorscheme=['#3A89C9','#99C7EC','#E6F5FE','#FFE3AA','#F5A275','#D24D3E']
        plt.rcParams['axes.prop_cycle'] = cycler('color', colorscheme)
    elif(number_of_plots==7):
        colorscheme=['#3A89C9','#99C7EC','#E6F5FE','#FFFAD2','#FFE3AA','#F5A275','#D24D3E']
        plt.rcParams['axes.prop_cycle'] = cycler('color', colorscheme)
    elif(number_of_plots==8):
        colorscheme=['#3A89C9','#77B7E5','#B4DDF7','#E6F5FE','#FFE3AA','#F9BD7E','#ED875E','#D24D3E']
        plt.rcParams['axes.prop_cycle'] = cycler('color', colorscheme)
    elif(number_of_plots==9):
        colorscheme=['#3A89C9','#77B7E5','#B4DDF7','#E6F5FE','#FFFAD2','#FFE3AA','#F9BD7E','#ED875E','#D24D3E']
        plt.rcParams['axes.prop_cycle'] = cycler('color', colorscheme)
    elif(number_of_plots==10):
        colorscheme=['#3D52A1','#3A89C9','#77B7E5','#B4DDF7','#E6F5FE','#FFE3AA','#F9BD7E','#ED875E','#D24D3E','#AE1C3E']
        plt.rcParams['axes.prop_cycle'] = cycler('color', colorscheme)
    elif(number_of_plots==11):
        colorscheme=['#3D52A1','#3A89C9','#77B7E5','#B4DDF7','#E6F5FE','#FFFAD2','#FFE3AA','#F9BD7E','#ED875E','#D24D3E','#AE1C3E']
        plt.rcParams['axes.prop_cycle'] = cycler('color', colorscheme)
    else:
        colorscheme=clist
        print("OUT OF RANGE[3-11] : COLORBLIND MODE DEACTIVATED ---> DEFAULT MODE")
    return(colorscheme)

def rainbow(number_of_plots):
    prop_cycle=plt.rcParams['axes.prop_cycle']
    clist=prop_cycle.by_key()['color']

    if(number_of_plots==4):
        colorscheme=['#404096','#57A3AD','#DEA73A','#D92120']
        plt.rcParams['axes.prop_cycle'] = cycler('color', colorscheme)
    elif(number_of_plots==5):
        colorscheme=['#404096','#529DB7','#7DB874','#E39C37','#D92120']
        plt.rcParams['axes.prop_cycle'] = cycler('color', colorscheme)
    elif(number_of_plots==6):
        colorscheme=['#404096','#498CC2','#63AD99','#BEBC48','#E68B33','#D92120']
        plt.rcParams['axes.prop_cycle'] = cycler('color', colorscheme)
    elif(number_of_plots==7):
        colorscheme=['#781C81','#3F60AE','#539EB6','#6DB388','#CAB843','#E78532','#D92120']
        plt.rcParams['axes.prop_cycle'] = cycler('color', colorscheme)
    elif(number_of_plots==8):
        colorscheme=['#781C81','#3F56A7','#4B91C0','#5FAA9F','#91BD61','#D8AF3D','#E77C30','#D92120']
        plt.rcParams['axes.prop_cycle'] = cycler('color', colorscheme)
    elif(number_of_plots==9):
        colorscheme=['#781C81','#3F4EA1','#4683C1','#57A3AD','#6DB388','#B1BE4E','#DFA53A','#E7742F','#D92120']
        plt.rcParams['axes.prop_cycle'] = cycler('color', colorscheme)
    elif(number_of_plots==10):
        colorscheme=['#781C81','#3F479B','#4277BD','#529DB7','#62AC9B','#86BB6A','#C7B944','#E39C37','#E76D2E','#D92120']
        plt.rcParams['axes.prop_cycle'] = cycler('color', colorscheme)
    elif(number_of_plots==11):
        colorscheme=['#781C81','#404096','#416CB7','#4D95BE','#5BA7A7','#6EB387','#A1BE56','#D3B33F','#E59435','#E6682D','#D92120']
        plt.rcParams['axes.prop_cycle'] = cycler('color', colorscheme)
    elif(number_of_plots==12):
        colorscheme=['#781C81','#413B93','#4065B1','#488BC2','#55A1B1','#63AD99','#7FB972','#B5BD4C','#D9AD3C','#E68E34','#E6642C','#D92120']
        plt.rcParams['axes.prop_cycle'] = cycler('color', colorscheme)
    else:
        colorscheme=clist
        print("OUT OF RANGE[4-12] : COLORBLIND MODE DEACTIVATED ---> DEFAULT MODE")
    return(colorscheme)

def colorfunction(nfiles,function,printed,*options):
    solid = (0, ())
    loosely_dotted = (0, (1, 10))
    dotted = (0, (1, 5))
    densely_dotted = (0, (1, 1))

    loosely_dashed = (0, (5, 10))
    dashed = (0, (5, 5))
    densely_dashed = (0, (5, 1))

    loosely_dashdotted = (0, (3, 10, 1, 10))
    dashdotted = (0, (3, 5, 1, 5))
    densely_dashdotted = (0, (3, 1, 1, 1))

    loosely_dashdotdotted = (0, (3, 10, 1, 10, 1, 10))
    dashdotdotted = (0, (3, 5, 1, 5, 1, 5))
    densely_dashdotdotted = (0, (3, 1, 1, 1, 1, 1))

    color=[]
    style=[]
    estyle=[]
    for argument in options:
        if argument=='blue':
            option='blue'
        if argument=='bluegreen':
            option='bluegreen'
        if argument=='green':
            option='green'
        if argument=='gold':
            option='gold'
        if argument=='brown':
            option='brown'
        if argument=='rose':
            option='rose'
        if argument=='purple':
            option='purple'

    if printed=='c':
        estyle=[solid]*nfiles
        if function=='fccolorblind':
            color=fccolorblind(nfiles)
        elif function=='rbscale':
            color=rbscale(nfiles)
        elif function=='rainbow':
            color=rainbow(nfiles)
        elif function=='huescale':
            color=huescale(nfiles,*options)

    if (printed=='b&w'):
        color=['black']*nfiles
    if (printed=='blue'):
        color=['#4477AA']*nfiles
    if (printed=='red'):
        color=['#CC6677']*nfiles
    if (printed=='yellow'):
        color=['#DDCC77']*nfiles
    if (printed=='green'):
        color=['#117733']*nfiles
    if (printed=='b&w' or printed=='blue'  or printed=='red' or printed=='yellow' or printed=='green'):
        style = [solid,dashed,dotted,dashdotted,dashdotdotted,densely_dashed,densely_dotted,densely_dashdotted,densely_dashdotdotted,loosely_dashed,loosely_dotted,loosely_dashdotted,loosely_dashdotdotted]
        if(nfiles > 13):
            print('CAREFUL : MAXIMUM 13 DIFFERENT LINESTYLES')
            style = style*int(np.ceil(nfiles/13))
        estyle = style[0:nfiles]
        default_cycler=(cycler(color=color)+cycler(linestyle=estyle))
        plt.rc('axes', prop_cycle=default_cycler)

    return(color,estyle)

def cbmap(function):
    x=np.linspace(0.,1.,1000)
    if function=='rbscale':
        red=0.237-2.13*x+26.92*x**2-65.5*x**3+63.5*x**4-22.36*x**5
        green=((0.572+1.524*x-1.811*x**2)/(1.-0.291*x+0.1574*x**2))**2
        blue=(1./(1.579-4.03*x+12.92*x**2-31.4*x**3+48.6*x**4-23.36*x**5))
    if function=='rainbow':
        red = (0.472-0.567*x+4.05*x**2)/(1.+8.72*x-19.17*x**2+14.1*x**3)
        green = 0.108932-1.22635*x+27.284*x**2-98.577*x**3+163.3*x**4-131.395*x**5+40.634*x**6
        blue = 1./(1.97+3.54*x-68.5*x**2+243*x**3-297*x**4+125*x**5)
    if function=='huescale':
        red = 1.-0.392*(1.+ss.erf((x-0.869)/0.255))
        green = 1.021-0.456*(1.+ss.erf((x-0.527)/0.376))
        blue = 1.-0.493*(1.+ss.erf((x-0.272)/0.309))

    redline=[]
    greenline=[]
    blueline=[]
    for i in range(len(x)):
        redline.append((x[i],red[i],red[i]))
        greenline.append((x[i],green[i],green[i]))
        blueline.append((x[i],blue[i],blue[i]))

    cdict = {'red':   redline,
             'green': greenline,
             'blue': blueline}

    cbcmap = mcolors.LinearSegmentedColormap('cmap_%s' %(function), cdict)
    return(cbcmap)

def cbmap_discrete(function):
    cbcmap = cbmap(function)

    cmaplist = [cbcmap(i) for i in range(cbcmap.N)]
    cbcmap_n = cbcmap.from_list('cbcmap_n', cmaplist, cbcmap.N)
    return(cbcmap_n)

def norm_discrete(data, function, nbin):
    bounds=np.linspace(data.min(),data.max(),nbin+1)
    cbcmap_n = cbmap_discrete(function)
    norm=mcolors.BoundaryNorm(bounds,cbcmap_n.N)
    if(nbin>=cbcmap_n.N):
        print('CAREFUL : ONLY %d DIFFERENT COLORS IN THIS COLORMAP' %(cbcmap_n.N))
    return(norm)

def reverse_colormap(cmap, name = 'my_cmap_r'):
    reverse = []
    k = []

    for key in cmap._segmentdata:
        k.append(key)
        channel = cmap._segmentdata[key]
        data = []
        for t in channel:
            data.append((1-t[0],t[2],t[1]))
        reverse.append(sorted(data))

    LinearL = dict(zip(k,reverse))
    my_cmap_r = mcolors.LinearSegmentedColormap(name, LinearL)
    return my_cmap_r

def mapping(fig,ax,data2d,function,extent):
    im=ax.imshow(data2d, cmap=cbmap(function), aspect='auto', extent=extent)
    fig.colorbar(im)

def mapping_discrete(fig,ax,data2d,function,extent,nbin):
    im = ax.imshow(data2d, cmap=cbmap_discrete(function), norm=norm_discrete(data2d,function,nbin), aspect='auto', extent=extent)
    fig.colorbar(im)

def test_fccolorblind(ny):
    nx=100
    x=np.linspace(0,10, nx)
    y=np.zeros((ny,nx), dtype=int)
    color=fccolorblind(ny)

    for i in range(ny):
        for j in range(nx):
            y[i][j]=x[j]+i
        # plt.plot(x,y[i], color[i], linewidth=2.0)
        plt.plot(x,y[i], linewidth=2.0)

    plt.show()

def test_huescale(ny, *option):
    #SET DEFAULT VALUES IF NO OPTIONAL ARGUMENT
    hue='None'
    #OPTION
    for argument in option:
        if argument=='blue':
            hue='blue'
        if argument=='bluegreen':
            hue='bluegreen'
        if argument=='green':
            hue='green'
        if argument=='gold':
            hue='gold'
        if argument=='brown':
            hue='brown'
        if argument=='rose':
            hue='rose'
        if argument=='purple':
            hue='purple'

    nx=100
    x=np.linspace(0,10, nx)
    y=np.zeros((ny,nx), dtype=int)
    color=huescale(ny, *option)

    for i in range(ny):
        for j in range(nx):
            y[i][j]=x[j]+i
        # plt.plot(x,y[i], color[i], linewidth=2.0)
        plt.plot(x,y[i], linewidth=2.0)

    plt.show()

def test_rbscale(ny):
    nx=100
    x=np.linspace(0,10, nx)
    y=np.zeros((ny,nx), dtype=int)
    color=rbscale(ny)

    for i in range(ny):
        for j in range(nx):
            y[i][j]=x[j]+i
        # plt.plot(x,y[i], color[i], linewidth=2.0)
        plt.plot(x,y[i], linewidth=2.0)

    plt.show()

def test_rainbow(ny):
    nx=100
    x=np.linspace(0,10, nx)
    y=np.zeros((ny,nx), dtype=int)
    color=rainbow(ny)

    for i in range(ny):
        for j in range(nx):
            y[i][j]=x[j]+i
        # plt.plot(x,y[i], color[i], linewidth=2.0)
        plt.plot(x,y[i], linewidth=2.0)

    plt.show()

def test_mapping(function):
    fig,ax=plt.subplots()

    r = np.arange(-np.pi, np.pi, 0.1)
    t = np.arange(0, 2*np.pi, 0.1)
    extent = [r[0],r[-1],t[0],t[-1]]
    X, Y = np.meshgrid(r, t)
    data = np.cos(X) * np.sin(Y) * 10

    mapping(fig,ax,data,function,extent)
    plt.show()

def test_mapping_discrete(function,nbin):
    fig,ax=plt.subplots()

    r = np.arange(-np.pi, np.pi, 0.1)
    t = np.arange(0, 2*np.pi, 0.1)
    extent = [r[0],r[-1],t[0],t[-1]]
    X, Y = np.meshgrid(r, t)
    data = np.cos(X) * np.sin(Y) * 10

    mapping_discrete(fig,ax,data,function,extent,nbin)
    plt.show()

ext: py

reason: import numpy,import scipy


text:
# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
from eight import *

from ..temporal_distribution import TemporalDistribution as TD
import numpy as np
import unittest

class TemporalDistributionTestCase(unittest.TestCase):
    def create_td(self):
        return TD(np.arange(0,5, dtype='timedelta64[Y]'), np.ones(5) * 2)

    def test_init(self):
        """test TD inizialization"""
        #empty
        with self.assertRaises(ValueError):
            TD(None, None)
        #uneven lenght
        with self.assertRaises(ValueError):
            TD(np.arange(5), np.array(2, 2, 2, 2))
        #float instead datetime
        with self.assertRaises(ValueError):
            TD(np.arange(5), np.ones(5) * 2)

    def test_mul_td(self):
        """test __mul__ (i.e. convolution)"""
        td = self.create_td()

        #test timedelta
        td2 = TD(np.array((-1, 0, 1), dtype='timedelta64[Y]'), np.ones(3).astype(float))
        #test datetime
        td3 = TD(np.array((-1, 0, 1), dtype='datetime64[Y]'), np.ones(3).astype(float))
        #convolution only possible with timedelta
        with self.assertRaises(AssertionError):
            td * td3
        with self.assertRaises(AssertionError):
            td3 * td

        multiplied = td * td2
        #check result mul.times (allclose does not work with datetime)
        self.assertTrue(np.array_equal(
            np.arange(-1, 6, dtype='timedelta64[Y]').astype('timedelta64[s]'),
            multiplied.times)
        )
        #check sum of values
        self.assertEqual(
            td.values.sum() * td2.values.sum(),
            multiplied.values.sum()
        )
        #check result array mul.values
        self.assertTrue(np.allclose(
            np.array((2.,  4.,  6.,  6.,  6.,  4.,  2.)),
            multiplied.values
        ))

    def test_div_td(self):
        """check unpossible division between tds"""
        td = self.create_td()
        td2 = TD(np.array((-1, 0, 1), dtype='timedelta64[Y]'), np.ones(3).astype(float))
        with self.assertRaises(ValueError):
            td / td2

    def test_div_int(self):
        """check possible division between td and int"""
        td = self.create_td()
        divided = td / 2.
        self.assertTrue(np.array_equal(
            np.arange(0,5, dtype='timedelta64[Y]').astype('timedelta64[s]'),
            divided.times
        ))

    def test_mul_int(self):
        """check mul between td and int"""
        td = self.create_td() * 5
        self.assertTrue(np.array_equal(
            td.times,
            np.arange(0,5, dtype='timedelta64[Y]').astype('timedelta64[s]'),
        ))
        self.assertTrue(np.allclose(
            td.values,
            np.ones(5) * 10
        ))

    def test_add_integer(self):
        """check add between td and int"""
        td = self.create_td() + 5
        self.assertTrue(np.array_equal(
            td.times,
            np.arange(0,5, dtype='timedelta64[Y]').astype('timedelta64[s]'),
        ))
        self.assertTrue(np.allclose(
            td.values,
            np.ones(5) * 7
        ))

    def test_add_td(self):
        """check add between tds"""
        td = self.create_td()
        td2 = TD(np.array((-1, 0, 1), dtype='timedelta64[Y]'), np.ones(3).astype(float))
        added = td + td2
        self.assertTrue(np.array_equal(
            np.arange(-1, 5, dtype='timedelta64[Y]').astype('timedelta64[s]'),
            added.times
        ))
        self.assertEqual(
            td.values.sum() + td2.values.sum(),
            added.values.sum()
        )
        self.assertTrue(np.allclose(
            np.array((1.,  3.,  3.,  2.,  2.,  2.)),
            added.values
        ))

    def test_iter(self):
        td = iter(self.create_td())
        self.assertEqual(next(td), (np.timedelta64(0,'Y').astype('timedelta64[s]'), 2))
        self.assertEqual(next(td), (np.timedelta64(1,'Y').astype('timedelta64[s]'), 2))
        self.assertEqual(next(td), (np.timedelta64(2,'Y').astype('timedelta64[s]'), 2))
        self.assertEqual(next(td), (np.timedelta64(3,'Y').astype('timedelta64[s]'), 2))
        self.assertEqual(next(td), (np.timedelta64(4,'Y').astype('timedelta64[s]'), 2))
        with self.assertRaises(StopIteration):
            next(td)

    def test_representation(self):
        repr(self.create_td())

    def test_str(self):
        str(self.create_td())

reason: import numpy


text:
#!/usr/bin/env python3

# Script that computes the baselines for a given master based on a stack of baselines
#

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Copyright 2017 California Institute of Technology. ALL RIGHTS RESERVED.
#
# 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.
#
# United States Government Sponsorship acknowledged. This software is subject to
# U.S. export control laws and regulations and has been classified as 'EAR99 NLR'
# (No [Export] License Required except when exporting to an embargoed country,
# end user, or in support of a prohibited end use). By downloading this software,
# the user agrees to comply with all applicable U.S. export laws and regulations.
# The user has the responsibility to obtain export licenses, or other export
# authority as may be required before exporting this software to any 'EAR99'
# embargoed foreign country or citizen of those countries.
#
# Author: David Bekaert
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

import argparse
from glob import glob
import numpy as np
import scipy
import os

# command line parsing of input file
def cmdLineParse():
    '''
    Command line parser.
    '''
    parser = argparse.ArgumentParser(description='baseline re-estimation for a master date')
    parser.add_argument('-i','--input', dest='baseline_dir', type=str,required=True, help='Path to the baseline directory')
    parser.add_argument('-m', '--master_date' ,dest='new_master', type=str, required=True , help='New master date for stack')
    return parser.parse_args()

def baselinegrid(inps):
    """
        Basline files are given as grids
    """
    import gdal

    # parsing the command line inputs
    baseline_dir = inps.baseline_dir
    new_master = int(inps.new_master)

    # check if the baseline grids are all in the same folder or if they are date YYYYMMDD_YYYYMMDD folders.
    baseline_files = glob(os.path.join(baseline_dir,"2*","2*[0-9].vrt"))
    if not baseline_files:
        # try to see if they are all local
        baseline_files = glob(os.path.join(baseline_dir,"2*[0-9].vrt"))
    if not baseline_files:
        # need to raize error as no baseline files where found
        raise ValueError('No Baseline files were found')

    # finding the master baseline grid file
    master_file = False
    for baseline_file in baseline_files:
        date = os.path.basename(baseline_file)
        date = date.split('.vrt')
        date = int(date[0])
        if date == new_master:
            master_file = os.path.join(os.path.dirname(baseline_file),str(date))
    if not master_file:
        raise Exception('Could not find the master baseline grid')

    # generate new baseline grid for each slave and also store the average for overview
    baselines_new = [float(0)]
    dates_new = [new_master]
    for baseline_file in baseline_files:
        date = os.path.basename(baseline_file)
        date = date.split('.vrt')
        date = int(date[0])
        # check if this is a slave date
        if not date == new_master:
            slave_file = os.path.join(os.path.dirname(baseline_file),str(date))
            local_baseline_file = "baselineGRID_" + str(date)
            cmd = "imageMath.py -e='a-b' --a=" + slave_file + " --b=" + master_file + " -o " + local_baseline_file + " -t FLOAT -s BIP"
            os.system(cmd)
            # generating a vrt file as well
            cmd = "isce2gis.py vrt -i " + local_baseline_file
            os.system(cmd)

            # compute the average as well for baseline overview
            if os.path.isfile(local_baseline_file):
                dataset_avg = gdal.Open(local_baseline_file + '.vrt',gdal.GA_ReadOnly)
                stats = dataset_avg.GetRasterBand(1).GetStatistics(0,1)
                average = stats[2]
                baselines_new.append(average)
                dates_new.append(date)

    # convert to numpy arrays
    baselines_new = np.reshape(np.array(baselines_new),(-1,1))
    dates_new = np.reshape(np.array(dates_new),(-1,1))
    temp =np.hstack([dates_new,baselines_new])
    temp = temp[temp[:, 0].argsort()]
    np.savetxt('baseline_overview_new', temp, fmt='%.f %.2f ', delimiter='\t', newline='\n')

    # generate a baseline file for each acquisition
    for counter in range(temp.shape[0]):
        if temp[counter,0] == new_master:
            dir_name = 'master'
        else:
            dir_name = str(int(temp[counter,0]))
        # generate the directory if it does not exist yet
        try:
            os.stat(dir_name)
        except:
            os.mkdir(dir_name)
        np.savetxt(os.path.join(dir_name,'baseline'), [temp[counter,:]], fmt='%.f %.2f ', delimiter='\t', newline='\n')

def baselinefile(inps):
    """
        Baseline files are txt files with a single value in them
    """
    # parsing the command line inputs
    baseline_dir = inps.baseline_dir
    new_master = int(inps.new_master)

    # check if the baseline files are all in the same folder or if they are date YYYYMMDD_YYYYMMDD folders.
    baseline_files = glob(os.path.join(baseline_dir,"2*","2*.txt"))
    if not baseline_files:
        # try to see if they are all local
        baseline_files = glob(os.path.join(baseline_dir,"2*.txt"))

    if not baseline_files:
        # need to raize error as no baseline files where found
        raise ValueError('No Baseline files were found')

    # generate an array of dates
    master = []
    slave = []
    baseline = []
    for baseline_file in baseline_files:
        dates = os.path.basename(baseline_file)
        dates = dates.split('.')[0]
        master.append(int(dates.split('_')[0]))
        slave.append(int(dates.split('_')[1]))

        # read file and either catch a single value or read for specific -perp (average):- string
        file = open(baseline_file,'r')
        file_lines = file.readlines()

        # there is only one line for the baseline
        if len(file_lines)==1:
               baseline.append(float(file_lines[0]))

        # there are multiple lines, only extract the specific string
        else:
            baseline_temp=[]
            for file_line in file_lines:
                if file_line.find("perp (average):") != -1:
                    # getting the string with the value
                    temp = file_line.split("perp (average):")[1]
                    # removing the newline character
                    temp = temp.split("\n")[0]
                    baseline_temp.append(float(temp))
                # take the mean
                baseline.append(np.mean(np.array(baseline_temp)))

    # converting to an numpy array
    baseline = np.reshape(np.array(baseline),(-1,1))
    master = np.reshape(np.array(master),(-1,1))
    slave = np.reshape(np.array(slave),(-1,1))

    # count the number of nan in the baseline
    ix_count = np.count_nonzero(np.isnan(baseline))
    if ix_count>0:
        for ix in range(baseline.shape[0]):
            if np.isnan(baseline[ix])==1:
                print(str(master[ix,0]) + "_" + str(slave[ix,0]))
        # now raize error
        raise ValueError('NaN found for baseline...')

    # generating an array of acquisitions
    dates= np.reshape(np.unique(np.concatenate((master,slave), axis=0)),(-1,1))
    # getting number of baseline combinations and the number of acquisitions
    n_acquistions = dates.shape[0]
    n_combinations = baseline.shape[0]

    #### mapping the baselines to a new master
    # generate the design matrix that maps the baselines to dates
    A = np.zeros((n_combinations,n_acquistions))
    for counter in range(n_combinations):
        pos_master, temp = np.where(dates == master[counter])
        pos_slave, temp = np.where(dates == slave[counter])
        A[counter,pos_master]=-1
        A[counter,pos_slave]=1
        del pos_slave
        del pos_master

    # location of the requested master
    pos_master, temp = np.where(dates == new_master)

    # remove the new master from the design matrix and acquisitions
    A[:,pos_master[0]]=0
    # compute the new baselines
    baselines_new = np.linalg.lstsq(A, baseline)[0]

#   # add the new master back in and write out the file
#   baselines_new = np.concatenate((baselines_new, np.zeros((1,1))))
 #  dates = np.concatenate((dates, [[new_master]]))
    # concatenate together to write single matrix
    temp= np.concatenate((dates, baselines_new), axis=1)
    np.savetxt('baseline_overview', temp, fmt='%.f %.2f ', delimiter='\t', newline='\n')

    # generate a baseline file for each acquisition
    for counter in range(n_acquistions):
        if temp[counter,0] == new_master:
           dir_name = 'master'
        else:
           dir_name = str(int(temp[counter,0]))
        # generate the directory if it does not exist yet
        try:
            os.stat(dir_name)
        except:
            os.mkdir(dir_name)
        np.savetxt(os.path.join(dir_name,'baseline'), [temp[counter,:]], fmt='%.f %.2f ', delimiter='\t', newline='\n')

# main script
if __name__ == '__main__':
    '''
    Main driver.
    '''

    # parsing the command line inputs
    inps = cmdLineParse()

    ### check if the baselines are as single txt file or as a grid
    # baseline files
    baseline_files = glob(os.path.join(inps.baseline_dir,"2*","2*.txt"))
    if not baseline_files:
        # try to see if they are all local
        baseline_files = glob(os.path.join(inps.baseline_dir,"2*.txt"))

    # baseline grid
    baseline_grids = glob(os.path.join(inps.baseline_dir,"2*","2*[0-9].vrt"))
    if not baseline_grids:
        # try to see if they are all local
        baseline_grids = glob(os.path.join(inps.baseline_dir,"2*[0-9].vrt"))

    ### let the grid take priority
    if baseline_grids:
        baselinegrid(inps)
    elif baseline_files:
        baselinefile(inps)


text:
import tkinter
from tkinter import *
from tkinter.ttk import *  # Widgets avec thèmes
from SE4TeC_demo.GUI_function import gui_function
import matplotlib
matplotlib.use("TkAgg")
from matplotlib import pyplot as plt
import numpy as np

class SMAPPage(tkinter.Frame):
    # SMAP
    def __init__(self, container, parent):
        self.container = container
        self.parent = parent
        self.dataset = self.parent.guiFunc.dataset
        tkinter.Frame.__init__(self, container)

        # the "textvairiable" of each Combobox:
        self.v_source = StringVar()
        self.v_source.set("select")
        self.v_target = StringVar()
        self.v_queryL = IntVar()
        self.v_queryI = IntVar()
        self.v_class = StringVar()

        self.frame2_1 = tkinter.Frame(self.container, bg="gray90")
        self.frame2_1.grid(row=0, column=0, ipady = 25, sticky="new")
        l_source = tkinter.Label(self.frame2_1, text="Source Time Series :", background="gray90",
                                 foreground="SkyBlue4")

        self.combb_source = Combobox(self.frame2_1, values=self.dataset.tsNbrList, textvariable = self.v_source, state='readonly',
                                                 width=10)
        self.combb_source.bind('<<ComboboxSelected>>', self.callback_source)
        self.m = tkinter.Label(self.frame2_1, text="Query length", bg="gray90", foreground="SkyBlue4")
        # Query length, the index of target TS will change along with the query's length
        self.combb_m = Combobox(self.frame2_1, values=self.dataset.queryLength, textvariable = self.v_queryL, state='readonly', width=5)
        self.combb_m.bind('<<ComboboxSelected>>', self.callback_m)

        l_source.grid(row=0, column=0, sticky=W)
        self.combb_source.grid(row=0, column=1, sticky=W, columnspan=2)
        self.m.grid(row=1, column=0, sticky=W)
        self.combb_m.grid(row=1, column=1, sticky=W)
        # Placement of a single SOURCE/TARGET visualization
        self.frame2_1_1 = tkinter.Frame(self.frame2_1, borderwidth=2, highlightthickness=1, bg="gray90",
                                        highlightbackground="gray90",
                                        highlightcolor="gray90",
                                        relief="sunken")
        self.frame2_1_1.grid(row=2, column=0, sticky=W, columnspan=3, padx=(40, 10), pady=(10, 40))
        l_target = tkinter.Label(self.frame2_1_1, text="Target ", bg="gray90")
        self.combb_target = Combobox(self.frame2_1_1, values=self.dataset.tsNbrList, textvariable = self.v_target, state='readonly', width=10)
        self.combb_target.bind('<<ComboboxSelected>>', self.callback_target)
        l_target.grid(row=0, column=0, sticky=W)
        self.combb_target.grid(row=0, column=1, sticky=W)
        # Placement of a single index for SOURCE/TARGET visualization
        self.frame2_1_2 = tkinter.Frame(self.frame2_1_1, borderwidth=20, bg="gray90")
        self.frame2_1_2.grid(row=1, column=0, sticky=W, columnspan=2)
        self.index = tkinter.Label(self.frame2_1_2, text="index", bg="gray90")
        self.combb_index = Combobox(self.frame2_1_2, values=self.dataset.queryLength, textvariable = self.v_queryI, state='readonly', width=5)
        self.combb_index.bind('<<ComboboxSelected>>', self.callback_index)

        l_DP = tkinter.Label(self.frame2_1_2, text="Distance Profile", bg="gray90")
        b_DP = tkinter.Button(self.frame2_1_2, text="extract", command=lambda: self.parent.guiFunc.extractDP(self), highlightbackground="gray90")
        self.index.grid(row=0, column=0, sticky=W)
        self.combb_index.grid(row=0, column=1, sticky=W)

        l_DP.grid(row=1, column=0, sticky=W)
        b_DP.grid(row=1, column=1, sticky=W)

        # Placement of Matrix Profile for SOURCE/TARGET visualization
        l_MP = tkinter.Label(self.frame2_1_1, text="Matrix Profile", bg="gray90")
        b_MP = tkinter.Button(self.frame2_1_1, text="extract", command=lambda: self.parent.guiFunc.extractMP(self), highlightbackground="gray90",
                              relief='sunken')
        l_MP.grid(row=2, column=0, sticky=W)
        b_MP.grid(row=2, column=1, sticky=W)

        # Placement of Representative/Discrimination Profile for SOURCE visualization
        l_RP = tkinter.Label(self.frame2_1, text="Rep. Profile  in class", bg="gray90", foreground="SkyBlue4")
        combb_class = Combobox(self.frame2_1, values=self.dataset.ClassList, textvariable = self.v_class, state='readonly', width=6)
        b_RP = tkinter.Button(self.frame2_1, text="extract", command=lambda: self.parent.guiFunc.extractRP(self), highlightbackground="gray90")
        l_RP.grid(row=3, column=0, sticky=W)
        combb_class.grid(row=3, column=1, sticky=W + N)
        b_RP.grid(row=3, column=2, sticky=W)
        l_DiscP = tkinter.Label(self.frame2_1, text="Discm. Profile ", bg="gray90", foreground="SkyBlue4")
        b_DiscP = tkinter.Button(self.frame2_1, text="extract", command=lambda: self.parent.guiFunc.extractDiscP(self), highlightbackground="gray90")
        b_USE = tkinter.Button(self.frame2_1, text="time(USE)",
                                  command=lambda: self.parent.guiFunc.extractEDMatrix(self),
                                  highlightbackground="gray90")
        b_SMAPLB = tkinter.Button(self.frame2_1, text="speedup(LB)", command=lambda: self.parent.guiFunc.extractDiscP_LB(self),
                                 highlightbackground="gray90")
        l_DiscP.grid(row=4, column=0, sticky=W)
        b_DiscP.grid(row=4, column=1, sticky=E, columnspan=2)
        b_USE.grid(row=5, column=0, sticky=E, columnspan=1)
        b_SMAPLB.grid(row=5, column=1, sticky=E, columnspan=2)
    def callback_m(self, event=None):
        print('--- callback_m ---')
        queryL = self.v_queryL.get()
        RealIndex = list(range(self.dataset.tslength - int(queryL)))
        self.combb_index.configure(values=RealIndex)

    def callback_source(self, event=None):
        print('--- callback_source ---')
        dataset = self.dataset
        nbr_source = self.v_source.get()
        hash_source = dataset.tsNameDir[nbr_source]
        self.source = dataset.tsObjectDir[hash_source]
        self.parent.v_sourceC.set(self.source.class_timeseries)
        # CANVAS
        source = self.source.timeseries
        x = range(len(source))
        self.ax1 = self.parent.ax1
        self.ax1.clear()  # clear the previous plot at the same position
        self.ax1.spines['top'].set_visible(False)
        self.ax1.spines['right'].set_visible(False)
        self.ax1.plot(x, source, linewidth=0.5, label=nbr_source)
        self.ax1.set_ylabel("Source TS")
        self.ax1.legend(loc="upper right")
        self.parent.canvas.draw()

    def callback_target(self, event=None):
        print('--- callback_target ---')
        dataset = self.dataset
        nbr_target = self.v_target.get()
        hash_target = dataset.tsNameDir[nbr_target]
        self.target = dataset.tsObjectDir[hash_target]
        self.parent.v_targetC.set(self.target.class_timeseries)
        # CANVAS
        # remove the axis_x of "self.axe1"
        plt.setp(self.ax1.get_xaxis(), visible=False)
        self.ax1.spines['bottom'].set_visible(False)
        target = self.target.timeseries
        x = range(len(target))
        self.ax2 = self.parent.ax2
        self.ax2.clear()  # clear the previous plot at the same position
        self.ax2.spines['top'].set_visible(False)
        self.ax2.spines['right'].set_visible(False)
        self.ax2.plot(x, target, linewidth=0.5, label=nbr_target)
        self.ax2.set_ylabel("Target TS")
        self.ax2.legend(loc="upper right")
        self.parent.canvas.draw()

    def callback_index(self, event=None):
        print('--- callback_index ---')
        dataset = self.dataset
        self.m = self.v_queryL.get()
        index_start = self.v_queryI.get()
        index_end = index_start + self.m
        x_query = range(index_start,index_end)
        self.query = self.source.timeseries[index_start:index_end]
        # CANVAS
        self.ax1 = self.parent.ax1
        self.ax1.clear()
        source = self.source.timeseries
        x_source = range(len(source))
        self.ax1.plot(x_source, source, linewidth=0.5, label=self.v_source.get())
        self.ax1.plot(x_query, self.query, linewidth=2, label="Query")
        self.ax1.spines['top'].set_visible(False)
        self.ax1.spines['right'].set_visible(False)
        self.ax1.set_ylabel("Source TS")
        self.ax1.legend(loc="upper right")
        self.parent.canvas.draw()


text:
"""Initialization functions.

Each initialization function is implemented as a class, with callable objects
that map shape tuples to initialized numpy arrays.

Examples
--------
>>> from bnas.init import Orthogonal
>>> from bnas.model import Linear
>>> Linear('transition', 100, 100, w_init=Orthogonal())
"""

import sys

import numpy as np
import theano

class InitializationFunction:
    def __call__(self, *args, **kwargs):
        raise NotImplementedError

def even_split(k):
    def split(n):
        if n % k != 0:
            raise ValueError('Can not split evenly!')
        return [n//k for _ in range(k)]
    return split

class Concatenated(InitializationFunction):
    """Concatenated initializations.

    This can be used to construct a matrix where different rows are
    initialized in different ways, for instance if you have a recurrent
    transformations with some inputs and want the state-to-state
    transformation to use orthogonal matrix initialization and the
    input-to-state transformation to use Gaussian initialization.

    Arguments
    ---------
    init_funs : list of functions
        Functions to initialize each of the matrices
    div_fun : function (int => list of int), optional
        Function mapping the shape of the first dimension to a list of
        first-dimension shapes for each of the initialization functions in
        `init_funs`. By default, the matrix is split up evenly, as in the
        example below.
    axis : int
        Axis along which to concatenate, default is 0 which is useful when
        transforming several inputs, but set to 1 if several concatenated
        outputs are produced.
    Example
    -------
    >>> Linear('transition', dims*2, dims, w_init=Concatenated([
    ...     Orthogonal(),
    ...     Gaussian(fan_in=dims)]))
    """
    def __init__(self, init_funs, div_fun=None, axis=0):
        if div_fun is None:
            k = len(init_funs)
            div_fun = even_split(k)
        self.init_funs = init_funs
        self.div_fun = div_fun
        self.axis = axis

    def __call__(self, dims, dtype=theano.config.floatX):
        divs = self.div_fun(dims[self.axis])
        assert sum(divs) == dims[self.axis]
        shapes = [dims[:self.axis] + (dim0,) + dims[self.axis+1:]
                  for dim0 in divs]
        return np.concatenate(
                [f(shape, dtype) for f, shape in zip(self.init_funs, shapes)],
                axis=self.axis)

class Constant(InitializationFunction):
    """Constant initialization.

    All elements are initialized with the same constant value.

    Parameters
    ----------
    a : float
        Initialization constant.
    """

    def __init__(self, a):
        self.a = a

    def __call__(self, dims, dtype=theano.config.floatX):
        return np.full(dims, self.a, dtype=dtype)

class Gaussian(InitializationFunction):
    """Isotropic Gaussian initialization.

    Elements are initialized independently from a Gaussian distribution
    with a given mean and standard deviation.

    Parameters
    ----------
    dev : float, optional
        Standard deviation of distribution
    mean : float, optional
        Mean of distribution
    fan_in : int, optional
        If this argument is given, `dev` and `mean` are ignored. Instead,
        mean 0 and standard deviation :math:`\sqrt{2/fan_in}` is used.
    """

    def __init__(self, dev=1.0, mean=0.0, fan_in=None):
        if fan_in is None:
            self.dev = dev
            self.mean = mean
        else:
            self.dev = np.sqrt(2.0/fan_in)
            self.mean = 0.0

    def __call__(self, dims, dtype=theano.config.floatX):
        m = np.random.standard_normal(dims)*self.dev + self.mean
        return m.astype(dtype)

class Uniform(InitializationFunction):
    """Uniform initialization.

    Elements are initialized independently from a uniform distribution
    with a given mean and scale (so the minimum value is `mean - scale/2`
    and the maximum is `mean + scale/2`).

    Parameters
    ----------
    scale : float, optional
        Scale of distribution
    mean : float, optional
        Mean of distribution
    """

    def __init__(self, scale=0.01, mean=0.0):
        self.scale = scale
        self.mean = mean

    def __call__(self, dims, dtype=theano.config.floatX):
        return np.random.uniform(
                size=dims,
                low=mean-0.5*scale,
                high=mean+0.5*scale).astype(config.floatX)

class Orthogonal(InitializationFunction):
    """Orthogonal initalization.

    Create an orthogonal matrix, i.e. where M x M.T == I.
    Note that this can only be used with 2D matrixes, and typically with
    square ones.

    Parameters
    ----------
    scale : float, optional
        Scaling factor
    """

    def __init__(self, scale=1.0):
        self.scale = scale

    def __call__(self, dims, dtype=theano.config.floatX):
        # Code from Blocks: blocks/blocks/initialization.py
        if len(dims) != 2:
            raise ValueError(
                    'Orthogonal matrix must be square, '
                    'but has shape: %s' % dims)
        if dims[0] == dims[1]:
            M = np.random.standard_normal(dims)
            Q, R = np.linalg.qr(M)
            Q = Q * np.sign(np.diag(R))
            return (Q * self.scale).astype(dtype)
        print('WARNING: creating non-square orthogonal matrix (bug?)',
              file=sys.stderr)
        M1 = np.random.standard_normal((dims[0], dims[0]))
        M2 = np.random.standard_normal((dims[1], dims[1]))
        Q1, R1 = np.linalg.qr(M1)
        Q2, R2 = np.linalg.qr(M2)
        Q1 = Q1 * np.sign(np.diag(R1))
        Q2 = Q2 * np.sign(np.diag(R2))
        n_min = min(dims)
        return (np.dot(Q1[:,:n_min], Q2[:n_min,:]) * self.scale).astype(dtype)

class Identity(InitializationFunction):
    """Identity matrix initialization.

    Creates a scaled identity matrix, which must be 2D and square.

    Parameters
    ----------
    scale : float, optional
        Scale
    """

    def __init__(self, scale=1.0):
        self.scale = scale

    def __call__(self, dims, dtype=theano.config.floatX):
        if len(dims) != 2:
            raise ValueError(
                    'Identity matrix must be 2D, but has shape %s' % dims)
        if dims[0] != dims[1]:
            raise ValueError(
                    'Identity matrix must be square, but has shape %s' % dims)
        return np.eye(dims[0], dtype=dtype)

class Identity2D(InitializationFunction):
    """Identity filter for 2D convolutional layers."""

    def __init__(self, scale=1.0):
        self.scale = scale

    def __call__(self, dims, dtype=theano.config.floatX):
        if not len(dims) == 4:
            raise ValueError('Shape of 2D filter must be 4D')
        if not (dims[0] == dims[1] and dims[-2] == dims[-1]):
            raise ValueError(
                'First/second and third/fourth dimensions must be equal')
        if not dims[-1] % 2 == 1:
            raise ValueError('Filter size must be odd')
        m = np.zeros(dims, dtype=dtype)
        for i in range(dims[0]):
            m[i,i,dims[-2]//2,dims[-1]//2] = self.scale
        return m

max_stars_repo_name: redperiabras/FILIPINEU

max_issues_repo_name: redperiabras/FILIPINEU

max_forks_repo_name: redperiabras/FILIPINEU

reason: import numpy,import theano


text:
# -*- coding: utf-8 -*-
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
""" ncutout_tarray.py

SpecNCutout: Batch-wise SpecAugment + N-CutOut layers for augmentation in
spectral domain for GPUs.

• variable number of holes for cutout
• hole filler types ['zeros', 'random']
• compatiable with TF2.x and @tf.function decorator
• implementation based on tf.TensorArray

USAGE:

    spec_ncutout_layer = SpecNCutout(prob=0.5,
                                     n_holes=3,
                                     hole_fill='random')
    m = (your method to get spectrogram here...)
    m_aug = spec_ncutout_layer(m)

For more details, see test() in the below

References:
    • original NumPy implementation of https://arxiv.org/abs/1708.04552
        https://github.com/uoguelph-mlrg/Cutout/blob/master/util/cutout.py

"""
import tensorflow as tf
import numpy as np              # for test()
import matplotlib.pyplot as plt # for test()
from io import BytesIO          # for test()

class SpecNCutout(tf.keras.layers.Layer):
    """
    SpecNCutout based on SpecAugment and CutOut: implementation using
    tf.TensorArray.

    Arguments
    ---------
    • prob: (tf.Float)
        probability (0-1) of cutout activity. If prob=1.0 (default), always
        output cut-out spectrogram
    • n_holes: (int)
        Number of random holes to create
    • uniform_mask: (bool)
        If True (default), use efficient uniform mask in batch.
    • hole_fill: (str) or [(float), (float)]
        Values to fill the holes with. Default is 'min'.
        - 'min' fills with minimum magnitude of input spectrogram.
        - 'zeros' fills with zeros.
        - 'random' fills with random values within the range of min and max of input.
        - [min_mag, max_mag] fills with random values within the range.
    • hole_config: [(int),(int),(int),(int)]
        Configures the range of hole mask size by [min_width, max_width,
        min_height, max_height]. If [None,None,None,None] (default), 1/10 of
        the input length will be set as minimum, and 1/2 of the input length
        will be set as maximum.
    • hole_wise_act_with_prob: (bool)
        - if True (default), apply hole-wise activation probability to
          augmentation.
        - if False, element-wise activation is uniformly applied to all the
          corresponding holes.

    Input
    -----
    • <tf.Float> 4D tensor variable with shape (B,H,W,C), equivalent with
      (Batch,Freq,Time,1).

    """
    def __init__(self,
                 prob=1.0,
                 n_holes=1,
                 uniform_mask=True,
                 hole_fill='min',
                 hole_config=[None,None,None,None],
                 hole_wise_act_with_prob=True,
                 **kwargs):
        super(SpecNCutout, self).__init__()
        self.prob = prob
        self.n_holes = n_holes
        self.uniform_mask = uniform_mask
        self.hole_fill, self.filler_min, self.filler_max = None, None, None
        if hole_fill in ['min', 'zeros', 'random']:
            self.hole_fill = hole_fill
        elif type(hole_fill)==list and len(hole_fill)==2:
            self.hole_fill = 'random_with_range'
            self.filler_min = hole_fill[0]
            self.filler_max = hole_fill[1]
        else:
            raise NotImplementedError(hole_fill)

        self.hole_minw, self.hole_maxw, self.hole_minh, self.hole_maxh = hole_config

    def build(self, input_shape):
        self.x_h = input_shape[1]
        self.x_w = input_shape[2]
        self.index_h = tf.range(self.x_h) # [0,1,2,...h]: will be used for 1d-mask
        self.index_w = tf.range(self.x_w) # [0,1,2,...w]: will be used for 1d-mask

        # Pre-calculate hole fillers
        if self.hole_fill=='min':
            self.hf = tf.ones(input_shape, tf.float32)
        elif self.hole_fill=='zeros':
            self.hf = tf.zeros(input_shape, tf.float32)
        elif self.hole_fill=='random':
            self.hf = tf.random.uniform(input_shape, 0., 1., tf.float32)
        elif self.hole_fill=='random_with_range':
            self.hf = tf.random.uniform(input_shape, self.filler_min,
                                   self.filler_max, tf.float32)

    def generate_single_mask(self, h_start=int(), h_end=int(), w_start=int(),
                             w_end=int()):
        # 1d mask
        m_h = tf.logical_and((h_start <= self.index_h), (self.index_h <= h_end))
        m_w = tf.logical_and((w_start <= self.index_w), (self.index_w <= w_end))

        # from 1d to 2d mask
        m_h = tf.expand_dims(m_h, axis=1) # shape: (h,1)
        m_w = tf.expand_dims(m_w, axis=0) # shape: (1,w)
        mask = tf.logical_and(m_h, m_w) # shape:(h,w), dtype:tf.bool
        return mask # (h, w)

    def generate_mixed_mask(self, bsz, hole_act_prob, hole_minh, hole_maxh,
                            hole_minw, hole_maxw):
        # If using uniform mask, b should be set to 1.
        # Else if using different masks for batches, b should be > 1.
        n_masks = self.n_holes

        # Randomize hole width and heights
        if hole_minw==hole_maxw:
            xs_w = hole_minw
        else:
            xs_w = tf.random.uniform((bsz, n_masks), hole_minw, hole_maxw, tf.int32)
            # (n): width of x for bth batch in nth mask

        if hole_minh==hole_maxh:
            ys_h = hole_minh
        else:
            ys_h = tf.random.uniform((bsz, n_masks), hole_minh, hole_maxh, tf.int32)
                # (n): height of y for bth batch in nth mask

        # Get hole positions
        if (self.hole_minw==-1) & (self.hole_maxw==-1): # 'horizontal' mode
            xs = tf.ones((bsz, n_masks), tf.int32) * (self.x_w // 2)
        else:
            # Randomize hole positions on x-axis
            xs = tf.random.uniform((bsz, n_masks), 0, self.x_w - 1, tf.int32)
                # xs: center position on x-axis for (batch, n_hole)

        if (self.hole_minh==-1) & (self.hole_maxh==-1): # 'vertical' mode
            ys = tf.ones((bsz, n_masks), tf.int32) * (self.x_h // 2)
        else:
            ys = tf.random.uniform((bsz, n_masks), 0, self.x_h - 1, tf.int32)
                # ys: center position on y-axis for (batch, n_hole)

        # Hole ranges
        xs_start = tf.clip_by_value(xs - (xs_w // 2), 0, self.x_w - 2)
        xs_end = tf.clip_by_value(xs + (xs_w // 2), 1, self.x_w - 1)
        ys_start = tf.clip_by_value(ys - (ys_h // 2), 0, self.x_h - 2)
        ys_end = tf.clip_by_value(ys + (ys_h // 2), 1, self.x_h - 1)

        # Generate single mask, n times --> mix masks
        m_arr =  tf.TensorArray(tf.bool, size=bsz, dynamic_size=False,
                                clear_after_read=True)
        for b in tf.range(bsz):
            mask = tf.zeros((self.x_h, self.x_w), tf.bool)
            for n in tf.range(self.n_holes):
                if tf.random.uniform([]) < hole_act_prob:
                    _mask = self.generate_single_mask(ys_start[b,n], ys_end[b,n],
                                                      xs_start[b,n], xs_end[b,n])
                    _mask.set_shape(mask.get_shape())
                    # Mixing
                    mask = tf.logical_or(mask, _mask) # shape: (h,w)
            mask = tf.expand_dims(mask, axis=2) # shape: (h,w,1)
            # Stack batch of masks (if bsz>0)
            m_arr = m_arr.write(b, mask) # shape: (b,h,w,1) with True for hole area

        return m_arr.stack() # shape: (b,h,w,1) with True for HOLE area (background is False)

    @staticmethod
    def get_true_background(mask):
        return tf.cast(tf.logical_not(mask), tf.float32)

    @staticmethod
    def get_true_holes(mask):
        return tf.cast(mask, tf.float32)

    def get_hole_filler(self, x):
        """ Generate hole filler that has same shape with input spectrogram. """
        hf = self.hf
        if self.hole_fill=='min':
            hf = hf * tf.reduce_mean(x)
        elif self.hole_fill=='zeros':
            hf = hf
        elif self.hole_fill=='random':
            hf = hf * (tf.reduce_max(x) - tf.reduce_min(x)) + tf.reduce_min(x)
        elif self.hole_fill=='random_with_range':
            hf = hf
        return hf

    @tf.function
    def call(self, x):
        # if tf.random.uniform([], 0, 1) < self.prob:
        if self.prob > 0:
            bsz = tf.shape(x)[0]
            x_h = tf.shape(x)[1]
            x_w = tf.shape(x)[2]

            if self.hole_minw==None:
                hole_minw = (x_w // 10)
            elif self.hole_minw==-1:
                hole_minw = x_w
            else:
                hole_minw = self.hole_minw

            if self.hole_maxw==None:
                hole_maxw = tf.cast((tf.cast(x_w, tf.float32) / 2.5), tf.int32)
            elif self.hole_maxw==-1:
                hole_maxw = x_w
            else:
                hole_maxw = self.hole_maxw

            if self.hole_minh==None:
                hole_minh = (x_h // 10)
            elif self.hole_minh==-1:
                hole_minh = x_h
            else:
                hole_minh = self.hole_minh

            if self.hole_maxh==None:
                hole_maxh = tf.cast((tf.cast(x_h, tf.float32) / 2.5), tf.int32)
            elif self.hole_maxh==-1:
                hole_maxh = x_h
            else:
                hole_maxh = self.hole_maxh

            # Generation of masks
            if self.uniform_mask:
                # Uniform mask: set bsz=1 for uniform mask generation
                uni_mask = self.generate_mixed_mask(1, 1., hole_minh,
                                                    hole_maxh, hole_minw,
                                                    hole_maxw) # shape: (b,h,w,1)

                # Random activation within batch
                act_mask = tf.cast((tf.random.uniform([bsz, 1, 1, 1], 0, 1) < self.prob), tf.float32)

                # Apply mask
                x_org = x * (1 - act_mask) # keep original without augmentation
                x_aug = x * act_mask
                x_aug = x_aug * self.get_true_background(uni_mask) # * act_mask
                x_aug = x_aug + self.get_true_holes(uni_mask) * act_mask * self.get_hole_filler(x)

                # Merge
                x = x_org + x_aug
            else:
                # Generate different masks for elements with independent prob
                masks = self.generate_mixed_mask(bsz, self.prob, hole_minh,
                                                 hole_maxh, hole_minw,
                                                 hole_maxw)

                # Apply different masks
                x = x * self.get_true_background(masks) + self.get_true_holes(masks) * self.get_hole_filler(x)
            return x
        else:
            # bypass...
            return x

    def get_config(self):
        config = super().get_config().copy()
        config.update({
            'x_h': self.x_h,
            'x_w': self.x_w,
            'index_h': np.arange(self.x_h),
            'index_w': np.arange(self.x_w),
            'prob': self.prob,
            'n_holes': self.n_holes,
            'hole_fill': self.hole_fill,
            'filler_min': self.filler_min,
            'filler_max': self.filler_max,
            'hole_minw': self.hole_minw,
            'hole_maxw': self.hole_maxw,
            'hole_minh': self.hole_minh,
            'hole_maxh': self.hole_maxh,
            'uniform_mask': self.uniform_mask
        })
        return config

#%% TEST
def plot_to_image(figure):
    """ Converts the matplotlib figure to a PNG. """
    # Save the plot to a PNG in memory.
    buf = BytesIO()
    plt.savefig(buf, format='png')
    # Closing the figure prevents it from being displayed directly inside
    # the notebook.
    plt.close(figure)
    buf.seek(0)
    # Convert PNG buffer to TF image
    image = tf.image.decode_png(buf.getvalue(), channels=4)
    # Add the batch dimension
    image = tf.expand_dims(image, 0)
    return image

def display_spec(mel_spectrogram=None, title=None, get_img=None):
    """

    Arguments
    ---------
      mel_spectrogram: (ndarray)
          mel_spectrogram to visualize.
      title: (String)
          plot figure's title
    """
    # Show mel-spectrogram using librosa's specshow.
    fig = plt.figure(figsize=(10, 4))
    plt.imshow(mel_spectrogram, origin='lower')
    plt.xlabel('time(frame)')
    plt.ylabel('mel')
    if title: plt.title(title)
    plt.tight_layout()
    if get_img:
        return plot_to_image(fig)
        print('GET_IMSHOW: created an image for tensorboard...')
    else:
        plt.show()
    return

def test():
    import librosa
    # Load audio file, extract mel spectrogram
    audio, sampling_rate = librosa.load('data/61-70968-0002.wav')
    m = librosa.feature.melspectrogram(y=audio,
                                       sr=sampling_rate,
                                       n_mels=256,
                                       hop_length=128,
                                       fmax=8000)
    m = librosa.power_to_db(abs(m))

    # Reshape spectrogram shape to [batch_size, time, frequency, 1]
    m = tf.constant(np.reshape(m, (1, m.shape[0], m.shape[1], 1)))
    # Show original spec
    display_spec(m[0,:,:,0].numpy(), title='Original')

    # Apply Cutout
    spec_ncutout_layer = SpecNCutout(prob=1.,
                                     n_holes=1,
                                     uniform_mask=False,
                                     hole_fill='min',
                                     hole_wise_act_with_prob=True,
                                     hole_config=[-1,-1,None,None])
    spec_ncutout_layer.trainable = False
    m_aug = spec_ncutout_layer(m)
    display_spec(m_aug[0,:,:,0].numpy())

    # Test speed with large batch input.
    m_batch = tf.stack([m[0,:,:,:]] * 128) # batch size is 1024
    m_batch_aug = spec_ncutout_layer(m_batch)
    display_spec(m_batch_aug[1,:,:,0].numpy())
    #%timeit -n 10 spec_ncutout_layer(m_batch)
    #%timeit -n 10 spec_ncutout_layer(spec_ncutout_layer(m_batch))

max_stars_repo_name: serkef/neural-audio-fp

max_issues_repo_name: serkef/neural-audio-fp

max_forks_repo_name: serkef/neural-audio-fp


text:
import math

import numpy as np

class GeneticAlgorithm:
    def __init__(self, log, chromosome_size, generations, population_size, selection_percent):
        # Logging
        self.log = log

        self._chromosome_size = chromosome_size
        self._generations = generations
        self._population_size = population_size
        self._selection_percent = selection_percent
        self._population = np.zeros(shape=(self._population_size, self._chromosome_size))
        self._fitness = np.zeros(self._population_size).flatten()
        self._num_chromosomes_to_select = math.ceil(self._selection_percent * self._population_size)

    @property
    def population(self) -> np.array:
        return self._population

    def initialize_population(self):
        self._population = np.random.rand(self._population_size, self._chromosome_size)
        self._fitness = np.random.rand(self._population_size).flatten()

    def select(self):
        population_with_fitness = list(zip(self.population, self._fitness))
        sorted_population_with_fitness = (sorted(population_with_fitness, key=lambda t: t[1])[::-1])[
                                         :self._num_chromosomes_to_select]

    def update_fitness_value(self, fitness_value: float, idx_to_update: int):
        self._fitness[idx_to_update] = fitness_value

    def crossover(self):
        return

    def mutate(self):
        return

# if __name__ == '__main__':
#     ga = GeneticAlgorithm(log=None, chromosome_size=10, generations=10, population_size=20, selection_percent=0.3)
#     ga.initialize_population()
#     ga.select()

max_stars_repo_name: kanishkaganguly/QuadGARL

max_issues_repo_name: kanishkaganguly/QuadGARL

max_forks_repo_name: kanishkaganguly/QuadGARL


text:
import numpy as np
import matplotlib.pyplot as plt

a = 0.0;  b = 3.0                     # time interval
N = 3                                 # number of time steps
dt = (b - a)/N                        # time step (s)
V_exact = [1.0, 2.0, 5.0, 12.0]       # exact volumes (L)
V = np.zeros(4)                       # numerically computed volume (L)
V[0] = 1                              # inital volume
r = np.zeros(3)                       # rates of volume increase (L/s)
r[0] = 1; r[1] = 3; r[2] = 7

for i in [0, 1, 2]:
    V[i+1] = V[i] + dt*r[i]

time = [0, 1, 2, 3]
plt.plot(time, V, 'bo-', time, V_exact, 'r')
plt.title('Case 1')
plt.legend(['numerical','exact'], loc='upper left')
plt.xlabel('t (s)')
plt.ylabel('V (L)')
plt.show()