text:
import numpy as np

"""
Konvolucni metody jsou ponekud narocnejsi na vykon (protoze nepouzivame plne optimalizovane knihovny na konvoluci)

Pro pridani noveho kernelu ho napiste mezi ostatni kernely a pridejte do filters. Pote napiste wrapper pro nej ve
functions.py a nakonec napiste CLI prepinac v main.py
"""

#TODO use better functions
def channel_convolution_result(image: np.array, kernel: np.array) -> np.array:
    """
    vezme 2 rozmerne pole a kernel a aplikuje kernel na pole a vrati ho
    :param image: image where we apply convolution
    :param kernel: kernel to apply
    :return: 2 dimensional np.array of sums
    """
    result = np.zeros(image.shape)
    result = result.astype("int32")  # for overflowing and negative values

    kernel_size = kernel.shape[0]
    # Pad with zeros from all sides,
    towork = np.pad(image, [(kernel_size // 2, kernel_size // 2), (kernel_size // 2, kernel_size // 2)],
                    mode='constant', constant_values=0)

    # Using //2 because padding, kernel shape must be square, so it doesnt matter which side we use
    for i in range((towork.shape[0] - ((kernel_size // 2) * 2))):
        for j in range((towork.shape[1] - ((kernel_size // 2) * 2))):
            #  we get the sum of pixels around
            result[i, j] = \
                np.sum((kernel * towork[(i + 0):(i + kernel_size), (j + 0):(j + kernel_size)]))

    # cut values to fit between 0-255 (no clipping, overflowing etc, all above 255 is set to 255, same with 0)
    np.clip(result, 0, 255, result)
    result = result.astype("uint8")
    return result

def apply_filter(image: np.array, kernel: np.array) -> np.array:
    """
    obalová funkce na channel_convolution_result, zkontroluje velikost img pole a podle počtu barevných kanálů zavolá
    channel_convolution_result na každý z nich
    :param image: obrázek na zpracování (v numpy.array formátu)
    :param kernel: matice podle které se obrázek bude editovat
    :return:
    """
    # A given image has to have either 2 (grayscale) or 3 (RGB) dimensions
    assert image.ndim in [2, 3]
    # A given filter has to be 2 dimensional and square
    assert kernel.ndim == 2
    assert kernel.shape[0] == kernel.shape[1]

    # If its 2 dimensional, we can return result, no postprocessing needed
    if image.ndim is 2:
        return channel_convolution_result(image, kernel)
    else:
        result_red = channel_convolution_result(image[::, ::, 0], kernel)
        result_green = channel_convolution_result(image[::, ::, 1], kernel)
        result_blue = channel_convolution_result(image[::, ::, 2], kernel)

        # stack all channels in 3. dimension
        result = np.dstack((result_red, result_green, result_blue))

    return result

"""
Seznam pouzitelnych kernelu
"""

sharpening_kernel = np.array([
    [0, -1, 0],
    [-1, 5, -1],
    [0, -1, 0],
])

approx_gaussian_blur_3_kernel = (1 / 16) * np.array([
    [1, 2, 1],
    [2, 4, 2],
    [1, 2, 1],
])

approx_gaussian_blur_5_kernel = (1 / 256) * np.array([
    [1, 4, 6, 4, 1],
    [4, 16, 24, 16, 4],
    [6, 24, 36, 24, 6],
    [4, 16, 24, 16, 4],
    [1, 4, 6, 4, 1],
])

edge_detection_kernel = np.array([
    [-1, -1, -1],
    [-1, 8, -1],
    [-1, -1, -1],
])

embossing_kernel = np.array([
    [-2, -1, 0],
    [-1, 1, 1],
    [0, 1, 2]
])

# Slovník použitelných kernelů, při přidání nového kernelu je třeba ho přidat i sem
filters = {
    'Sharpening': sharpening_kernel,
    'Gaussian blur 3x3 (approx)': approx_gaussian_blur_3_kernel,
    'Gaussian blur 5x5 (approx)': approx_gaussian_blur_5_kernel,
    'Edge detection': edge_detection_kernel,
    'Embossing': embossing_kernel,
}

max_stars_repo_name: Grayfoox/cli-image-editor

max_issues_repo_name: Grayfoox/cli-image-editor

max_forks_repo_name: Grayfoox/cli-image-editor


text:
"""
LrCollection.py

   Heikki.Huttunen@tut.fi, Jul 29th, 2014

   Defines the class LrCollection: A hierarchical two-layer
   structure for MEG decoding. The input consists of time slices
   and sensor slices. Each 1st layer classifier will see one
   slice of the data either in time or sensor dimension.

   The 1st layer predictions are combined together using
   a second layer classifier.

   Classifiers can be any classifier with sklearn interface.
   Alternatively, there can be a list of classifiers for
   both layers, in which case all will be used.

===
Copyright (c) 2014, Heikki Huttunen
Department of Signal Processing
Tampere University of Technology
Heikki.Huttunen@tut.fi

All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the Tampere University of Technology nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""

import numpy as np
import copy

class LrCollection():
    def __init__(self,
                 clf1,
                 clf2,
                 useCols = True,
                 useRows = True):
        """
        Initialize the LR collection classifier.

        Args:

            clf1:           First layer classifier. Can also be a list of
                            classifiers.
            clf2:           Second layer classifier. Can also be a list of
                            classifiers. In this case, the output will be
                            averaged over the predictions of the list.
            useCols:        If true, train a predictor for each sensor
            useRows:        If true, train a predictor for each timepoint

        Returns:

            self

        """

        # If the first layer classifier is not inside a list, store it
        # in a 1-element list.

        if not isinstance(clf1, list):
            self.clf1 = [clf1]
        else:
            self.clf1 = clf1

        # If the second layer classifier is not inside a list, store it
        # in a 1-element list.

        if not isinstance(clf2, list):
            self.clf2 = [clf2]
        else:
            self.clf2 = clf2

        self.useCols = useCols
        self.useRows = useRows

    def getView(self, X, idx):
        """
        Extract data from a single row or column in the data matrix.
        Can also span multiple rows/columns.

        Args:

            X:      Input data array of shape (n, p, t)
            idx:    A three element list of requested slice coordinates.
                    The element idx[0] is the list of trials to extract.
                    Second element idx[1] is a two element vector with
                    start and end indices in the sensor space (e.g.,
                    idx[1] = [0, 306]). The third element idx[1] is a
                    two element vector with start and end indices in the time
                    dimension (e.g., idx[1] = [0, 31]).
        """

        cols = idx[1]
        rows = idx[2]

        # Extract the requested slice and reshape to a design matrix
        # of shape (n, cols[1]-cols[0], rows[1]-rows[0]).

        result = X[idx[0], cols[0]:cols[1], rows[0]:rows[1]]
        result = np.reshape(result, (result.shape[0], -1))

        return result

    def fit(self, X, y):
        """
        Train the hierarchical classification model.

        Args:

            X:      Input training data array of shape (n, p, t)
            y:      Training class labels (shape: (n,))

        """

        # All 1st layer classifiers will be stored here:

        self.classifiers = []

        # We will be using all data for training.

        trials = range(X.shape[0])

        # Generate column and row views for the selected trials.

        if self.useCols:

            for col in range(X.shape[1]):

                # Train all classifiers in the list of 1st layer

                for c in self.clf1:
                    clf = copy.deepcopy(c)

                    # Define the slice with one sensor and all time indices

                    rows = [0, X.shape[2]]
                    cols = [col, col+1]

                    # Get the data for this view

                    view = self.getView(X, [trials, cols, rows])

                    # Train a classifier with this view.

                    clf.fit(view, y)
                    self.classifiers.append((clf, (cols, rows)))

        if self.useRows:

            for row in range(X.shape[2]):

                # Train all classifiers in the list of 1st layer

                for c in self.clf1:
                    clf = copy.deepcopy(c)

                    # Define the slice with one time index and all sensors

                    rows = [row, row+1]
                    cols = [0, X.shape[1]]

                    # Get the data for this view
                    view = self.getView(X, [trials, cols, rows])

                    # Train a classifier with this view.

                    clf.fit(view, y)
                    self.classifiers.append((clf, (cols, rows)))

        # The input to the second layer are the predicted probabilities
        # from the first layer predictors.

        yHat = self.predict_proba_l1(X)

        # Train second layer classifiers to merge the inputs.

        for c in self.clf2:
            c.fit(yHat, y)

    def predict_proba_l1(self, X):
        """
        Predict class probabilities for the test data using all 1st layer
        classifiers.

        Args:

            X:      Input test data array of shape (n_t, p, t)

         Returns:

            Numpy array of probabilities (shape: (n_t, num_classifiers))

        """

        yHat = []

        trials = range(X.shape[0])

        # Predict probability with every classifier in our list

        for classifier in self.classifiers:

            # classifier is a list with the "classifier"
            # and the related "indices".

            c = classifier[0]
            idx = classifier[1]

            # Get the same view as in training stage

            view = self.getView(X, [trials, idx[0], idx[1]])

            # Predict

            p = c.predict_proba(view)[:, 1]
            yHat.append(p)

        return np.array(yHat).T

    def predict_proba(self, X):
        """
        Predict class probabilities for the test data.

        Args:

            X:      Input test data array of shape (n_t, p, t)

         Returns:

            Numpy array of probabilities (shape: (n_t, num_classes))

        """

        # Predict first using all 1st layer classifiers:

        yHat = self.predict_proba_l1(X)

        # Combine these together with each of the 2nd layer classifiers

        y = []

        for c in self.clf2:

            if y == []:
                y = c.predict_proba(yHat)
            else:
                y = y + c.predict_proba(yHat)

        y = y / len(self.clf2)

        return y

    def predict(self, X):
        """
        Predict class labels for the test data.

        Args:

            X:      Input test data array of shape (n_t, p, t)

         Returns:

            Numpy array of probabilities (shape: (n_t, ))

        """
        yHat = (self.predict_proba(X) > 0.5)
        return yHat

ext: py

max_stars_repo_name: mahehu/decmeg

max_issues_repo_name: mahehu/decmeg

max_forks_repo_name: mahehu/decmeg

reason: import numpy


text:
#!/usr/bin/python
# encoding: utf-8

"""
@author: Ian
@contact:yongguiluo@hotmail.com
@file: bpmodel.py
@time: 2019/3/2 8:37
"""
import tensorflow as tf
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.models import load_model
import pandas as pd
import numpy as np
import os

def parse(x, y):
    print(y)
    return x, tf.keras.utils.to_categorical(y-422, num_classes=298)

class BpModel:
    def __init__(self, totalNum=50000, trainsetNum=40000, baseDir='D:/Desktop/DF/portrait'):
        self._baseDir = baseDir
        self._totalNum = totalNum
        self._trainsetNum = trainsetNum

    def prepareTrainDataset(self):
        df = pd.read_csv(os.path.join(self._baseDir, 'train_dataset.csv'))
        dfVal = df.values
        np.random.shuffle(dfVal)
        print(dfVal.shape)
        data = dfVal[: self._trainsetNum, 1:29].astype(np.float32)
        print(data.shape)
        label = dfVal[: self._trainsetNum, 29].astype(np.float32)
        label = np.array([tf.keras.utils.to_categorical(y-422, num_classes=298) for y in label])
        print(label.shape)
        print(label[:5])
        dataset = tf.data.Dataset.from_tensor_slices((data, label))
        dataset = dataset.shuffle(self._trainsetNum).repeat(1000).batch(100)
        return dataset

    def prepareValDataset(self):
        df = pd.read_csv(os.path.join(self._baseDir, 'train_dataset.csv'))
        dfVal = df.values
        np.random.shuffle(dfVal)
        print(dfVal.shape)
        data = dfVal[self._trainsetNum:, 1:29].astype(np.float32)
        print(data.shape)
        label = dfVal[self._trainsetNum:, 29].astype(np.float32)
        label = np.array([tf.keras.utils.to_categorical(y-422, num_classes=298) for y in label])
        print(label.shape)
        dataset = tf.data.Dataset.from_tensor_slices((data, label))
        dataset = dataset.repeat(100).batch(100)
        return dataset

    def prepareTestDataset(self):
        df = pd.read_csv(os.path.join(self._baseDir, 'test_dataset.csv'))
        dfVal = df.values
        np.random.shuffle(dfVal)
        print(dfVal.shape)
        data = dfVal[:, 1:29].astype(np.float32)
        print(data.shape)
        label = np.zeros((dfVal.shape[0])).astype(np.float32)
        label = np.array([tf.keras.utils.to_categorical(0, num_classes=298) for y in label])
        print(label.shape)
        dataset = tf.data.Dataset.from_tensor_slices((data, label))
        dataset = dataset.batch(1000)
        return dataset

    def buildModel(self):
        model = tf.keras.Sequential()
        model.add(Dense(500, activation='sigmoid', input_shape=(28,)))
        model.add(Dense(298, activation='softmax'))
        adam = Adam(lr=1e-4)
        model.compile(optimizer=adam, loss='categorical_crossentropy', metrics=['accuracy'])
        return model

    def loadModel(self, filename):
        return load_model(os.path.join(self._baseDir, 'result/models', filename))

if __name__ == '__main__':
    mode = '2'
    m = BpModel()
    testDataset = m.prepareTestDataset()
    model = m.loadModel('weights-improvement-99-0.22.hdf5')
    result = model.predict(testDataset, steps=50)
    r = np.argmax(result, axis=1)
    print(r[:5]+422)#[237 209 221 120 232]
    df = pd.read_csv(os.path.join(m._baseDir, 'submit_example.csv'))
    df['score'] = r+422
    df.to_csv(os.path.join(m._baseDir, 'proj0.csv'), index=False)

    if mode == '1':
        model = m.buildModel()
        print(model.summary())
        trainDataset = m.prepareTrainDataset()
        valDataset = m.prepareValDataset()
        filepath1 = os.path.join(m._baseDir, "result/models/weights-improvement-{epoch:02d}-{val_acc:.2f}.hdf5")
        callbacks = [
            # Interrupt training if `val_loss` stops improving for over 2 epochs
            # tf.keras.callbacks.EarlyStopping(patience=2, monitor='val_loss'),
            # Write TensorBoard logs to `./logs` directory
            tf.keras.callbacks.TensorBoard(log_dir=os.path.join(m._baseDir, "result/log")),
            tf.keras.callbacks.ModelCheckpoint(filepath1, monitor='val_acc', verbose=1, save_best_only=True, mode='max'),
            tf.keras.callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=10, verbose=0, mode='auto', cooldown=0, min_lr=0)
        ]
        print('开启训练')
        model.fit(trainDataset, steps_per_epoch=4000, epochs=100, validation_data=valDataset, validation_steps=100, callbacks=callbacks)


text:
from __future__ import print_function

import numpy as np
from scipy.optimize import curve_fit
from scipy.interpolate import PchipInterpolator
import os, copy
from openmdao.api import IndepVarComp, Component, Group, Problem
from ccblade.ccblade_component import CCBladePower, CCBladeLoads, CCBladeGeometry
from commonse import gravity, NFREQ
from commonse.csystem import DirectionVector
from commonse.utilities import trapz_deriv, interp_with_deriv
from precomp import _precomp
from akima import Akima, akima_interp_with_derivs
from rotor_geometry import RotorGeometry, NREL5MW, DTU10MW, TUM3_35MW, NINPUT, TURBULENCE_CLASS, TURBINE_CLASS
import _pBEAM
# import ccblade._bem as _bem  # TODO: move to rotoraero
import _bem  # TODO: move to rotoraero

from rotorse import RPM2RS, RS2RPM

try:
    from AeroelasticSE.FAST_reader import InputReader_Common, InputReader_OpenFAST, InputReader_FAST7
    from AeroelasticSE.FAST_writer import InputWriter_Common, InputWriter_OpenFAST, InputWriter_FAST7
    from AeroelasticSE.FAST_wrapper import FastWrapper
    from AeroelasticSE.runFAST_pywrapper import runFAST_pywrapper, runFAST_pywrapper_batch
    # from AeroelasticSE.CaseGen_IEC import CaseGen_IEC
    from AeroelasticSE.CaseLibrary import RotorSE_rated, RotorSE_DLC_1_4_Rated, RotorSE_DLC_7_1_Steady, RotorSE_DLC_1_1_Turb
    from AeroelasticSE.FAST_post import return_timeseries
except:
    pass

class FASTLoadCases(Component):
    def __init__(self, NPTS, npts_coarse_power_curve, FASTpref):
        super(FASTLoadCases, self).__init__()
        self.add_param('fst_vt_in', val={})

        # ElastoDyn Inputs
        # Assuming the blade modal damping to be unchanged. Cannot directly solve from the Rayleigh Damping without making assumptions. J.Jonkman recommends 2-3% https://wind.nrel.gov/forum/wind/viewtopic.php?t=522
        self.add_param('r', val=np.zeros(NPTS), units='m', desc='radial positions. r[0] should be the hub location \
            while r[-1] should be the blade tip. Any number \
            of locations can be specified between these in ascending order.')
        self.add_param('le_location', val=np.zeros(NPTS), desc='Leading-edge positions from a reference blade axis (usually blade pitch axis). Locations are normalized by the local chord length. Positive in -x direction for airfoil-aligned coordinate system')
        self.add_param('beam:Tw_iner', val=np.zeros(NPTS), units='m', desc='y-distance to elastic center from point about which above structural properties are computed')
        self.add_param('beam:rhoA', val=np.zeros(NPTS), units='kg/m', desc='mass per unit length')
        self.add_param('beam:EIyy', val=np.zeros(NPTS), units='N*m**2', desc='flatwise stiffness (bending about y-direction of airfoil aligned coordinate system)')
        self.add_param('beam:EIxx', val=np.zeros(NPTS), units='N*m**2', desc='edgewise stiffness (bending about :ref:`x-direction of airfoil aligned coordinate system <blade_airfoil_coord>`)')
        self.add_param('modes_coef_curvefem', val=np.zeros((3, 5)), desc='mode shapes as 6th order polynomials, in the format accepted by ElastoDyn, [[c_x2, c_],..]')

        # AeroDyn Inputs
        self.add_param('z_az', val=np.zeros(NPTS), units='m', desc='dimensional aerodynamic grid')
        self.add_param('chord', val=np.zeros(NPTS), units='m', desc='chord at airfoil locations')
        self.add_param('theta', val=np.zeros(NPTS), units='deg', desc='twist at airfoil locations')
        self.add_param('precurve', val=np.zeros(NPTS), units='m', desc='precurve at airfoil locations')
        self.add_param('presweep', val=np.zeros(NPTS), units='m', desc='presweep at structural locations')
        self.add_param('Rhub', val=0.0, units='m', desc='dimensional radius of hub')
        self.add_param('Rtip', val=0.0, units='m', desc='dimensional radius of tip')
        self.add_param('airfoils', val=[0]*NPTS, desc='CCAirfoil instances', pass_by_obj=True)

        # Turbine level inputs
        self.add_param('hubHt', val=0.0, units='m', desc='hub height')
        self.add_param('turbulence_class', val=TURBULENCE_CLASS['A'], desc='IEC turbulence class', pass_by_obj=True)
        self.add_param('turbine_class', val=TURBINE_CLASS['I'], desc='IEC turbulence class', pass_by_obj=True)

        # Initial conditions
        self.add_param('U_init', val=np.zeros(npts_coarse_power_curve), units='m/s', desc='wind speeds')
        self.add_param('Omega_init', val=np.zeros(npts_coarse_power_curve), units='rpm', desc='rotation speeds to run')
        self.add_param('pitch_init', val=np.zeros(npts_coarse_power_curve), units='deg', desc='pitch angles to run')

        # Environmental conditions
        self.add_param('Vrated', val=11.0, units='m/s', desc='rated wind speed')
        self.add_param('Vgust', val=11.0, units='m/s', desc='gust wind speed')
        self.add_param('Vextreme', val=11.0, units='m/s', desc='IEC extreme wind speed at hub height')
        self.add_param('rho',       val=0.0,        units='kg/m**3',    desc='density of air')
        self.add_param('mu',        val=0.0,        units='kg/(m*s)',   desc='dynamic viscosity of air')
        self.add_param('shearExp',  val=0.0,                            desc='shear exponent')

        # FAST run preferences
        self.Analysis_Level      = FASTpref['Analysis_Level']
        self.FAST_ver            = FASTpref['FAST_ver']
        self.FAST_exe            = os.path.abspath(FASTpref['FAST_exe'])
        self.FAST_directory      = os.path.abspath(FASTpref['FAST_directory'])
        self.Turbsim_exe         = os.path.abspath(FASTpref['Turbsim_exe'])
        self.debug_level         = FASTpref['debug_level']
        self.FAST_runDirectory   = FASTpref['FAST_runDirectory']
        self.FAST_InputFile      = FASTpref['FAST_InputFile']
        self.FAST_namingOut      = FASTpref['FAST_namingOut']
        self.dev_branch          = FASTpref['dev_branch']
        self.cores               = FASTpref['cores']
        self.case                = {}
        self.channels            = {}

        # DLC Flags
        self.DLC_powercurve      = FASTpref['DLC_powercurve']
        self.DLC_gust            = FASTpref['DLC_gust']
        self.DLC_extrm           = FASTpref['DLC_extrm']
        self.DLC_turbulent       = FASTpref['DLC_turbulent']

        self.add_output('dx_defl', val=0., desc='deflection of blade section in airfoil x-direction under max deflection loading')
        self.add_output('dy_defl', val=0., desc='deflection of blade section in airfoil y-direction under max deflection loading')
        self.add_output('dz_defl', val=0., desc='deflection of blade section in airfoil z-direction under max deflection loading')

        self.add_output('root_bending_moment', val=0.0, units='N*m', desc='total magnitude of bending moment at root of blade 1')
        self.add_output('Mxyz', val=np.array([0.0, 0.0, 0.0]), units='N*m', desc='individual moments [x,y,z] at the blade root in blade c.s.')

        self.add_output('loads_r', val=np.zeros(NPTS), units='m', desc='radial positions along blade going toward tip')
        self.add_output('loads_Px', val=np.zeros(NPTS), units='N/m', desc='distributed loads in blade-aligned x-direction')
        self.add_output('loads_Py', val=np.zeros(NPTS), units='N/m', desc='distributed loads in blade-aligned y-direction')
        self.add_output('loads_Pz', val=np.zeros(NPTS), units='N/m', desc='distributed loads in blade-aligned z-direction')
        self.add_output('loads_Omega', val=0.0, units='rpm', desc='rotor rotation speed')
        self.add_output('loads_pitch', val=0.0, units='deg', desc='pitch angle')
        self.add_output('loads_azimuth', val=0.0, units='deg', desc='azimuthal angle')
        self.add_output('model_updated', val=False, desc='boolean, Analysis Level 0: fast model written, but not run')

    def solve_nonlinear(self, params, unknowns, resids):

        fst_vt, R_out = self.update_FAST_model(params)

        if self.Analysis_Level == 2:
            # Run FAST with ElastoDyn
            list_cases, list_casenames, required_channels, case_keys = self.DLC_creation(params, fst_vt)
            FAST_Output = self.run_FAST(fst_vt, list_cases, list_casenames, required_channels)
            self.post_process(FAST_Output, case_keys, R_out, params, unknowns)

        elif self.Analysis_Level == 1:
            # Write FAST files, do not run
            self.write_FAST(fst_vt, unknowns)

    def update_FAST_model(self, params):

        # Create instance of FAST reference model

        fst_vt = copy.deepcopy(params['fst_vt_in'])

        fst_vt['Fst']['OutFileFmt'] = 2

        # Update ElastoDyn
        fst_vt['ElastoDyn']['TipRad'] = params['Rtip']
        fst_vt['ElastoDyn']['HubRad'] = params['Rhub']
        tower2hub = fst_vt['InflowWind']['RefHt'] - fst_vt['ElastoDyn']['TowerHt']
        fst_vt['ElastoDyn']['TowerHt'] = params['hubHt']

        # Update Inflowwind
        fst_vt['InflowWind']['RefHt'] = params['hubHt']
        fst_vt['InflowWind']['PLexp'] = params['shearExp']

        # Update ElastoDyn Blade Input File
        fst_vt['ElastoDynBlade']['NBlInpSt']   = len(params['r'])
        fst_vt['ElastoDynBlade']['BlFract']    = (params['r']-params['Rhub'])/(params['Rtip']-params['Rhub'])
        fst_vt['ElastoDynBlade']['BlFract'][0] = 0.
        fst_vt['ElastoDynBlade']['BlFract'][-1]= 1.
        fst_vt['ElastoDynBlade']['PitchAxis']  = params['le_location']
        fst_vt['ElastoDynBlade']['StrcTwst']   = params['beam:Tw_iner']
        fst_vt['ElastoDynBlade']['BMassDen']   = params['beam:rhoA']
        fst_vt['ElastoDynBlade']['FlpStff']    = params['beam:EIyy']
        fst_vt['ElastoDynBlade']['EdgStff']    = params['beam:EIxx']
        for i in range(5):
            fst_vt['ElastoDynBlade']['BldFl1Sh'][i] = params['modes_coef_curvefem'][0,i]
            fst_vt['ElastoDynBlade']['BldFl2Sh'][i] = params['modes_coef_curvefem'][1,i]
            fst_vt['ElastoDynBlade']['BldEdgSh'][i] = params['modes_coef_curvefem'][2,i]

        # Update AeroDyn15
        fst_vt['AeroDyn15']['AirDens'] = params['rho']
        fst_vt['AeroDyn15']['KinVisc'] = params['mu']

        # Update AeroDyn15 Blade Input File
        r = (params['r']-params['Rhub'])
        r[0]  = 0.
        r[-1] = params['Rtip']-params['Rhub']
        fst_vt['AeroDynBlade']['NumBlNds'] = len(r)
        fst_vt['AeroDynBlade']['BlSpn']    = r
        fst_vt['AeroDynBlade']['BlCrvAC']  = params['precurve']
        fst_vt['AeroDynBlade']['BlSwpAC']  = params['presweep']
        fst_vt['AeroDynBlade']['BlCrvAng'] = np.degrees(np.arcsin(np.gradient(params['precurve'])/np.gradient(r)))
        fst_vt['AeroDynBlade']['BlTwist']  = params['theta']
        fst_vt['AeroDynBlade']['BlChord']  = params['chord']
        fst_vt['AeroDynBlade']['BlAFID']   = np.asarray(range(1,len(params['airfoils'])+1))

        # Update AeroDyn15 Airfoile Input Files
        airfoils = params['airfoils']
        fst_vt['AeroDyn15']['af_data'] = [{}]*len(airfoils)
        for i in range(len(airfoils)):
            af = airfoils[i]
            fst_vt['AeroDyn15']['af_data'][i]['InterpOrd'] = "DEFAULT"
            fst_vt['AeroDyn15']['af_data'][i]['NonDimArea']= 1
            fst_vt['AeroDyn15']['af_data'][i]['NumCoords'] = 0          # TODO: link the airfoil profiles to this component and write the coordinate files (no need as of yet)
            fst_vt['AeroDyn15']['af_data'][i]['NumTabs']   = 1
            fst_vt['AeroDyn15']['af_data'][i]['Re']        = 0.75       # TODO: functionality for multiple Re tables
            fst_vt['AeroDyn15']['af_data'][i]['Ctrl']      = 0
            fst_vt['AeroDyn15']['af_data'][i]['InclUAdata']= "True"
            fst_vt['AeroDyn15']['af_data'][i]['alpha0']    = af.unsteady['alpha0']
            fst_vt['AeroDyn15']['af_data'][i]['alpha1']    = af.unsteady['alpha1']
            fst_vt['AeroDyn15']['af_data'][i]['alpha2']    = af.unsteady['alpha2']
            fst_vt['AeroDyn15']['af_data'][i]['eta_e']     = af.unsteady['eta_e']
            fst_vt['AeroDyn15']['af_data'][i]['C_nalpha']  = af.unsteady['C_nalpha']
            fst_vt['AeroDyn15']['af_data'][i]['T_f0']      = af.unsteady['T_f0']
            fst_vt['AeroDyn15']['af_data'][i]['T_V0']      = af.unsteady['T_V0']
            fst_vt['AeroDyn15']['af_data'][i]['T_p']       = af.unsteady['T_p']
            fst_vt['AeroDyn15']['af_data'][i]['T_VL']      = af.unsteady['T_VL']
            fst_vt['AeroDyn15']['af_data'][i]['b1']        = af.unsteady['b1']
            fst_vt['AeroDyn15']['af_data'][i]['b2']        = af.unsteady['b2']
            fst_vt['AeroDyn15']['af_data'][i]['b5']        = af.unsteady['b5']
            fst_vt['AeroDyn15']['af_data'][i]['A1']        = af.unsteady['A1']
            fst_vt['AeroDyn15']['af_data'][i]['A2']        = af.unsteady['A2']
            fst_vt['AeroDyn15']['af_data'][i]['A5']        = af.unsteady['A5']
            fst_vt['AeroDyn15']['af_data'][i]['S1']        = af.unsteady['S1']
            fst_vt['AeroDyn15']['af_data'][i]['S2']        = af.unsteady['S2']
            fst_vt['AeroDyn15']['af_data'][i]['S3']        = af.unsteady['S3']
            fst_vt['AeroDyn15']['af_data'][i]['S4']        = af.unsteady['S4']
            fst_vt['AeroDyn15']['af_data'][i]['Cn1']       = af.unsteady['Cn1']
            fst_vt['AeroDyn15']['af_data'][i]['Cn2']       = af.unsteady['Cn2']
            fst_vt['AeroDyn15']['af_data'][i]['St_sh']     = af.unsteady['St_sh']
            fst_vt['AeroDyn15']['af_data'][i]['Cd0']       = af.unsteady['Cd0']
            fst_vt['AeroDyn15']['af_data'][i]['Cm0']       = af.unsteady['Cm0']
            fst_vt['AeroDyn15']['af_data'][i]['k0']        = af.unsteady['k0']
            fst_vt['AeroDyn15']['af_data'][i]['k1']        = af.unsteady['k1']
            fst_vt['AeroDyn15']['af_data'][i]['k2']        = af.unsteady['k2']
            fst_vt['AeroDyn15']['af_data'][i]['k3']        = af.unsteady['k3']
            fst_vt['AeroDyn15']['af_data'][i]['k1_hat']    = af.unsteady['k1_hat']
            fst_vt['AeroDyn15']['af_data'][i]['x_cp_bar']  = af.unsteady['x_cp_bar']
            fst_vt['AeroDyn15']['af_data'][i]['UACutout']  = af.unsteady['UACutout']
            fst_vt['AeroDyn15']['af_data'][i]['filtCutOff']= af.unsteady['filtCutOff']
            fst_vt['AeroDyn15']['af_data'][i]['NumAlf']    = len(af.unsteady['Alpha'])
            fst_vt['AeroDyn15']['af_data'][i]['Alpha']     = af.unsteady['Alpha']
            fst_vt['AeroDyn15']['af_data'][i]['Cl']        = af.unsteady['Cl']
            fst_vt['AeroDyn15']['af_data'][i]['Cd']        = af.unsteady['Cd']
            fst_vt['AeroDyn15']['af_data'][i]['Cm']        = af.unsteady['Cm']
            fst_vt['AeroDyn15']['af_data'][i]['Cpmin']     = np.zeros_like(af.unsteady['Cm'])

        # AeroDyn spanwise output positions
        r = r/r[-1]
        r_out_target = [0.0, 0.1, 0.20, 0.40, 0.6, 0.75, 0.85, 0.925, 1.0]
        idx_out = [np.argmin(abs(r-ri)) for ri in r_out_target]
        R_out = [fst_vt['AeroDynBlade']['BlSpn'][i] for i in idx_out]

        fst_vt['AeroDyn15']['BlOutNd'] = [str(idx+1) for idx in idx_out]
        fst_vt['AeroDyn15']['NBlOuts'] = len(idx_out)

        return fst_vt, R_out

    def DLC_creation(self, params, fst_vt):
        # Case Generations

        # TMax = 99999. # Overwrite runtime if TMax is less than predefined DLC length (primarily for debugging purposes)
        TMax = 5.

        list_cases        = []
        list_casenames    = []
        required_channels = []
        case_keys         = []

        turbulence_class = TURBULENCE_CLASS[params['turbulence_class']]
        turbine_class    = TURBINE_CLASS[params['turbine_class']]

        if self.DLC_gust != None:
            list_cases_gust, list_casenames_gust, requited_channels_gust = self.DLC_gust(fst_vt, self.FAST_runDirectory, self.FAST_namingOut, TMax, turbine_class, turbulence_class, params['Vrated'], U_init=params['U_init'], Omega_init=params['Omega_init'], pitch_init=params['pitch_init'])
            list_cases        += list_cases_gust
            list_casenames    += list_casenames_gust
            required_channels += requited_channels_gust
            case_keys         += [2]*len(list_cases_gust)

        if self.DLC_extrm != None:
            list_cases_rated, list_casenames_rated, requited_channels_rated = self.DLC_extrm(fst_vt, self.FAST_runDirectory, self.FAST_namingOut, TMax, turbine_class, turbulence_class, params['Vextreme'])
            list_cases        += list_cases_rated
            list_casenames    += list_casenames_rated
            required_channels += requited_channels_rated
            case_keys         += [3]*len(list_cases_rated)

        if self.DLC_turbulent != None:
            list_cases_turb, list_casenames_turb, requited_channels_turb = self.DLC_turbulent(fst_vt, self.FAST_runDirectory, self.FAST_namingOut, TMax, turbine_class, turbulence_class, params['Vrated'], U_init=params['U_init'], Omega_init=params['Omega_init'], pitch_init=params['pitch_init'], Turbsim_exe=self.Turbsim_exe)
            list_cases        += list_cases_turb
            list_casenames    += list_casenames_turb
            required_channels += requited_channels_turb
            case_keys         += [4]*len(list_cases_turb)

        required_channels = sorted(list(set(required_channels)))
        channels_out = {}
        for var in required_channels:
            channels_out[var] = True

        return list_cases, list_casenames, channels_out, case_keys

    def run_FAST(self, fst_vt, case_list, case_name_list, channels):

        # FAST wrapper setup
        fastBatch = runFAST_pywrapper_batch(FAST_ver=self.FAST_ver)

        fastBatch.FAST_exe          = self.FAST_exe
        fastBatch.FAST_runDirectory = self.FAST_runDirectory
        fastBatch.FAST_InputFile    = self.FAST_InputFile
        fastBatch.FAST_directory    = self.FAST_directory
        fastBatch.debug_level       = self.debug_level
        fastBatch.dev_branch        = self.dev_branch
        fastBatch.fst_vt            = fst_vt
        fastBatch.post              = return_timeseries

        fastBatch.case_list         = case_list
        fastBatch.case_name_list    = case_name_list
        fastBatch.channels          = channels

        # Run FAST
        if self.cores == 1:
            FAST_Output = fastBatch.run_serial()
        else:
            FAST_Output = fastBatch.run_multi(self.cores)

        return FAST_Output

    def write_FAST(self, fst_vt, unknowns):
        writer                   = InputWriter_OpenFAST(FAST_ver=self.FAST_ver)
        writer.fst_vt            = fst_vt
        writer.FAST_runDirectory = self.FAST_runDirectory
        writer.FAST_namingOut    = self.FAST_namingOut
        writer.dev_branch        = self.dev_branch
        writer.execute()

        unknowns['model_updated'] = True
        if self.debug_level > 0:
            print('RAN UPDATE: ', self.FAST_runDirectory, self.FAST_namingOut)

    def post_process(self, FAST_Output, case_keys, R_out, params, unknowns):

        def post_gust(data, case_type):

            if case_type == 2:
                t_s = min(max(data['Time'][0], 30.), data['Time'][-2])
                t_e = min(data['Time'][-1], 90.)
                idx_s = list(data['Time']).index(t_s)
                idx_e = list(data['Time']).index(t_e)
            else:
                idx_s = 0
                idx_e = -1

            # Tip Deflections
            # return tip x,y,z for max out of plane deflection
            blade_max_tip = np.argmax([max(data['TipDxc1'][idx_s:idx_e]), max(data['TipDxc2'][idx_s:idx_e]), max(data['TipDxc3'][idx_s:idx_e])])
            if blade_max_tip == 0:
                tip_var = ["TipDxc1", "TipDyc1", "TipDzc1"]
            elif blade_max_tip == 1:
                tip_var = ["TipDxc2", "TipDyc2", "TipDzc2"]
            elif blade_max_tip == 2:
                tip_var = ["TipDxc3", "TipDyc3", "TipDzc3"]
            idx_max_tip = np.argmax(data[tip_var[0]][idx_s:idx_e])
            unknowns['dx_defl'] = data[tip_var[0]][idx_s+idx_max_tip]
            unknowns['dy_defl'] = data[tip_var[1]][idx_s+idx_max_tip]
            unknowns['dz_defl'] = data[tip_var[2]][idx_s+idx_max_tip]

            # Root bending moments
            # return root bending moment for blade with the highest blade bending moment magnitude
            root_bending_moment_1 = np.sqrt(data['RootMxc1'][idx_s:idx_e]**2. + data['RootMyc1'][idx_s:idx_e]**2. + data['RootMzc1'][idx_s:idx_e]**2.)
            root_bending_moment_2 = np.sqrt(data['RootMxc2'][idx_s:idx_e]**2. + data['RootMyc2'][idx_s:idx_e]**2. + data['RootMzc2'][idx_s:idx_e]**2.)
            root_bending_moment_3 = np.sqrt(data['RootMxc3'][idx_s:idx_e]**2. + data['RootMyc3'][idx_s:idx_e]**2. + data['RootMzc3'][idx_s:idx_e]**2.)
            root_bending_moment_max       = [max(root_bending_moment_1), max(root_bending_moment_2), max(root_bending_moment_3)]
            root_bending_moment_idxmax    = [np.argmax(root_bending_moment_1), np.argmax(root_bending_moment_2), np.argmax(root_bending_moment_3)]
            blade_root_bending_moment_max = np.argmax(root_bending_moment_max)

            unknowns['root_bending_moment'] = root_bending_moment_max[blade_root_bending_moment_max]*1.e3
            idx = root_bending_moment_idxmax[blade_root_bending_moment_max]
            if blade_root_bending_moment_max == 0:
                unknowns['Mxyz'] = np.array([data['RootMxc1'][idx_s+idx]*1.e3, data['RootMyc1'][idx_s+idx]*1.e3, data['RootMzc1'][idx_s+idx]*1.e3])
            elif blade_root_bending_moment_max == 1:
                unknowns['Mxyz'] = np.array([data['RootMxc2'][idx_s+idx]*1.e3, data['RootMyc2'][idx_s+idx]*1.e3, data['RootMzc2'][idx_s+idx]*1.e3])
            elif blade_root_bending_moment_max == 2:
                unknowns['Mxyz'] = np.array([data['RootMxc3'][idx_s+idx]*1.e3, data['RootMyc3'][idx_s+idx]*1.e3, data['RootMzc3'][idx_s+idx]*1.e3])

        def post_extreme(data, case_type):

            if case_type == 3:
                t_s = min(max(data['Time'][0], 30.), data['Time'][-2])
                t_e = min(data['Time'][-1], 90.)
                idx_s = list(data['Time']).index(t_s)
                idx_e = list(data['Time']).index(t_e)
            else:
                idx_s = 0
                idx_e = -1

            Time = data['Time'][idx_s:idx_e]
            var_Fx = ["B1N1Fx", "B1N2Fx", "B1N3Fx", "B1N4Fx", "B1N5Fx", "B1N6Fx", "B1N7Fx", "B1N8Fx", "B1N9Fx"]
            var_Fy = ["B1N1Fy", "B1N2Fy", "B1N3Fy", "B1N4Fy", "B1N5Fy", "B1N6Fy", "B1N7Fy", "B1N8Fy", "B1N9Fy"]
            for i, (varFxi, varFyi) in enumerate(zip(var_Fx, var_Fy)):
                if i == 0:
                    Fx = np.array(data[varFxi][idx_s:idx_e])
                    Fy = np.array(data[varFyi][idx_s:idx_e])
                else:
                    Fx = np.column_stack((Fx, np.array(data[varFxi][idx_s:idx_e])))
                    Fy = np.column_stack((Fy, np.array(data[varFyi][idx_s:idx_e])))

            Fx_sum = np.zeros_like(Time)
            Fy_sum = np.zeros_like(Time)
            for i in range(len(Time)):
                Fx_sum[i] = np.trapz(Fx[i,:], R_out)
                Fy_sum[i] = np.trapz(Fy[i,:], R_out)
            idx_max_strain = np.argmax(np.sqrt(Fx_sum**2.+Fy_sum**2.))

            Fx = [data[Fxi][idx_max_strain] for Fxi in var_Fx]
            Fy = [data[Fyi][idx_max_strain] for Fyi in var_Fy]
            spline_Fx = PchipInterpolator(R_out, Fx)
            spline_Fy = PchipInterpolator(R_out, Fy)

            r = params['r']-params['Rhub']
            Fx_out = spline_Fx(r)
            Fy_out = spline_Fy(r)
            Fz_out = np.zeros_like(Fx_out)

            unknowns['loads_Px'] = Fx_out
            unknowns['loads_Py'] = Fy_out*-1.
            unknowns['loads_Pz'] = Fz_out

            unknowns['loads_Omega'] = data['RotSpeed'][idx_max_strain]
            unknowns['loads_pitch'] = data['BldPitch1'][idx_max_strain]
            unknowns['loads_azimuth'] = data['Azimuth'][idx_max_strain]

        ############

        Gust_Outputs = False
        Extreme_Outputs = False
        #
        for casei in case_keys:
            if Gust_Outputs and Extreme_Outputs:
                break

            if casei in[1]:
                # power curve
                pass

            if casei in [2]:
                # gust: return tip deflections and bending moments
                idx_gust = case_keys.index(casei)
                data = FAST_Output[idx_gust]
                post_gust(data, casei)
                Gust_Outputs = True

            if casei in [3]:
                # extreme wind speed: return aeroloads for strains
                idx_extreme = case_keys.index(casei)
                data = FAST_Output[idx_extreme]
                post_extreme(data, casei)
                Extreme_Outputs = True

            if casei in [4]:
                # turbulent wind with multiplt seeds
                idx_turb = [i for i, casej in enumerate(case_keys) if casej==4]
                data_concat = {}
                for i, fast_out_idx in enumerate(idx_turb):
                    datai = FAST_Output[idx_turb[fast_out_idx]]

                    for var in datai.keys():
                        if i == 0:
                            data_concat[var] = []
                        data_concat[var].extend(list(datai[var]))

                for var in data_concat.keys():
                    data_concat[var] = np.array(data_concat[var])

                post_gust(data_concat, casei)
                post_extreme(data_concat, casei)
                Gust_Outputs = True
                Extreme_Outputs = True

max_stars_repo_name: HaidongHe/RotorSE

max_issues_repo_name: HaidongHe/RotorSE

max_forks_repo_name: HaidongHe/RotorSE

reason: import numpy,from scipy


text:
import os
import cv2
import ipdb
import random
import argparse
import numpy as np
from utils import *
import matplotlib.pyplot as plt
from skimage.transform import resize
plt.style.use('ggplot')
plt.rcParams.update({'font.size': 10, 'font.weight':'bold'})
plt.rc("font", family="sans-serif")

if __name__ == '__main__':

    # Hyper parameters.
    parser = argparse.ArgumentParser(description='Processing Meaningful Perturbation data')
    parser.add_argument('--result_path',
                        default='./results/ILSVRC2012_val_00002056/',
                        type=str, help='filepath for the results')
    parser.add_argument('--input_img',
                        default='./Images/teaser/ILSVRC2012_val_00002056.JPEG',
                        type=str, help='input image filepath')
    parser.add_argument('--algo',
                        default='sg',
                        type=str, help='sg|occlusion|lime|mp')
    parser.add_argument('--dataset',
                        default='imagenet',
                        type=str, help='dataset to run on imagenet | places365')
    parser.add_argument('--save_path',
                        default='',
                        type=str, help='path for saving images')

    args = parser.parse_args()

    if args.algo == 'lime':
        row_label = ['LIME']
    elif args.algo == 'occlusion':
        row_label = ['SP']
    elif args.algo == 'sg':
        row_label = ['SG']
    elif args.algo == 'mp':
        row_label = ['MP']
    else:
        print('Incorrect choice!!')
        exit(0)

    # Read real image
    o_img = cv2.resize(cv2.cvtColor(cv2.imread(args.input_img, 1), cv2.COLOR_BGR2RGB), (224, 224))
    # print(o_img.shape)

    # Read generated heatmap
    heatmap_path = sorted([f for f in os.listdir(os.path.join(args.result_path)) if f.endswith('pytorch.npy') and f.startswith(args.algo)])

    heatmap = [resize(np.load(os.path.join(args.result_path, ll)), (224, 224)) for ll in heatmap_path]

    # Normalizing heatmaps
    if args.algo == 'sg' or args.algo == 'lime':
        heatmap = [i / np.max(np.abs(i)) for i in heatmap]

    # Make a list of all images to be plotted
    image_batch = [o_img]
    image_batch.extend(heatmap)

    zero_out_plot_multiple_patch_chirag([image_batch],
                                 folderName='./',
                                 row_labels_left=row_label,
                                 row_labels_right=[],
                                 col_labels=[],
                                 file_name=os.path.join(args.save_path, 'figure_{}.jpg'.format(args.algo)))


text:
# Importando librerías
from numpy import array

# Listas y arreglos
a = array(['h', 101, 'l', 'l', 'o'])
x = ['h', 101, 'l', 'l', 'o']

print(a)
print(x)
print("Tamaño: ", len(x))

# Condicionales

if isinstance(x[1], int):
    x[1] = chr(x[1])
elif isinstance(x[1], str):
    pass
else:
    raise TypeError("Tipo no soportado!. No te pases! >:c")

print(' uwu '.join(x))

# Ciclos

for item in x:
    print(item)

for i in range(len(x)):
    print(x[i])

for i in range(1, 10, 2):
    print(i)

while len(x):
    print(x.pop(0))

while len(x):
    print(x.pop(0))
else:
    print('F para x :C')

# Operaciones con listas
x.append('H')
x.append('o')
x.append('l')
x.append('a')
x.insert(1, 'o')

# Entrada de datos

print(x)
respuesta = input("Hola?")
print(respuesta)

# Operadores aritméticos y booleanos
print(x)
print(10.1)
print(1 + 2 - 4 * 5 / 8 % 2)
print(2 ** 5)
print(True and True)
print(False and True)
print(False or True)
print(not False)

# Listas comprimidas
print([i for i in range(1, 11) if i % 2 == 0])
print([j for j in range(2, 101) if all(j % i != 0 for i in range(2, j))])
print([j for j in range(2, 101) if not(j % 2 or j % 3 or j % 5)])

reason: from numpy


text:
"""Set a random seed."""

__copyright__ = "Copyright (C) 2015-present, DV Klopfenstein, Haibao Tang. All rights reserved."
__author__ = "DV Klopfenstein"

import sys
import numpy as np

class RandomSeed32:
    """Manage a random seed."""

    def __init__(self, seed=None):
        self.max_val = int("0xffffffff", 0)
        self.seed = self._init_seed(seed)

    def _init_seed(self, seed):
        """Use user-specified random seed or randomly pick one."""
        # None -> Create seed
        clsname = self.__class__.__name__
        if seed is None:
            seed = np.random.randint(self.max_val)
            sys.stdout.write("  RANDOM SEED({S}) CREATED BY {CLASS}\n".format(
                S=self.get_seed_str(seed), CLASS=clsname))
        # Set seed
        np.random.seed(seed)
        sys.stdout.write("  RANDOM SEED({S}) STORED IN {CLASS}\n".format(
            S=self.get_seed_str(seed), CLASS=clsname))
        return seed

    def prt(self, prt=sys.stdout):
        """Print object's random seed."""
        self.prt_seed(self.seed, prt)

    def prt_seed(self, seed, prt=sys.stdout):
        """Print given random seed."""
        prt.write("  RANDOM SEED = {SEED}\n".format(SEED=self.get_seed_str(seed)))

    @staticmethod
    def get_seed_str(seed):
        """Print given random seed."""
        return "0x{S:08x} = {S:,}".format(S=seed)

    def get_seed_hexstr(self):
        """Return a string representing the random seed in hex format"""
        return '0x{S:08x}'.format(S=self.seed)

# Copyright (C) 2015-present, DV Klopfenstein, Haibao Tang. All rights reserved.

max_stars_repo_name: flying-sheep/goatools

max_issues_repo_name: flying-sheep/goatools

max_forks_repo_name: flying-sheep/goatools


text:
import os
import pandas as pd
import numpy as np

pjoin = os.path.join
parpath = '/nfs/a1/userhome/huangtaicheng/workingdir/'

real_size_pd = pd.read_csv(pjoin(parpath, 'data', 'PhysicalSize', 'SizeRank.csv'))
real_size_pd = real_size_pd.sort_values('DiagSize')

real_size_pd_out = {}
real_size_name = []
real_size_size = []
real_size_rank = []

rankpart = {1: [1,5], 2:[5,10], 3:[10,50], 4:[50,100], 5:[100,500], 6:[500,1000], 7:[1000,5000], 8:[5000, 50000]}

# for i in range(25):
#     real_size_pd_part = real_size_pd[i*4:(i+1)*4]
#     real_size_name.extend(real_size_pd_part['Name'])
#     real_size_size.extend(real_size_pd_part['DiagSize'])
#     real_size_rank.extend([i+1]*len(real_size_pd_part))

for i in rankpart.keys():
    real_size_pd_part = real_size_pd[(real_size_pd['DiagSize']>=rankpart[i][0])&(real_size_pd['DiagSize']<rankpart[i][1])]
    real_size_name.extend(real_size_pd_part['Name'])
    real_size_size.extend(real_size_pd_part['DiagSize'])
    real_size_rank.extend([i]*len(real_size_pd_part))

real_size_pd_out['name'] = real_size_name
real_size_pd_out['diag_size'] = real_size_size
real_size_pd_out['real_sizerank'] = real_size_rank

real_size_pd_out = pd.DataFrame(real_size_pd_out)

max_stars_repo_name: helloTC/RealWorldSizeAxis

max_issues_repo_name: helloTC/RealWorldSizeAxis

max_forks_repo_name: helloTC/RealWorldSizeAxis


text:
import numpy as np
import os, sys
#~ sys.path.append('/home/felipe/Dropbox/simuls17/fibresGen')
#~ import matrixAndFibresGeneration as mfg
#~ import newTheoryFibresLib as ntf
#from matrixAndFibresGeneration import *
#from newTheoryFibresLib import *
import copy
from fibresLib import *

np.random.seed(5)

net = Network()

maxit = 99999
maxnochange = 100
dJmin = 0.01
Jtol = 1.0e-10
ampP0 = 0.01
alphaP = 0.9
gammaP = 0.95 # damping max coordinate, for min and max. 0 means no damping (fixed window) and 1 means maximum damping (unit window).
ampA0 = 0.01
maxA = 1.1
minA = 0.9
alphaA = 0.9
pertPoint = 0.01 # 0.0 for regular
alphaPert = 0.5
restartPert = 4
ksmooth = 200
omegaSmooth = 0.5
timesSmooth = 4
Jtol2 = 1.0e-15

setParamOpt = [maxit, maxnochange, dJmin, Jtol, ampP0, alphaP, gammaP, ampA0, alphaA, maxA, minA, pertPoint, alphaPert, restartPert, omegaSmooth, timesSmooth, Jtol2]

pertPoint = 0.0 # 0.0 for regular

net.asymFac = -1 # nx - ny
net.nFibPrevision = 90

net.createNetwork()
net.removeVertHoriFibers()

net.setFlagsAndConnectivity()
net.set_lfa(2,[1.00,0.0])
net.setAf(2,[0.1,0.0])

Preg1 = copy.deepcopy(net.P)
net.addPertubation(pertPoint)
net.correctPoints(0.99,0.01)

net.set_af_Lf_Vf()
net.setNormalAndAbar()

#~ print net.Abar
#~ print net.normal

AfOld = copy.deepcopy(net.Af)

colour = 'black'
writeFigNetwork(net,c= colour, figNum = 2 , filename = 'networkNotOptimised.pdf')

#~ net.optimize(setParamOpt,functionalNBCfib)
#~ net.optimize(setParamOpt,functionalNBCnormal)
net.optimize(setParamOpt,functionalNBCBoth)

#~ writeFigNetwork(net,figNum = 2, filename = 'networkOptimised.png')

Ndof = 6
Nsubsteps = 6
Nparam = 29

net.writeNetwork(Ndof,Nsubsteps,Nparam,fignum = 1,opInifile = 'SGP', opIncludeTri = 1, addAuxNodes = 2, addAuxNodeOnFibres = 1)

#~ print net.flagBound
#~ print net.lfa
#~ print net.Af
#~ print net.af
#~ print net.Lf
#~ print net.Vf
#~ print np.sum(net.Vf)

#~ dP1 = net.P - Preg1
#~
#~ pRep = 1 # if 1 = 4 ==> , if 2 = 1 ==>9, if 3 = 1 ==> 16
#~ net2 = Network()
#~ net2.replicateRVE(net,Preg1,dP1,pRep)

#~ pRep = 2 # if 1 = 4 ==> , if 2 = 1 ==>9, if 3 = 1 ==> 16
#~ net3 = Network()
#~ net3.replicateRVE(net,Preg1,dP1,pRep)

#~ pRep = 3 # if 1 = 4 ==> , if 2 = 1 ==>9, if 3 = 1 ==> 16
#~ net4 = Network()
#~ net4.replicateRVE(net,Preg1,dP1,pRep)
#~

#~ net2.writeDefault(Ndof,Nsubsteps,Nparam,2)
#~ net3.writeDefault(Ndof,Nsubsteps,Nparam,3)
#~ net4.writeDefault(Ndof,Nsubsteps,Nparam,4)

max_stars_repo_name: felipefr/netfibGen

max_issues_repo_name: felipefr/netfibGen

max_forks_repo_name: felipefr/netfibGen


text:
import os
import sys
import time
import glob
import numpy as np
import torch
from utils import utils
import logging
import argparse
import torch.nn as nn
import torch.utils
from tensorboardX import SummaryWriter
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
from ASVRawDataset import ASVRawDataset
from models.model_search import Network
from func.architect import Architect
from pathlib import Path
from func.functions import train, validate
from func.p2sgrad import P2SGradLoss

if __name__ == '__main__':
    parser = argparse.ArgumentParser('ASVSpoof2019 model')
    parser.add_argument('--data', type=str, default='/path/to/your/LA',
                    help='location of the data corpus')
    parser.add_argument('--valid_freq', type=int, default=1, help='validate frequency')
    parser.add_argument('--report_freq', type=int, default=1000, help='report frequency in training')
    parser.add_argument('--layers', type=int, default=8, help='number of cells of the network')
    parser.add_argument('--init_channels', type=int, default=64, help='number of the initial channels of the network')
    parser.add_argument('--sinc_scale', type=str, default='mel', help='the type of sinc layer')
    parser.add_argument('--sinc_kernel', type=int, default=128, help='kernel size of sinc layer')
    parser.add_argument('--gru_hsize', type=int, default=1024, help='number of the features in the hidden state of gru layers')
    parser.add_argument('--gru_layers', type=int, default=3, help='number of gru layers of the network')
    parser.add_argument('--trainable', dest='is_trainable', action='store_true', help='whether using trainable sinc layer')
    parser.add_argument('--batch_size', type=int, default=14)
    parser.add_argument('--num_epochs', type=int, default=30)
    parser.add_argument('--warm_up_epoch', type=int, default=10, help='the network architecture will not change until this epoch')
    parser.add_argument('--sr', type=int, default=16000, help='default sampling rate')
    parser.add_argument('--lr', type=float, default=5e-5, help='intial learning rate')
    parser.add_argument('--no-mask', dest='is_mask', action='store_false', help='whether use freq mask, if not set, use mask by default')
    parser.add_argument('--weight_decay', type=float, default=3e-4)
    parser.add_argument('--seed', type=int, default=None, help='random seed')
    parser.add_argument('--comment', type=str, default='EXP', help='Comment to describe the saved mdoel')
    parser.add_argument('--momentum', type=float, default=0.9, help='momentum')
    parser.add_argument('--unrolled', action='store_true', default=False, help='use one-step unrolled validation loss')
    parser.add_argument('--arch_learning_rate', type=float, default=6e-4, help='learning rate for arch encoding')
    parser.add_argument('--arch_weight_decay', type=float, default=1e-3, help='weight decay for arch encoding')
    parser.add_argument('--rand', dest='is_rand', action='store_true', help='whether use rand start of input audio')

    # by default, use fixed first 4 seconds of the original audio file, not using randomly selected 4 seconds
    parser.set_defaults(is_rand=False)
    # use mask by default
    parser.set_defaults(is_mask=True)
    parser.set_defaults(is_trainable=False)

    args = parser.parse_args()
    args.comment = 'search-{}-{}'.format(args.comment, time.strftime("%Y%m%d-%H%M%S"))
    utils.create_exp_dir(args.comment, scripts_to_save=glob.glob('*.py'))
    log_format = '%(asctime)s %(message)s'
    logging.basicConfig(stream=sys.stdout, level=logging.INFO,
    format=log_format, datefmt='%m/%d %I:%M:%S %p')
    fh = logging.FileHandler(os.path.join(args.comment, 'log.txt'))
    fh.setFormatter(logging.Formatter(log_format))
    logging.getLogger().addHandler(fh)

    # models will be saved under this path
    model_save_path = os.path.join(args.comment, 'models')
    if not os.path.exists(model_save_path):
        os.mkdir(model_save_path)

    train_protocol = 'ASVspoof2019.LA.cm.train.trn_h.txt'
    dev_protocol = 'ASVspoof2019.LA.cm.train.trn_t.txt'
    eval_protocol = 'ASVspoof2019.LA.cm.dev.trl.txt'

    OUTPUT_CLASSES = 2

    # set random seed
    if args.seed:
        cudnn.benchmark = False
        torch.backends.cudnn.deterministic = True
        torch.backends.cudnn.enabled = True
        np.random.seed(args.seed)
        torch.manual_seed(args.seed)
        torch.cuda.manual_seed_all(args.seed)
        torch.cuda.manual_seed(args.seed)

    logging.info("args = %s", args)

    device = 'cuda'
    criterion = P2SGradLoss()
    criterion = criterion.cuda()

    model = Network(args.init_channels, args.layers, args, OUTPUT_CLASSES, criterion)
    model = model.cuda()
    architect = Architect(model, args)
    logging.info("param size = %fMB", utils.count_parameters_in_MB(model))

    optimizer = torch.optim.Adam(
        model.parameters(),
        args.lr,
        weight_decay=args.weight_decay)

    train_dataset = ASVRawDataset(Path(args.data), 'train', train_protocol, args.is_rand)
    dev_dataset = ASVRawDataset(Path(args.data), 'train', dev_protocol, is_rand=False)
    eval_dataset = ASVRawDataset(Path(args.data), 'dev', eval_protocol, is_rand=False)

    train_loader = torch.utils.data.DataLoader(
        dataset=train_dataset,
        batch_size=args.batch_size,
        num_workers=0,
        pin_memory=True,
        shuffle=True,
        drop_last=True,
    )
    dev_loader = torch.utils.data.DataLoader(
        dataset=dev_dataset,
        batch_size=args.batch_size,
        num_workers=0,
        pin_memory=True,
        shuffle=True,
        drop_last=True,
    )
    eval_loader = torch.utils.data.DataLoader(
        dataset=eval_dataset,
        batch_size=args.batch_size,
        num_workers=0,
        pin_memory=True,
        shuffle=True,
        drop_last=True,
    )

    begin_epoch = 0
    writer_dict = {
        'writer': SummaryWriter(args.comment),
        'train_global_steps': begin_epoch * len(train_loader),
        'valid_global_steps': begin_epoch // args.valid_freq,
    }

    best_acc = 85
    for epoch in range(args.num_epochs):
        logging.info('epoch %d ', epoch)
        genotype = model.genotype()
        logging.info('genotype = %s', genotype)

        # training
        train_acc, train_loss = train(args, train_loader, dev_loader, model, architect, criterion,
                                    args.lr, optimizer, epoch, writer_dict)

        logging.info('train_acc %f', train_acc)
        logging.info('train_loss %f', train_loss)

        # validation
        if epoch % args.valid_freq == 0:
            valid_acc, valid_loss = validate(eval_loader, model, criterion, epoch, writer_dict, validate_type='dev')
            print('*'*50)
            logging.info('dev_acc %f', valid_acc)
            logging.info('dev_loss %f', valid_loss)
            if valid_acc > best_acc:
                logging.info('best model')
            print('*'*50)

        best_acc = max(valid_acc, best_acc)
        torch.save(model.state_dict(), os.path.join(model_save_path, 'epoch_{}.pth'.format(epoch)))

max_stars_repo_name: eurecom-asp/raw-pc-darts-anti-spoofing

max_issues_repo_name: eurecom-asp/raw-pc-darts-anti-spoofing

max_forks_repo_name: eurecom-asp/raw-pc-darts-anti-spoofing


text:
# Copyright 2021 Google LLC
#
# 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.
"""Tests for confidence_intervals_util."""

from absl.testing import absltest
from absl.testing import parameterized
import apache_beam as beam
from apache_beam.testing import util
import numpy as np
from numpy import testing

from tensorflow_model_analysis.evaluators import confidence_intervals_util
from tensorflow_model_analysis.metrics import binary_confusion_matrices
from tensorflow_model_analysis.metrics import metric_types

_FULL_SAMPLE_ID = -1

class _ValidateSampleCombineFn(confidence_intervals_util.SampleCombineFn):

  def extract_output(
      self,
      accumulator: confidence_intervals_util.SampleCombineFn.SampleAccumulator
  ) -> confidence_intervals_util.SampleCombineFn.SampleAccumulator:
    return self._validate_accumulator(accumulator)

class ConfidenceIntervalsUtilTest(parameterized.TestCase):

  @parameterized.named_parameters(
      {
          'testcase_name': '_ints',
          'values': [0, 1, 2],
          'ddof': 1,
          'expected_mean': 1,
          'expected_std': np.std([0, 1, 2], ddof=1),
      }, {
          'testcase_name': '_ndarrays',
          'values': [np.array([0]), np.array([1]),
                     np.array([2])],
          'ddof': 1,
          'expected_mean': np.array([1]),
          'expected_std': np.array([np.std([0, 1, 2], ddof=1)]),
      }, {
          'testcase_name':
              '_confusion_matrices',
          'values': [
              binary_confusion_matrices.Matrices(
                  thresholds=[0.5], tp=[0], fp=[1], tn=[2], fn=[3]),
              binary_confusion_matrices.Matrices(
                  thresholds=[0.5], tp=[4], fp=[5], tn=[6], fn=[7]),
              binary_confusion_matrices.Matrices(
                  thresholds=[0.5], tp=[8], fp=[9], tn=[10], fn=[11])
          ],
          'ddof':
              1,
          'expected_mean':
              binary_confusion_matrices.Matrices(
                  thresholds=[0.5],
                  tp=np.mean([0, 4, 8]),
                  fp=np.mean([1, 5, 9]),
                  tn=np.mean([2, 6, 10]),
                  fn=np.mean([3, 7, 11])),
          'expected_std':
              binary_confusion_matrices.Matrices(
                  thresholds=[0.5],
                  tp=np.std([0, 4, 8], ddof=1),
                  fp=np.std([1, 5, 9], ddof=1),
                  tn=np.std([2, 6, 10], ddof=1),
                  fn=np.std([3, 7, 11], ddof=1)),
      })
  def test_mean_and_std(self, values, ddof, expected_mean, expected_std):
    actual_mean, actual_std = confidence_intervals_util.mean_and_std(
        values, ddof)
    self.assertEqual(expected_mean, actual_mean)
    self.assertEqual(expected_std, actual_std)

  def test_sample_combine_fn(self):
    metric_key = metric_types.MetricKey('metric')
    array_metric_key = metric_types.MetricKey('array_metric')
    missing_sample_metric_key = metric_types.MetricKey('missing_metric')
    non_numeric_metric_key = metric_types.MetricKey('non_numeric_metric')
    non_numeric_array_metric_key = metric_types.MetricKey('non_numeric_array')
    skipped_metric_key = metric_types.MetricKey('skipped_metric')
    slice_key1 = (('slice_feature', 1),)
    slice_key2 = (('slice_feature', 2),)
    # the sample value is irrelevant for this test as we only verify counters.
    samples = [
        # unsampled value for slice 1
        (slice_key1,
         confidence_intervals_util.SampleMetrics(
             sample_id=_FULL_SAMPLE_ID,
             metrics={
                 metric_key: 2.1,
                 array_metric_key: np.array([1, 2]),
                 missing_sample_metric_key: 3,
                 non_numeric_metric_key: 'a',
                 non_numeric_array_metric_key: np.array(['a', 'aaa']),
                 skipped_metric_key: 16
             })),
        # sample values for slice 1
        (slice_key1,
         confidence_intervals_util.SampleMetrics(
             sample_id=0,
             metrics={
                 metric_key: 1,
                 array_metric_key: np.array([2, 3]),
                 missing_sample_metric_key: 2,
                 non_numeric_metric_key: 'b',
                 non_numeric_array_metric_key: np.array(['a', 'aaa']),
                 skipped_metric_key: 7
             })),
        # sample values for slice 1 missing missing_sample_metric_key
        (slice_key1,
         confidence_intervals_util.SampleMetrics(
             sample_id=1,
             metrics={
                 metric_key: 2,
                 array_metric_key: np.array([0, 1]),
                 non_numeric_metric_key: 'c',
                 non_numeric_array_metric_key: np.array(['a', 'aaa']),
                 skipped_metric_key: 8
             })),
        # unsampled value for slice 2
        (slice_key2,
         confidence_intervals_util.SampleMetrics(
             sample_id=_FULL_SAMPLE_ID,
             metrics={
                 metric_key: 6.3,
                 array_metric_key: np.array([10, 20]),
                 missing_sample_metric_key: 6,
                 non_numeric_metric_key: 'd',
                 non_numeric_array_metric_key: np.array(['a', 'aaa']),
                 skipped_metric_key: 10000
             })),
        # Only 1 sample value (missing sample ID 1) for slice 2
        (slice_key2,
         confidence_intervals_util.SampleMetrics(
             sample_id=0,
             metrics={
                 metric_key: 3,
                 array_metric_key: np.array([20, 30]),
                 missing_sample_metric_key: 12,
                 non_numeric_metric_key: 'd',
                 non_numeric_array_metric_key: np.array(['a', 'aaa']),
                 skipped_metric_key: 5000
             })),
    ]

    with beam.Pipeline() as pipeline:
      result = (
          pipeline
          | 'Create' >> beam.Create(samples, reshuffle=False)
          | 'CombineSamplesPerKey' >> beam.CombinePerKey(
              _ValidateSampleCombineFn(
                  num_samples=2,
                  full_sample_id=_FULL_SAMPLE_ID,
                  skip_ci_metric_keys=[skipped_metric_key])))

      def check_result(got_pcoll):
        self.assertLen(got_pcoll, 2)
        accumulators_by_slice = dict(got_pcoll)

        self.assertIn(slice_key1, accumulators_by_slice)
        slice1_accumulator = accumulators_by_slice[slice_key1]
        # check unsampled value
        self.assertIn(metric_key, slice1_accumulator.point_estimates)
        self.assertEqual(2.1, slice1_accumulator.point_estimates[metric_key])
        # check numeric case sample_values
        self.assertIn(metric_key, slice1_accumulator.metric_samples)
        self.assertEqual([1, 2], slice1_accumulator.metric_samples[metric_key])
        # check numeric array in sample_values
        self.assertIn(array_metric_key, slice1_accumulator.metric_samples)
        array_metric_samples = (
            slice1_accumulator.metric_samples[array_metric_key])
        self.assertLen(array_metric_samples, 2)
        testing.assert_array_equal(np.array([2, 3]), array_metric_samples[0])
        testing.assert_array_equal(np.array([0, 1]), array_metric_samples[1])
        # check that non-numeric metric sample_values are not present
        self.assertIn(non_numeric_metric_key,
                      slice1_accumulator.point_estimates)
        self.assertNotIn(non_numeric_metric_key,
                         slice1_accumulator.metric_samples)
        self.assertIn(non_numeric_array_metric_key,
                      slice1_accumulator.point_estimates)
        self.assertNotIn(non_numeric_array_metric_key,
                         slice1_accumulator.metric_samples)
        # check that single metric missing samples generates error
        error_key = metric_types.MetricKey('__ERROR__')
        self.assertIn(error_key, slice1_accumulator.point_estimates)
        self.assertRegex(slice1_accumulator.point_estimates[error_key],
                         'CI not computed for.*missing_metric.*')
        # check that skipped metrics have no samples
        self.assertNotIn(skipped_metric_key, slice1_accumulator.metric_samples)

        self.assertIn(slice_key2, accumulators_by_slice)
        slice2_accumulator = accumulators_by_slice[slice_key2]
        # check unsampled value
        self.assertIn(metric_key, slice2_accumulator.point_estimates)
        self.assertEqual(6.3, slice2_accumulator.point_estimates[metric_key])
        # check that entirely missing sample generates error
        self.assertIn(
            metric_types.MetricKey('__ERROR__'),
            slice2_accumulator.point_estimates)
        self.assertRegex(slice2_accumulator.point_estimates[error_key],
                         'CI not computed because only 1.*Expected 2.*')

      util.assert_that(result, check_result)

      runner_result = pipeline.run()
      # we expect one missing samples counter increment for slice2, since we
      # expected 2 samples, but only saw 1.
      metric_filter = beam.metrics.metric.MetricsFilter().with_name(
          'num_slices_missing_samples')
      counters = runner_result.metrics().query(filter=metric_filter)['counters']
      self.assertLen(counters, 1)
      self.assertEqual(1, counters[0].committed)

      # verify total slice counter
      metric_filter = beam.metrics.metric.MetricsFilter().with_name(
          'num_slices')
      counters = runner_result.metrics().query(filter=metric_filter)['counters']
      self.assertLen(counters, 1)
      self.assertEqual(2, counters[0].committed)

  def test_sample_combine_fn_no_input(self):
    slice_key = (('slice_feature', 1),)
    samples = [
        (slice_key,
         confidence_intervals_util.SampleMetrics(
             sample_id=_FULL_SAMPLE_ID, metrics={})),
        (slice_key,
         confidence_intervals_util.SampleMetrics(sample_id=0, metrics={})),
        (slice_key,
         confidence_intervals_util.SampleMetrics(sample_id=1, metrics={})),
    ]

    with beam.Pipeline() as pipeline:
      result = (
          pipeline
          | 'Create' >> beam.Create(samples)
          | 'CombineSamplesPerKey' >> beam.CombinePerKey(
              _ValidateSampleCombineFn(
                  num_samples=2, full_sample_id=_FULL_SAMPLE_ID)))

      def check_result(got_pcoll):
        self.assertLen(got_pcoll, 1)
        accumulators_by_slice = dict(got_pcoll)
        self.assertIn(slice_key, accumulators_by_slice)
        accumulator = accumulators_by_slice[slice_key]
        self.assertEqual(2, accumulator.num_samples)
        self.assertIsInstance(accumulator.point_estimates, dict)
        self.assertIsInstance(accumulator.metric_samples, dict)

      util.assert_that(result, check_result)

if __name__ == '__main__':
  absltest.main()

reason: import numpy,from numpy


text:
botName='achrafjd-defbot'
import requests
import json
from random import sample, choice
from time import sleep
import pickle
import numpy as np

headers_vision = {'Ocp-Apim-Subscription-Key': 'YOUR_COMPUTER_VISION_KEY_HERE'}
vision_base_url = "https://ENTER_CORRECT_ENDPOINT/vision/v2.1/"
back_dict = dict()

analysed_tiles = []
previous_move = []
move_number = 0

# =============================================================================

def calculate_move(gamestate):
    global analysed_tiles
    global previous_move
    global move_number
    # Record the number of tiles so we know how many tiles we need to loop through
    num_tiles = len(gamestate["Board"])

    move_number += 1
    if gamestate["UpturnedTiles"] == []:
      print("{}. No upturned tiles for this move.".format(move_number))
    else:
      print("{}. ({}, {}) Upturned tiles for this move".format(move_number, gamestate["UpturnedTiles"][0]["Index"], gamestate["UpturnedTiles"][1]["Index"]))
    print("  gamestate: {}".format(gamestate))

    # If we have not yet used analysed_tiles (i.e. It is the first turn of the game)
    if analysed_tiles == []:
        # Create a list to hold tile information and set each one as UNANALYSED
        for index in range(num_tiles):
            # Mark tile as not analysed
            analysed_tiles.append({})
            analysed_tiles[index]["State"] = "UNANALYSED"
            analysed_tiles[index]["Subject"] = None
            analysed_tiles[index]["category"] = None
        get_categories(gamestate)

    if gamestate["UpturnedTiles"] != []:

        analyse_tiles(gamestate["UpturnedTiles"], gamestate)
        #conduct()
    else:
        # If it is not our first move of the game
        if previous_move != []:
            # then our previous move successfully matched two tiles
            # Update our analysed_tiles to mark the previous tiles as matched
            print("  MATCH: ({}, {}) - {}".format(previous_move[0], previous_move[1], analysed_tiles[previous_move[0]]["Subject"]))
            analysed_tiles[previous_move[0]]["State"] = "MATCHED"
            analysed_tiles[previous_move[1]]["State"] = "MATCHED"

    bonus_cat = gamestate['Bonus'].lower()

    if len(get_unanalysed_tiles()) == 0: #or move_number > 18:
        match = search_for_matching_tiles_category(bonus_cat)

    else:
        match = None

    if match is not None:
        # Print out the move for debugging ----------------->
        print("  Matching Move: {}".format(match))
        # Set our move to be these matching tiles
        move = match
    # If we don't have any matching tiles
    else:
        # Create a list of all the tiles that we haven't analysed yet
        unanalysed_tiles = get_unanalysed_tiles()
        # If there are some tiles that we haven't analysed yet
        if unanalysed_tiles != []:
            move = get_unequal_pair()
            print("  New tiles move: {}".format(move))
        # If the unanalysed_tiles list is empty (all tiles have been analysed)
        else:
            i = 0
            unmatched_tiles = get_unmatched_tiles()
            move = get_equal_pair()
            print("(Random) guess move: {}".format(move))

    # Store our move to look back at next turn
    previous_move = move
    # Return the move we wish to make

    return {"Tiles": move}

def get_unmatched_tiles():
    # Create a list of all the unmatched tiles
    unmatched_tiles = []
    # For every tile in the game
    for index, tile in enumerate(analysed_tiles):
        # If that tile hasn't been matched yet
        if tile["State"] != "MATCHED":
            # Add that tile to the list of unmatched tiles
            unmatched_tiles.append(index)
    # Return the list
    return unmatched_tiles

def get_unanalysed_tiles():
    # Filter out analysed tiles
    unanalysed_tiles = []
    # For every tile that hasn't been matched
    for index, tile in enumerate(analysed_tiles):
        # If the tile hasn't been analysed
        if tile["State"] == "UNANALYSED":
            unanalysed_tiles.append(index)

    return unanalysed_tiles

def analyse_tiles(tiles, gamestate):
    # For every tile in the list 'tiles'
    for tile in tiles:
        analyse_tile(tile, gamestate)

def analyse_tile(tile, gamestate):
    global known_pictures
    # If we have already analysed the tile
    if analysed_tiles[tile["Index"]]["State"] != "UNANALYSED":
        # We don't need to analyse the tile again, so stop
        return
    # Call analysis
    analyse_url = vision_base_url + "analyze"
    params_analyse = {'visualFeatures': 'categories,tags,description,faces,imageType,color,adult',
                      'details': 'celebrities,landmarks'}
    data = {"url": tile["Tile"]}
    msapi_response = microsoft_api_call(analyse_url, params_analyse, headers_vision, data)
    #print("  API Result tile #{}: {}".format(tile["Index"], msapi_response))
    # Check if the subject of the tile is a landmark

    if analysed_tiles[tile["Index"]]["category"] == 'animals':
        subject = check_for_animal(msapi_response, gamestate["AnimalList"])

    elif analysed_tiles[tile["Index"]]["category"] == 'landmarks':
        subject = check_for_landmark(msapi_response)

    elif analysed_tiles[tile["Index"]]["category"] == 'words':
        subject = check_for_text(tile)
    print('Marked {} as {}'.format(tile['Index'], subject))
    # Remember this tile by adding it to our list of known tiles
    # Mark that the tile has now been analysed

    analysed_tiles[tile["Index"]]["State"] = "ANALYSED"
    analysed_tiles[tile["Index"]]["Subject"] = subject
    #analysed_tiles[tile["Index"]]["category"] = cat

def check_for_animal(msapi_response, animal_list):
    # Initialise our subject to None
    subject = None
    # If the Microsoft API has returned a list of tags
    if "tags" in msapi_response:
        for tag in sorted(msapi_response["tags"], key=lambda x: x['confidence'], reverse=True):
            if "name" in tag and tag["name"] in animal_list:
                subject = tag["name"].lower()
                break
    return subject

# ----------------------------------- TODO -----------------------------------
def get_categories(gamestate):
    get_backs(gamestate['TileBacks'])
    for index, tile in enumerate(analysed_tiles):
        back = gamestate['TileBacks'][index]
        tile['category'] = back_dict[back]

def get_backs(back_list):
    analyse_url = vision_base_url + "ocr"
    params_analyse = {}
    for back in set(back_list):
        data = {"url": back}
        msapi_response = microsoft_api_call(analyse_url, params_analyse, headers_vision, data)
        back_dict[back] = msapi_response['regions'][0]['lines'][0]['words'][0]['text'].lower() + 's'

def get_unequal_pair():
    unanalysed_tiles = get_unanalysed_tiles()
    move = None
    for i in unanalysed_tiles:
        for j in unanalysed_tiles:
            if j <= i:
                continue
            print('for loop for not matching categories')
            if analysed_tiles[i]['category'] != analysed_tiles[j]['category']:
                move = [i,j]
                return move

    if move is None:
        print('Sampling because no unmatching tiles...')
        move = sample(unanalysed_tiles, 2)
    return move

def get_equal_pair():
    print('trying to match an equal pair, because no match found')
    unmatched_tiles = get_unmatched_tiles()
    move = None
    for i in unmatched_tiles:
        for j in unmatched_tiles:
            if j <= i:
                continue
            print('for loop for matching pairs')
            if i != j and analysed_tiles[i]['category'] == analysed_tiles[j]['category']:
                move = [i,j]
                return move

    if move is None:
        print('Sampling because no matching tiles...')
        move = sample(unmached_tiles, 2)
    return move

def check_for_landmark(msapi_response): # NOTE: you don't need a landmark_list
    subject = None

    for category in msapi_response["categories"]:
            # If the tag has a name and that name is one of the animals in our list
            if "detail" in category and "landmarks" in category["detail"] and category["detail"]["landmarks"]:
                # Record the name of the animal that is the subject of the tile
                # (We store the subject in lowercase to make comparisons easier)
                subject = category["detail"]["landmarks"][0]["name"].lower()
                # Print out the animal we have found here for debugging ----------------->
                print("  Landmark: {}".format(subject))
                # Exit the for loop
                break
    # Return the subject
    return subject

def check_for_text(tile):
    # Initialise our subject to None
    subject = None
    analyse_url = vision_base_url + "ocr"
    params_analyse = {}
    data = {"url": tile["Tile"]}
    msapi_response = microsoft_api_call(analyse_url, params_analyse, headers_vision, data)
    if msapi_response['regions'] != []:
        if "text" in msapi_response['regions'][0]['lines'][0]['words'][0]:
            subject = msapi_response['regions'][0]['lines'][0]['words'][0]['text'].lower()

    return subject

def search_for_matching_tiles():
    # For every tile subject and its index
    for index_1, tile_1 in enumerate(analysed_tiles):
        # Loop through every tile subject and index
        for index_2, tile_2 in enumerate(analysed_tiles):
            # If the two tile's subject is the same and isn't None and the tile
            # hasn't been matched before, and the tiles aren't the same tile
            if tile_1["State"] == tile_2["State"] == "ANALYSED" and tile_1["Subject"] == tile_2["Subject"] and tile_1["Subject"] is not None and index_1 != index_2:
                # Choose these two tiles
                # Return the two chosen tiles as a list
                return [index_1, index_2]
    # If we have not matched any tiles, return no matched tiles
    return None

def search_for_matching_tiles_category(category):
    print('Entering Search with category and following data: ')
    for i in get_unanalysed_tiles():
        print(analysed_tiles[i])
    print('Bonus category: ', category)
    for index_1, tile_1 in enumerate(analysed_tiles):
        # Loop through every tile subject and index
        for index_2, tile_2 in enumerate(analysed_tiles):
            # If the two tile's subject is the same and isn't None and the tile
            # hasn't been matched before, and the tiles aren't the same tile
            if tile_1["State"] == tile_2["State"] == "ANALYSED" and tile_1["Subject"] == tile_2["Subject"] and tile_1["Subject"] is not None and index_1 != index_2:
                if tile_1['category'] == tile_2['category'] == category:
                    return [index_1, index_2]
    # If we have not matched any tiles, return no matched tiles
    print('NO PAIR FOR BONUS CATEGORY {}'.format(category))
    print('Enter normal match with: ', [analysed_tiles[a] for a in get_unmatched_tiles()])
    return search_for_matching_tiles()

#def conduct():
#    for category in ['words', 'animals', 'landmarks']:
#        ind = np.where((analysed_tiles['category'] == category) & ((analysed_tiles['State']='UNANALYSED') | (analysed_tiles['Subject'] is None)))
#        if len(ind) == 1:
#            subs, counts = np.unique([a['Subject'] for a in analysed_tiles], return_count = True)
#            analysed_tiles[ind]['State'] = 'ANALYSED'
#            analysed_tiles[ind]['Subject'] = subject

def microsoft_api_call(url, params, headers, data):
    # Make API request
    response = requests.post(url, params=params, headers=headers, json=data)
    # Convert result to JSON
    res = response.json()
    # While we have exceeded our request volume quota
    while "error" in res and res["error"]["code"] == "429":
        # Wait for 1 second
        sleep(1)
        # Print that we are retrying the API call here ----------------->
        print("Retrying")
        # Make API request
        response = requests.post(url, params=params, headers=headers, json=data)
        # Convert result to JSON
        res = response.json()
    # Print the result of the API call here for debugging ----------------->
    # print("  API Result: {}".format(res))
    # Return JSON result of API request
    return res

# Test the user's subscription key
#
# Raise an error if the user's API key is not valid for the Microsoft
# Computer Vision API call
def valid_subscription_key():
    # Make a computer vision api call
    test_api_call = microsoft_api_call(vision_base_url + "analyze", {}, headers_vision, {})

    if "error" in test_api_call:
        raise ValueError("Invalid Microsoft Computer Vision API key for current region: {}".format(test_api_call))

# Check the subscription key
valid_subscription_key()


text:
#!/usr/bin/env python

import os,sys,damask
import string
from optparse import OptionParser
import numpy as np

scriptID   = string.replace('$Id: centered_data.py 125 2015-10-30 03:37:22Z chakra34 $','\n','\\n')
scriptName = os.path.splitext(scriptID.split()[1])[0]

parser = OptionParser(option_class=damask.extendableOption, usage='%prog options [file[s]]', description = """
Outputs a new grid for the given data field to be centered about the given center and also specifies the offset of the origin.

""", version = scriptID)

parser.add_option('-c','--center',
                  dest = 'center',
                  type = 'int', nargs = 2, metavar = 'int int',
                  help = 'center of the new image ')

parser.add_option('-s', '--size',
                  dest = 'size',
                  action = 'store_true',
                  help = 'if the center position is provided in terms of size [%default]')

parser.add_option('-p','--pix_size',
                  dest = 'pix_size',
                  type = 'string', metavar = 'eval',
                  help = 'pixel size [%default]')

parser.set_defaults(size       = False,
                    fill       = 0.0,
                    pix_size   = '10.0e-6/255',
                   )

(options,filenames) = parser.parse_args()

options.pix_size = eval(options.pix_size)

if options.center == None :
  print "The center has to be provided !!!"
  sys.exit()

else :
# --- loop over input files ------------------------------------------------------------------------

  if filenames == []: filenames = [None]

  for name in filenames:
    try:
      table = damask.ASCIItable(name = name,
                                labeled=False,
                                buffered = False,
                                readonly = True)
    except: continue
    damask.util.report(scriptName,name)

    table.head_read()
    table.data_readArray()
    if options.size :
      options.center = int( options.center / options.pix_size )

    dimension = table.data.shape
    new_grid_x = 2 * max(options.center[0],(dimension[0] - options.center[0]))
    new_grid_y = 2 * max(options.center[1],(dimension[1] - options.center[1]))
    offset = np.array([0,0])
    if new_grid_x/2 == (dimension[0] - options.center[0]) :
      offset[0] = -(dimension[0] - 2 * options.center[0])
    if new_grid_y/2 == (dimension[1] - options.center[1]) :
      offset[1] = -(dimension[1] - 2 * options.center[1])
    print "new_grid",new_grid_x,new_grid_y,"offset",offset[0],offset[1]
    table.close()


text:
from skimage.feature import corner_harris, corner_peaks
import numpy as np
from scipy import signal as sig
from skimage.io import imread
from skimage.color import rgb2gray
import matplotlib.pyplot as plt

img = imread('data/NotreDame2.jpg')
imggray = rgb2gray(img)

plt.figure(figsize=(10, 10))
plt.imshow(imggray, cmap="gray")
plt.axis("off")
plt.show()

def gradient_x(imggray):
    # Sobel operator kernels.
    kernel_x = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]])
    return sig.convolve2d(imggray, kernel_x, mode='same')

def gradient_y(imggray):
    kernel_y = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]])
    return sig.convolve2d(imggray, kernel_y, mode='same')

I_x = gradient_x(imggray)
I_y = gradient_y(imggray)

Ixx = I_x**2
Ixy = I_y*I_x
Iyy = I_y**2

# Loop through image and find our corners
k = 0.05

height, width = imggray.shape
harris_response = []
window_size = 6
offset = window_size//2
for y in range(offset, height-offset):
    for x in range(offset, width-offset):
        Sxx = np.sum(Ixx[y-offset:y+1+offset, x-offset:x+1+offset])
        Syy = np.sum(Iyy[y-offset:y+1+offset, x-offset:x+1+offset])
        Sxy = np.sum(Ixy[y-offset:y+1+offset, x-offset:x+1+offset])

        # Find determinant and trace, use to get corner response
        det = (Sxx * Syy) - (Sxy**2)
        trace = Sxx + Syy
        r = det - k*(trace**2)

        harris_response.append([x, y, r])

img_copy = np.copy(img)

for response in harris_response:
    x, y, r = response
    if r > 0:
        img_copy[y, x] = [0, 0, 255]

plt.figure(figsize=(20, 20))
plt.imshow(img_copy)
plt.show()

# Harris corner detection using skimage library
# print corner_harris(ximage)
coords = corner_peaks(corner_harris(imggray))

fig, ax = plt.subplots()
ax.imshow(img, interpolation='nearest', cmap=plt.cm.gray)
ax.plot(coords[:, 1], coords[:, 0], '.r', markersize=3)