text:
import cv2
import numpy as np
import os
import math

face_cascade = cv2.CascadeClassifier('../Cascades/haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('../Cascades/haarcascade_eye.xml')

parser = argparse.ArgumentParser()
parser.add_argument('-pic', type=str)
parser.add_argument('-pic_new',type=str)
args = parser.parse_args()

def square(x):
	return x * x

def distance_sqr(x1, y1, x2, y2):
	return square(x1-x2) + square(x2-y2)

def face_detector(image, cascade, cascade2):
	grayImage = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
	equalImage = cv2.equalizeHist(grayImage)
	faces = cascade.detectMultiScale(equalImage, scaleFactor=1.3, minNeighbors=2)

	for(x,y,w,h) in faces:
		image1 = image[y:y+h, x:x+w]
		image_high = image1
		eyes = cascade2.detectMultiScale(image1)
		for (ex, ey, ew, eh) in eyes:
			center_x = ex + ew * 0.5
			center_y = ey + eh * 0.5
			eyes1 = image1[ey:ey+eh, ex:ex+ew]
			eyes2 = eyes1
			kernel_radius = min(ew, eh) * 0.4
			for r in range(eh):
				for c in range(ew):
					diff_x = c - ew*0.5
					diff_y = r - eh*0.5
					distance = math.sqrt(diff_x * diff_x + diff_y * diff_y)
					p_x = 0
					p_y = 0
					if distance <= kernel_radius:
						re = (1 - math.cos(distance / kernel_radius * 2 * math.pi)) * 2.5
						p_x = -diff_x * (re / kernel_radius)
						p_y = -diff_y * (re / kernel_radius)
					if p_x < 0 :
						p_x  = 0
					if p_y < 0 :
						p_y = 0
					eyes2[r,c] = eyes1[int(r + p_y),int(c + p_x)]
			image1[ey:ey+eh, ex:ex+ew] = eyes2
		image_high1 = cv2.bilateralFilter(image_high, 15, 37, 37)
		image_high2 = image_high1 - image1 + 128
		image_high3 = cv2.GaussianBlur(image_high1,(1, 1),0)
		image_high4 = image1 + 2 * image_high3 - 255
		final = image1 * 0.45 + image_high4 * 0.55
		c_x = x + w * 0.5
		c_y = y + h * 0.5
		radius = min(w, h) * 2
		image_high4 = image_high3
		for row in range(h):
			for col in range(w):
				diff_x = col - w * 0.5
				diff_y = col - h * 0.5
				distance = math.sqrt(square(col - w*0.5) + square(row - h*0.5))
				m_x = 0
				m_y = 0
				if distance <= radius:
					re = (1 - math.cos(distance / radius * 2 * math.pi)) * 2
					m_x = -diff_x * (re / radius)
					m_y = -diff_y * (re / radius)
				if m_x < 0:
					m_x = 0
				if m_y < 0:
					m_y = 0
				image_high4[row,col] = image_high3[int(row + m_y), int(col + m_x)]
		image[y:y+h, x:x+w] = image_high4
	return image

img = cv2.imread("PHOTO/"+args.pic+".jpg")
show_image = face_detector(img, face_cascade, eye_cascade)
cv2.imwrite('PHOTO/'+args.pic_new+'.jpg', show_image)

max_stars_repo_name: LocalXpress/Leonardo

max_issues_repo_name: LocalXpress/Leonardo

max_forks_repo_name: LocalXpress/Leonardo


text:
import itertools
import json
import os
import shutil
import subprocess
import time

import numpy as np
import pandas as pd
import yaml

class SolutionComparator:
    def __init__(self, data_sizes, input_sizes, solutions_to_compare="all"):

        if solutions_to_compare == "all":
            self.solutions_to_compare = next(
                os.walk(os.path.join("..", "solutions"))
            )[1]
        elif isinstance(solutions_to_compare, str):
            self.solutions_to_compare = [solutions_to_compare]
        else:
            self.solutions_to_compare = solutions_to_compare

        self.input_dicts = {
            d_size: {isize: self._get_input(isize) for isize in input_sizes}
            for d_size in data_sizes
        }
        self.comparison_data = []
        self._tmp_dir = "tmp"

    def _cleanup(self):
        shutil.rmtree(self._tmp_dir, ignore_errors=True)

    @staticmethod
    def _get_input(size):
        return [size]

    @staticmethod
    def _dump_data(size, data_path):
        with open(data_path, "w") as fp:
            fp.write(f"{size} nothing")

    def _try_running_command(
        self, command_dic: dict, command_name: str, act_solution: str
    ):
        command = command_dic.get(command_name)
        if command:
            print(f"running {command_name} for {act_solution}")

            command_start_time = time.time()
            _proc = subprocess.Popen(
                command.split(),
                # stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                cwd=self._tmp_dir,
            )
            _proc.wait()
            _stdout, _stderr = _proc.communicate()
            command_time = time.time() - command_start_time
            if _proc.returncode != 0:
                self._cleanup()
                print(f"\n\n{act_solution} {command_name} ERROR:\n--")
                print(_stderr.decode("utf-8"))
                raise RuntimeError(_stderr.decode("utf-8"))

        else:
            print(f"no {command_name} for {act_solution}")
            command_time = None

        return command_time

    def run_comparison(self):

        for act_solution in self.solutions_to_compare:
            print(f"solution: {act_solution}")
            self._cleanup()
            act_solution_path = os.path.join("..", "solutions", act_solution)
            shutil.copytree(act_solution_path, self._tmp_dir)
            try:
                commands = yaml.safe_load(
                    open(os.path.join("tmp", "commands.yaml"))
                )
            except FileNotFoundError:
                self._cleanup()
                raise FileNotFoundError(
                    f"no commands.yaml in solution directory: {act_solution}"
                )

            self._try_running_command(
                commands, "setup-env-command", act_solution
            )

            for data_size, input_dict in self.input_dicts.items():

                data_path = os.path.join("data", f"{data_size}.csv")
                shutil.copy(data_path, os.path.join(self._tmp_dir, "data.csv"))

                self._try_running_command(
                    commands, "etl-command", act_solution
                )

                for input_size, input_object in input_dict.items():
                    print(f"input size: {input_size} - data size: {data_size}")

                    json.dump(
                        input_object,
                        open(os.path.join(self._tmp_dir, "inputs.json"), "w"),
                    )

                    calc_time = self._try_running_command(
                        commands, "process-command", act_solution
                    )
                    if calc_time is None:
                        self._cleanup()
                        raise ValueError(
                            "no process-command specified "
                            f"in {act_solution} commands.yaml"
                        )

                    try:
                        output_list = json.load(
                            open(os.path.join(self._tmp_dir, "outputs.json"))
                        )
                    except FileNotFoundError:
                        self._cleanup()
                        raise RuntimeError(
                            f"solution {act_solution} "
                            "did not produce an outputs.json"
                        )

                    self.comparison_data.append(
                        {
                            "calc_time": calc_time,
                            "input_size": input_size,
                            "data_size": data_size,
                            "solution": act_solution,
                            "output_list": output_list.copy(),
                        }
                    )

                self._try_running_command(
                    commands, "cleanup-command", act_solution
                )

        self._cleanup()

    def plot_comparison(self):

        if self.comparison_data:
            pd.DataFrame(self.comparison_data).pivot_table(
                index=["data_size", "input_size"],
                columns="solution",
                values="calc_time",
            ).plot.bar(figsize=(13, 7))
        else:
            print("run the comparison first")

    def output_comparison(self):

        if self.comparison_data:
            return (
                pd.DataFrame(self.comparison_data)
                .groupby("solution")
                .apply(
                    lambda df: pd.DataFrame(
                        itertools.chain(*df["output_list"].tolist())
                    ).reset_index(drop=True)
                )
                .fillna(0)
                .pipe(
                    lambda df: df.reset_index().pivot_table(
                        columns="solution",
                        index=[
                            "level_1",
                            *df.select_dtypes(exclude=np.number).columns,
                        ],
                    )
                )
            )
        else:
            print("run the comparison first")

ext: py

reason: import numpy


text:
import statistics

class PlayerAi:
    """
    Represents a chess-playing AI.
    """

    def __init__(self, model):
        """
        ``model`` - A keras model which predicts the fitness of a board state
        given a feature vector representing the board.
        """

        self.__model = model

    def get_move(self, board, decisiveness=None, verbose=False):
        """
        Given a board state, returns the best next move according to the model.
        """
        from numpy import array
        from numpy.random import choice
        from numpy import sort

        fitnesses = []
        moves = []
        max_fitness = None;
        best_move = None;

        for move in board.legal_moves:
            # Find next board state.
            end_board = board.copy()
            end_board.push(move)
            pieces = self.__board_to_sample(end_board)

            # Predict fitness.
            fitness = self.__model.predict([pieces])[0][0]
            fitnesses.append(fitness)
            moves.append(move)

            # Update best move if needed.
            if ((max_fitness is None) or (max_fitness < fitness)):
                max_fitness = fitness
                chosen_move = move
        fitness = max_fitness
        fitnesses = array(fitnesses, dtype='float64')

        if (not(decisiveness is None)):
            probabilities = array(fitnesses)
            probabilities = probabilities ** decisiveness
            probabilities = probabilities / probabilities.sum()
            if (verbose):
                weights = -sort(-probabilities)
                weights = (100 * weights / weights.max()).round().astype('int')
                print('Weights of choices: {0}'\
                        .format(weights.tolist()))
            chosen_move = choice(moves, p=probabilities)
            fitness = fitnesses[moves.index(chosen_move)]

        if (verbose):
            print('Number of moves: {0}'.format(len(fitnesses)))
            if (len(fitnesses) > 1):
                print('Mean fitness: {0}'.format(statistics.mean(fitnesses)))
                print('Median fitness: {0}'.format(statistics.median(fitnesses)))
                print('Standard deviation: {0}'.format(statistics.stdev(fitnesses)))
                print('Minimum fitness: {0}'.format(min(fitnesses)))
                print('Maximum fitness: {0}'.format(max(fitnesses)))
            print('Fitness = {0}'.format(fitness))

        return chosen_move

    def __board_to_sample(self, board):
        """
        Converts a chess Board into a feature vector recognized by the model.
        """

        pieces = [0] * 64
        encoding = {'P':1,'R':2,'N':3,'B':4,'Q':5,'K':6,'p':-1,'r':-2,'n':-3,'b':-4,'q':-5,'k':-6}

        for i, piece in board.piece_map().items():
            pieces[i] = encoding[piece.symbol()]

        return pieces

max_stars_repo_name: ucdchessai/chess-ai

max_issues_repo_name: ucdchessai/chess-ai

max_forks_repo_name: ucdchessai/chess-ai

reason: from numpy


text:
# $Id$
#
# Copyright (C) 2007-2008 Greg Landrum
#   All Rights Reserved
#
""" Implementation of the clustering algorithm published in:
  Butina JCICS 39 747-750 (1999)

"""
import numpy
from rdkit import RDLogger
logger = RDLogger.logger()

def EuclideanDist(pi, pj):
  dv = numpy.array(pi) - numpy.array(pj)
  return numpy.sqrt(dv * dv)

def ClusterData(data, nPts, distThresh, isDistData=False, distFunc=EuclideanDist, reordering=False):
  """  clusters the data points passed in and returns the list of clusters

    **Arguments**

      - data: a list of items with the input data
        (see discussion of _isDistData_ argument for the exception)

      - nPts: the number of points to be used

      - distThresh: elements within this range of each other are considered
        to be neighbors

      - isDistData: set this toggle when the data passed in is a
          distance matrix.  The distance matrix should be stored
          symmetrically. An example of how to do this:

            dists = []
            for i in range(nPts):
              for j in range(i):
                dists.append( distfunc(i,j) )

      - distFunc: a function to calculate distances between points.
           Receives 2 points as arguments, should return a float

      - reordering: if this toggle is set, the number of neighbors is updated
           for the unassigned molecules after a new cluster is created such
           that always the molecule with the largest number of unassigned
           neighbors is selected as the next cluster center.

    **Returns**

      - a tuple of tuples containing information about the clusters:
         ( (cluster1_elem1, cluster1_elem2, ...),
           (cluster2_elem1, cluster2_elem2, ...),
           ...
         )
         The first element for each cluster is its centroid.

  """
  if isDistData and len(data) > (nPts * (nPts - 1) / 2):
    logger.warning("Distance matrix is too long")
  nbrLists = [None] * nPts
  for i in range(nPts):
    nbrLists[i] = []

  dmIdx = 0
  for i in range(nPts):
    for j in range(i):
      if not isDistData:
        dij = distFunc(data[i], data[j])
      else:
        dij = data[dmIdx]
        dmIdx += 1
      if dij <= distThresh:
        nbrLists[i].append(j)
        nbrLists[j].append(i)
  # sort by the number of neighbors:
  tLists = [(len(y), x) for x, y in enumerate(nbrLists)]
  tLists.sort(reverse=True)

  res = []
  seen = [0] * nPts
  while tLists:
    _, idx = tLists.pop(0)
    if seen[idx]:
      continue
    tRes = [idx]
    for nbr in nbrLists[idx]:
      if not seen[nbr]:
        tRes.append(nbr)
        seen[nbr] = 1
    # update the number of neighbors:
    # remove all members of the new cluster from the list of
    # neighbors and reorder the tLists
    if reordering:
      # get the list of affected molecules, i.e. all molecules
      # which have at least one of the members of the new cluster
      # as a neighbor
      nbrNbr = [nbrLists[t] for t in tRes]
      nbrNbr = frozenset().union(*nbrNbr)
      # loop over all remaining molecules in tLists but only
      # consider unassigned and affected compounds
      for x, y in enumerate(tLists):
        y1 = y[1]
        if seen[y1] or (y1 not in nbrNbr):
          continue
        # update the number of neighbors
        nbrLists[y1] = set(nbrLists[y1]).difference(tRes)
        tLists[x] = (len(nbrLists[y1]), y1)
      # now reorder the list
      tLists.sort(reverse=True)
    res.append(tuple(tRes))
  return tuple(res)

max_stars_repo_name: kazuyaujihara/rdkit

max_issues_repo_name: kazuyaujihara/rdkit

max_forks_repo_name: bp-kelley/rdkit


text:
import streamlit as st
import altair as alt
import pandas as pd
import numpy as np

rng = np.random.default_rng()

img_bull = 'https://upload.wikimedia.org/wikipedia/commons/0/03/BULL.png'
img_bear = 'https://upload.wikimedia.org/wikipedia/commons/1/1e/JB_PRODUCE_logo_oficial.png'
img_straight = 'https://static.thenounproject.com/png/1494756-200.png'

animal_dict = {"Bull":img_bull, "Bear":img_bear, "Straight":img_straight}

series_comm = pd.read_csv("https://raw.githubusercontent.com/ChristopherDavisUCI/Math_CEO/main/Python_MathCEO/BearBull2/commodities.csv",usecols=[0,1],index_col=0,thousands=",",
                          squeeze=True,dtype={"Commodity":"string","Price":"float64"})

st.title("Bear Markets and Bull Markets")

cols = st.beta_columns([x for _ in range(5) for x in [1.3,1]])

for i in range(0,len(cols),2):
    with cols[i]:
        st.image("https://github.com/ChristopherDavisUCI/Math_CEO/blob/main/Python_MathCEO/BearBull2/images/bear.png?raw=true")

    with cols[i+1]:
        st.image("https://github.com/ChristopherDavisUCI/Math_CEO/blob/main/Python_MathCEO/BearBull2/images/bull.png?raw=true")

st.header("Introduction")

st.markdown('''
    The price of a commodity is shown for a variety of days.
    If the price is lower than it was 5 days ago, we call it a "bear" market.
    If the price is higher than it was 5 days ago, we call it a "bull" market.
    (Why these names?  Imagine a bull pushing someone up into the air... higher!  Imagine a bear dragging someone down to the ground... lower!)

For example,
    in the sample picture, we are in a bull market on Day 12, because the price is higher than it was on Day 7.
    Notice how the price on Day 11 doesn't matter, only the price on Day 7, because we only care about the price five days earlier.  Do you see why Day 7 is a bear market?
    ''', unsafe_allow_html=True)

st.image("https://github.com/ChristopherDavisUCI/Math_CEO/blob/main/Python_MathCEO/BearBull2/images/sample1.png?raw=true", use_column_width='auto')

st.markdown('''
    The first five prices represent neither bear markets nor bull markets, because we don't know what the price was five days earlier.  The values for all the other days in this sample market are shown below.
''')

st.image("https://github.com/ChristopherDavisUCI/Math_CEO/blob/main/Python_MathCEO/BearBull2/images/sample2.png?raw=true", use_column_width='auto')

st.header("Your challenge")

def get_score(x,animal):
    if animal == "Bear":
        other = "Bull"
    else:
        other = "Bear"
    if x == animal_dict[animal]:
        return 1
    elif x == animal_dict[other]:
        return -0.5
    else:
        return 0

interval = 5

def choose_image(row):
    if row["Bear"]:
        return img_bear
    elif row["Bull"]:
        return img_bull
    else:
        return img_straight

def get_comm(name, pts):
    price = series_comm[name]
    prices = price+price*(0.1*np.random.randn(pts)).cumsum()
    return [round(x,2) for x in prices]

def make_chart(name,pts,animal):
    max_score = 0
    while max_score == 0:
        df = pd.DataFrame({'x':range(1,pts+1),'y':get_comm(name, pts),'img':np.zeros(pts)})
        df["Bear"] = False
        df["Bull"] = False
        df.loc[interval:,'Bull'] = (df.iloc[:-interval]['y'].to_numpy() < df.iloc[interval:]['y'].to_numpy())
        df.loc[interval:,'Bear'] = (df.iloc[:-interval]['y'].to_numpy() > df.iloc[interval:]['y'].to_numpy())
        df["img"] = df.apply(choose_image, axis=1)
        df.loc[:,'score'] = df['img'].map(lambda x: get_score(x,animal))

        max_score = (df['img']==animal_dict[animal]).sum()

    answers_selection = alt.selection_multi(on='click', toggle=False, empty='none',fields = ['x'], init=[{'x':[1,2,3]}])

    base = alt.Chart(df).mark_image(width=20,height=20).encode(
        x=alt.X('x:O', axis = alt.Axis(title="Day",labelAngle=0,tickCount=len(df),labelOverlap="parity")),
        y=alt.Y('y', axis = alt.Axis(title="Price in Dollars"), scale=alt.Scale(zero=False)),
        tooltip = [alt.Tooltip('x',title="Day"),alt.Tooltip('y',title="Price", format='$,.2f')],
        size = alt.value(50)
    ).properties(
        width=700,
        height=300
    )

    base = base.add_selection(
        answers_selection
    )

    base = base.encode(
        url=alt.condition(answers_selection, 'img', alt.value(img_straight))
    )

    text = alt.Chart(df).transform_filter(answers_selection).mark_text(
        align='left',
        baseline='top',
    ).encode(
        x=alt.value(5),
        y=alt.value(-30),
        color = alt.condition(f"datum.total_score == {max_score}",alt.value("green"),alt.value("black")),
        size = alt.condition(f"datum.total_score == {max_score}",alt.value(30),alt.value(14))
    ).transform_aggregate(
        total_score='sum(score)'
    ).transform_calculate(
        text_base=f'Your current score: '+alt.datum.total_score
    ).encode(
        text = alt.condition(f"datum.total_score == {max_score}",alt.value("You win!! "*5),'text_base:N'),
    )

    comb = alt.layer(base,text).properties(
        title={
          "text": ["","",f"Price of {name}"],
          "subtitle": [f'Click all of the {animal}s.',f"Maximum possible score: {max_score}",""],
          "color": "black",
          "fontSize": 18,
          "subtitleFontSize":14,
          "subtitleColor": "green"
        },
    )

    st.write(comb)
    return None

st.markdown('''
    In each of the charts below, you are asked to click on either the
    days with a bull market or the days with a bear market.  Try to do this visually, but sometimes it's "too close to call", and then you
    can put your mouse over the faces to see the exact numbers.

    **Warning!**  If you click an incorrect face, you won't be able to get the maximum possible score.  You get 1 point for a correct click and you lose 0.5 points for an incorrect click.
''', unsafe_allow_html=True)

st.button("Get new charts")

empty_list = []

no_charts = 10

comms = rng.choice(series_comm.index,replace=False,size=no_charts + 1)

for i in range(no_charts):
    animal = rng.choice(["Bear","Bull"])
    st.markdown("---")
    st.write("")
    make_chart(comms[i],10+2*i,animal)

animal = rng.choice(["Bear","Bull"])
st.markdown("---")
st.header("The ultimate test :skull:")
st.write("")
st.write("")
make_chart(comms[i+1],100,animal)


text:
from flask import Flask, render_template, request
import csv

import pandas as pd
import numpy as np
from rank_bm25 import BM25Okapi
###########
def data_process(train_data,test_data,whole_data):
    #### READ Train, test, and all replies data ####
    file = open(train_data)
    read_csv = csv.reader(file)
    train = []
    for row in read_csv:
        train.append(row)
    train= train[1:]
    train = pd.DataFrame(train,columns=['message_id','response_id','rating'])

    file = open(test_data)
    read_csv = csv.reader(file)
    test = []
    for row in read_csv:
        test.append(row)
    test= test[1:]
    test = pd.DataFrame(test,columns=['message_id','response_id'])

    tsv = open(whole_data)
    read_tsv = csv.reader(tsv, delimiter="\t")
    data =[]
    for row in read_tsv:
        data.append(row)
    data = pd.DataFrame(data)
    data.rename(columns=data.iloc[0], inplace = True)
    data.drop([0], inplace = True)

    #### Merge data ####################################
    merged_train = pd.merge(train[['message_id']], data[['message_id','message']].drop_duplicates(subset="message_id"), on='message_id', how='left')
    merged_test = pd.merge(test[['message_id']], data[['message_id','message']].drop_duplicates(subset="message_id"), on='message_id', how='left')
    merged2 = pd.merge(train[['response_id','rating']], data[['response_id','response']], on='response_id', how='left')
    merged3 = pd.merge(test[['response_id']], data[['response_id','response']], on='response_id', how='left')

    merged_train['response_id'] = list(merged2['response_id'])
    merged_train['response'] = list(merged2['response'])
    merged_train['rating']= list(merged2['rating'])

    merged_test['response_id'] = list(merged3['response_id'])
    merged_test['response'] = list(merged3['response'])
    ### save to csv
    merged_train[['response']].to_csv('response_without_id_train.csv',index=False)
    merged_test[['response']].to_csv('response_without_id_test.csv',index=False)
    merged_train.to_csv('merged_train.csv',index=False)
    merged_test.to_csv('merged_test.csv',index=False)

    #### get message #####
    me = merged_train[['message']].drop_duplicates(subset="message")
    melist = me['message'].to_list()
    with open('query_train.txt', 'w') as filehandle:
        filehandle.writelines("%s\n" % reid for reid in melist)

    onlyme = merged_test[['message']].drop_duplicates(subset="message")
    melist = onlyme['message'].to_list()
    with open('query_test.txt', 'w') as filehandle:
        filehandle.writelines("%s\n" % reid for reid in melist)

app = Flask(__name__)

@app.route("/")
def home():
    return render_template("home.html")

@app.route("/get")
def get_bot_response():

    what_the_user_said = request.args.get('msg')
    #train_path = 'message_without_id_train.csv'
    train_path_res = 'response_without_id_train.csv'

    #### the following code is to use two bm25, match query to message first and then match message to response
    # file = open(train_path)
    # read_csv = csv.reader(file)
    # corpus1 = []
    # for row in read_csv:
    #     corpus1.append(row[0])
    # tokenized_corpus = [doc.split(" ") for doc in corpus1]
    # bm25 = BM25Okapi(tokenized_corpus)
    # tokenized_query = what_the_user_said.split(" ")
    # doc_scores = bm25.get_scores(tokenized_query)
    # result = bm25.get_top_n(tokenized_query, corpus1, n=1)

    # query = result[0]

    # message = pd.read_csv('merged_train.csv')
    # message['re_id']=message['response_id']+' '+ message['response']
    # message_id = message[['message_id']].drop_duplicates(subset="message_id")['message_id'].to_list()
    # corpus = []
    # for i in message_id:
    #     response = message[message['message_id']==i]['re_id'].to_list()
    #     corpus.append(response)

    # q = []
    # with open('query_train.txt') as file:
    #     for i in file:
    #         q.append(i.strip())

    # corpus_index = q.index(query)

    # tokenized_corpus1 = [doc.split(" ") for doc in corpus[corpus_index]]
    # BM25 = BM25Okapi(tokenized_corpus1)
    # tokenized_query1 = what_the_user_said.split(" ")
    # doc_scores1 = BM25.get_scores(tokenized_query1)
    # result1 = BM25.get_top_n(tokenized_query1, corpus[corpus_index], n=10)

    # if len(result1) !=0:
    #     return result1[0].split(' ', 1)[1]

    file = open(train_path_res)
    read_csv = csv.reader(file)
    corpus = []
    for row in read_csv:
        corpus.append(row[0])
    tokenized_corpus = [doc.split(" ") for doc in corpus]
    bm25 = BM25Okapi(tokenized_corpus)
    tokenized_query = what_the_user_said.split(" ")
    doc_scores = bm25.get_scores(tokenized_query)
    result = bm25.get_top_n(tokenized_query, corpus, n=1)

    if len(result) !=0:
        return result[0]
    else:
        return "I don't know"

if __name__ == "__main__":

    train_data = "aggregated-hw3-ratings.train.csv"
    test_data ="aggregated-hw3-rating.test.csv"
    whole_data = "chatbot-replies.tsv"
    data_process(train_data,test_data,whole_data)
    app.run()

max_stars_repo_name: Siyinz/Info-Retrieval-ChatBot

max_issues_repo_name: Siyinz/Info-Retrieval-ChatBot

max_forks_repo_name: Siyinz/Info-Retrieval-ChatBot


text:
import pandas as pd
import numpy as np

from optbinning import BinningProcess

from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.metrics import classification_report
from sklearn.metrics import auc, roc_auc_score, roc_curve
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline

raw_data = pd.read_csv('data/raw/heloc_dataset_v1.csv', delimiter=',')
variable_names = list(raw_data.columns[1:])
X_train = np.genfromtxt('data/preprocessed/X_train.csv', delimiter=',')
X_test = np.genfromtxt('data/preprocessed/X_test.csv', delimiter=',')
y_train = np.genfromtxt('data/preprocessed/y_train.csv', delimiter=',')
y_test = np.genfromtxt('data/preprocessed/y_test.csv', delimiter=',')

special_codes = [-9, -8, -7]

binning_fit_params = {
    "ExternalRiskEstimate": {"monotonic_trend": "descending"},
    "MSinceOldestTradeOpen": {"monotonic_trend": "descending"},
    "MSinceMostRecentTradeOpen": {"monotonic_trend": "descending"},
    "AverageMInFile": {"monotonic_trend": "descending"},
    "NumSatisfactoryTrades": {"monotonic_trend": "descending"},
    "NumTrades60Ever2DerogPubRec": {"monotonic_trend": "ascending"},
    "NumTrades90Ever2DerogPubRec": {"monotonic_trend": "ascending"},
    "PercentTradesNeverDelq": {"monotonic_trend": "descending"},
    "MSinceMostRecentDelq": {"monotonic_trend": "descending"},
    "NumTradesOpeninLast12M": {"monotonic_trend": "ascending"},
    "MSinceMostRecentInqexcl7days": {"monotonic_trend": "descending"},
    "NumInqLast6M": {"monotonic_trend": "ascending"},
    "NumInqLast6Mexcl7days": {"monotonic_trend": "ascending"},
    "NetFractionRevolvingBurden": {"monotonic_trend": "ascending"},
    "NetFractionInstallBurden": {"monotonic_trend": "ascending"},
    "NumBank2NatlTradesWHighUtilization": {"monotonic_trend": "ascending"}
}

binning_process = BinningProcess(variable_names, special_codes=special_codes,
        binning_fit_params=binning_fit_params)

clf_lr = Pipeline(steps=[('binning_process', binning_process),
                        ('classifier', LogisticRegression(solver='lbfgs'))])

clf_lr.fit(X_train, y_train)
y_pred = clf_lr.predict(X_test)
print(classification_report(y_test, y_pred))

max_stars_repo_name: kevenrc/explainableAI

max_issues_repo_name: kevenrc/explainableAI

max_forks_repo_name: kevenrc/explainableAI


text:
# -*- coding:utf-8 -*-
# @author  : cbingcan
# @time    : 2021/8/24/024 11:17
import cv2
import time
from multiprocessing import Process, Value
import sophon.sail as sail
from utils import DETECTION_TPU_ID
import threading
import pickle
import os
import sys, errno
from utils import *
from PIL import Image
import numpy as np

class Capture():

    """
     1、读取视频流进程，一个进程一个处理一个rtsp视频流。
     2、将读取到的视频帧写入detect_q
    """

    def __init__(self, threadID, name, engine, data, detect_queue):
        super().__init__()
        self.threadID = threadID
        self.name = name
        self.data = data
        self.detect_queue = detect_queue
        self.engine = engine
        self.handle = engine.get_handle()
        self.bmcv = sail.Bmcv(self.handle)
        self.graph_name = self.engine.get_graph_names()[0]
        self.input_name = self.engine.get_input_names(self.graph_name)[0]

    def process(self, im_tensors):
        # 推理
        t = time.time()
        print("input_name = %s" % self.input_name)
        #print("推理开始：shape = " , im_tensors.shape)
        net_out = self.engine.process(self.graph_name, {self.input_name: im_tensors})
        # print("output shape: %s" % net_out.shape)
        print('total cost {} ms'.format((time.time() - t) * 1000))

    def run(self, exit, num):
       readImg = False
       graph_name = self.engine.get_graph_names()[0]
       input_name = self.engine.get_input_names(graph_name)[0]
       scale = self.engine.get_input_scale(graph_name, input_name)
       input_dtype = self.engine.get_input_dtype(graph_name, input_name)
       if not readImg:
         decoder = sail.Decoder(self.data['rtsp'], True, DETECTION_TPU_ID)
       input_shape = [1,3,input_img_h,input_img_w]
       img_dtype = self.bmcv.get_bm_image_data_format(input_dtype)
       output_name = self.engine.get_output_names(graph_name)[0]
       output_dtype = self.engine.get_output_dtype(graph_name, output_name)
       output_shape = [1, 3, 450, 800]
       input = sail.Tensor(self.handle, output_shape, input_dtype, False, False)
       tmp = sail.BMImage(self.handle,input_shape[2], input_shape[3], sail.Format.FORMAT_BGR_PLANAR, img_dtype)
       while True:
           t = time.time()
           if not readImg:
            img = sail.BMImage()
            ret = decoder.read(self.handle, img)
            #print('视频解码用时 {} ms'.format((time.time() - t) * 1000))
            if ret != 0:
                    continue

           if (self.detect_queue.qsize() > 500):
            if (exit.value == 1.0):
                print("cap exit: ", exit.value)
                break
            time.sleep(0.01)
            continue

           if not readImg:
            #print('wxc w',input_img_w,' h:', input_img_h)
            tmp = self.bmcv.vpp_resize(img, input_img_w, input_img_h)
            self.bmcv.imwrite("tmp.jpg", tmp)
            self.bmcv.bm_image_to_tensor(tmp, input)
           else:
            img =  ('100.jpg', (800,450))

           if (exit.value == 1.0):# or num.value > 10000:
            print(" cap exit2: ", exit.value)
            break
           try:
            if not readImg:
              #input.sync_d2s()
              input_img = self.bmcv.tensor_to_bm_image(input)
              self.bmcv.imwrite("input_img.jpg", input_img)
              input_array=input.asnumpy().astype(np.int8)
              print("fps: ", decoder.get_fps())
              print('cap img:',input_array[0,:,449,797:])
              self.detect_queue.put({"id": self.data["id"], "frame":input_array})
              #input.unmap()
            else:
              print('cap img:',img[0,:,1,0:3])
              self.detect_queue.put({"id": self.data["id"], "frame": img})
           except IOError as e:
            if e.errno == errno.EPIPE:
                print("queue full, discard it")
           except BrokenPipeError as k:
                print("pipeerror: {}".format(k.errno))
                pass
           except EOFError as l:
               print("EOF error: {}".format(l.errno))
               pass
           except TimeoutError as e:
               print("Timeout :", e)
               pass
           except Exception as e:
               print(e)
               pass
           #print("pid: {} , qsize: {}".format(os.getpid(), self.detect_queue.qsize()))
           #print(pickle.dumps(img))
           #print(pickle.dumps(img.data()))
           #self.detect_queue.put({"id": self.data["id"], "frame":img})
           #print('视频解码用时 {} ms'.format((time.time() - t) * 1000))
           #time.sleep(0.5)

max_stars_repo_name: sophon-ai-algo/sophon-inference

max_issues_repo_name: sophon-ai-algo/sophon-inference

max_forks_repo_name: sophon-ai-algo/sophon-inference


text:
from .base_monitor import BaseMonitor

import cv2
import numpy as np
from sc2.constants import NEXUS, PROBE, PYLON, ASSIMILATOR, GATEWAY, \
    CYBERNETICSCORE, STALKER, STARGATE, VOIDRAY, OBSERVER, ROBOTICSFACILITY

class ChromaticMonitor(BaseMonitor):

    def __init__(self, headless):
        super().__init__(headless=headless)
        self.flipped = None
        self.worker_names = ['probe', 'scv', 'drone']
        self.main_base_names = [
            'nexus',  # Protoss
            'hatchery'  # Zerg
            'commandcenter',  # Terran
            'orbitalcommand',  # Terran(Upgraded)
            'planetaryfortress'  # Terran(Upgraded)
        ]
        self.draw_dict = {
            NEXUS: [15, (0, 255, 0)],
            PYLON: [3, (20, 235, 0)],
            PROBE: [1, (55, 200, 0)],
            ASSIMILATOR: [2, (55, 200, 0)],
            OBSERVER: [1, (255, 255, 255)],
            GATEWAY: [3, (200, 100, 0)],
            CYBERNETICSCORE: [3, (150, 150, 0)],
            ROBOTICSFACILITY: [5, (215, 155, 0)],
            STARGATE: [5, (255, 0, 0)],
            VOIDRAY: [3, (255, 100, 0)]
        }

    async def draw(self, bot):
        """
        convert data into OpenGL images
        """
        game_data = np.zeros(
            (bot.game_info.map_size[1], bot.game_info.map_size[0], 3),
            dtype=np.uint8
        )
        await self.draw_own_units(bot, game_data)
        await self.draw_enemy_buildings(bot, game_data)
        await self.draw_enemy_units(bot, game_data)
        await self.draw_resources(bot, game_data)
        await self.flip(game_data)

        if not self.headless:
            self.show(bot.title, self.flipped)

    async def draw_own_units(self, bot, game_data):
        """
        draw bot own units
        """
        for unit_type in self.draw_dict:
            for unit in bot.units(unit_type):
                pos = unit.position
                cv2.circle(
                    game_data,
                    (int(pos[0]), int(pos[1])),
                    self.draw_dict[unit_type][0],
                    self.draw_dict[unit_type][1],
                    -1
                )

    async def draw_enemy_buildings(self, bot, game_data):
        for enemy_building in bot.known_enemy_structures:
            pos = enemy_building.position
            if enemy_building.name.lower() in self.main_base_names:
                await self.draw_enemy_main_base(game_data, pos)
            else:
                await self.draw_anonymous_enemy_building(game_data, pos)

    @staticmethod
    async def draw_enemy_main_base(game_data, pos):
        cv2.circle(
            game_data,
            (int(pos[0]), int(pos[1])),
            15,
            (0, 0, 255),
            -1
        )

    @staticmethod
    async def draw_anonymous_enemy_building(game_data, pos):
        cv2.circle(
            game_data,
            (int(pos[0]), int(pos[1])),
            5,
            (200, 50, 212),
            -1
        )

    async def draw_enemy_units(self, bot, game_data):
        for enemy_unit in bot.known_enemy_units:
            if not enemy_unit.is_structure:
                pos = enemy_unit.position
                if enemy_unit.name.lower() in self.worker_names:
                    await self.draw_enemy_worker(game_data, pos)
                else:
                    await self.draw_anonymous_enemy_units(game_data, pos)

    @staticmethod
    async def draw_enemy_worker(game_data, pos):
        cv2.circle(
            game_data,
            (int(pos[0]), int(pos[1])),
            1,
            (55, 0, 155),
            -1
        )

    @staticmethod
    async def draw_anonymous_enemy_units(game_data, pos):
        cv2.circle(
            game_data,
            (int(pos[0]), int(pos[1])),
            3,
            (50, 0, 215),
            -1
        )

max_stars_repo_name: tsonglew/yuri

max_issues_repo_name: tsonglew/yuri

max_forks_repo_name: tsonglew/yuri


text:
'''
    Almost equilateral triangles
    Problem 94
'''
from numba import jit

@jit
def is_area_int(L):
    lim = (L // 3) + 1
    sol = 0
    for a in range(3, lim, 2):
        for i in (-1, 1):
            b = a + i
            p = a + a + b
            b_h = b // 2
            hsqrd = a * a - b_h * b_h
            h = int(hsqrd**0.5)
            if h * h == hsqrd:
                area = h * b
                if area % 2 == 0:
                    if p < L:
                        sol += p
    return sol

if __name__ == "__main__":
    from time import time
    t0 = time()

    L = 10**9
    print("Final Result is :", is_area_int(L))

    print("Time Taken : {:.2f} secs".format(time() - t0))

reason: from numba


text:
# Copyright 2020 NREL

# 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.

# See https://floris.readthedocs.io for documentation

import math

import numpy as np
from scipy.stats import norm
from scipy.spatial import distance_matrix
from scipy.interpolate import interp1d

from ..utilities import cosd, sind, tand
from ..logging_manager import LoggerBase

from floris.simulation.wake_vortex.VortexCylinder import vc_tang_u, vc_longi_u, vc_root_u, vcs_tang_u, vcs_longi_u, vc_tang_u_doublet
from floris.simulation.wake_vortex.VortexDoublet  import doublet_line_u
from floris.simulation.wake_vortex.SelfSimilar    import ss_u
from floris.simulation.wake_vortex.VortexCylinderSkewed import svc_tang_u, svc_longi_u, svc_root_u, svcs_tang_u, svcs_longi_u
from floris.simulation.wake_vortex.Solver import Ct_const_cutoff, WakeVorticityFromCt, WakeVorticityFromGamma

class Turbine(LoggerBase):
    """
    Turbine is a class containing objects pertaining to the individual
    turbines.

    Turbine is a model class representing a particular wind turbine. It
    is largely a container of data and parameters, but also contains
    methods to probe properties for output.

    Args:
        instance_dictionary: A dictionary that is generated from the
            input_reader; it should have the following key-value pairs:

            -   **description** (*str*): A string containing a description of
                the turbine.
            -   **properties** (*dict*): A dictionary containing the following
                key-value pairs:

                -   **rotor_diameter** (*float*): The rotor diameter (m).
                -   **hub_height** (*float*): The hub height (m).
                -   **blade_count** (*int*): The number of blades.
                -   **pP** (*float*): The cosine exponent relating the yaw
                    misalignment angle to power.
                -   **pT** (*float*): The cosine exponent relating the rotor
                    tilt angle to power.
                -   **generator_efficiency** (*float*): The generator
                    efficiency factor used to scale the power production.
                -   **power_thrust_table** (*dict*): A dictionary containing the
                    following key-value pairs:

                    -   **power** (*list(float)*): The coefficient of power at
                        different wind speeds.
                    -   **thrust** (*list(float)*): The coefficient of thrust
                        at different wind speeds.
                    -   **wind_speed** (*list(float)*): The wind speeds for
                        which the power and thrust values are provided (m/s).

                -   **yaw_angle** (*float*): The yaw angle of the turbine
                    relative to the wind direction (deg). A positive value
                    represents a counter-clockwise rotation relative to the
                    wind direction.
                -   **tilt_angle** (*float*): The tilt angle of the turbine
                    (deg). Positive values correspond to a downward rotation of
                    the rotor for an upstream turbine.
                -   **TSR** (*float*): The tip-speed ratio of the turbine. This
                    parameter is used in the "curl" wake model.
                -   **ngrid** (*int*, optional): The square root of the number
                    of points to use on the turbine grid. This number will be
                    squared so that the points can be evenly distributed.
                    Defaults to 5.
                -   **rloc** (*float, optional): A value, from 0 to 1, that determines
                    the width/height of the grid of points on the rotor as a ratio of
                    the rotor radius.
                    Defaults to 0.5.

                    Need to Update _________________________________________
                    - R: rotor radius
                    - r_hub: position of the turbine hub in global coordinate system
                    - e_shaft_yaw0: unit vector along the shaft (untitled for now), going downwind, when the turbine has zero yaw
                    - e_vert: unit vertical vector, about which positive yawing is done
                    - U0: Free stream velocity in global coordinates (can be changerd with `update_wind`)
                    - Ct: Thrust coefficient (can be changed with `update_loading`)
                    - Ground: Include ground effect in calculations
                    - Model: one of ['VC','VCFF', 'VD', 'SS']
                            'VCFF': Vortex cylinder with far-field approximation (fastest)
                            'VC': Vortex cylinder
                            'SS': Self similar model of Troldborg et al.  (not good close to rotor)
                            'VD': Self similar model of Troldborg et al.  (not good close to rotor)

Returns:
        Turbine: An instantiated Turbine object.
    """

    def __init__(self, instance_dictionary):
        self.description = instance_dictionary["description"]

        properties = instance_dictionary["properties"]
        self.rotor_diameter = properties["rotor_diameter"]
        self.hub_height = properties["hub_height"]
        self.blade_count = properties["blade_count"]
        self.pP = properties["pP"]
        self.pT = properties["pT"]
        self.generator_efficiency = properties["generator_efficiency"]
        self.power_thrust_table = properties["power_thrust_table"]
        self.yaw_angle = properties["yaw_angle"]
        self.tilt_angle = properties["tilt_angle"]
        self.tsr = properties["TSR"]

        # Vortex turbine (for induction computation) parameters
        self.R = self.rotor_diameter/2
        self.r_hub = [0,0,self.hub_height]
        self.e_shaft_yaw0 = [1,0,0]
        self.e_vert = [0,0,1]

        """
            Specifies vectors to define coordinate notations for transformation
            matrices between vortex turbine cylindrical corrdinates and global coordinates
        """
        # Specify global coordinate system [TODO ??? need to check]
        self.e_shaft_g0 = np.asarray([1,0,0]).reshape(3,1)
        self.e_vert_g = np.asarray([0,0,1]).reshape(3,1)
        self.e_horz_g = np.asarray([1.,0.,0.]).reshape(3,1)
        # Transformation matrix from cylindrical to wind turbine coordinate system
        self.T_c2wt = np.asarray([[0,0,1,1,0,0,0,1,0]]).reshape(3,3)

        self.set_yaw_angle(self.yaw_angle)
        self.update_position(self.r_hub)
        self.U0_g = np.asarray([10,0,0]).ravel().reshape(3,1)
        #self.update_wind([0,0,10])
        self.name=''
        self.r=None
        self.gamma_t=None
        self.gamma_t=None
        self.Gamma_r=None
        self.Lambda=np.inf
        self.Ground=False# Ground effect will be included in calculation of induced velocity
        self.chi=None
        self.Model='VC'

        # initialize to an invalid value until calculated
        self.air_density = -1
        self.use_turbulence_correction = False

        # Initiate to False unless specifically set
        # For the following parameters, use default values if not user-specified
        self.ngrid = int(properties["ngrid"]) if "ngrid" in properties else 5
        self.rloc = float(properties["rloc"]) if "rloc" in properties else 0.5
        if "use_points_on_perimeter" in properties:
            self.use_points_on_perimeter = bool(properties["use_points_on_perimeter"])
        else:
            self.use_points_on_perimeter = False

        self._initialize_turbine()

        # The indices for this Turbine instance's points from the FlowField
        # are set in `FlowField._discretize_turbine_domain` and stored
        # in this variable.
        self.flow_field_point_indices = None

    # Private methods

    def _initialize_turbine(self):
        # Initialize the turbine given saved parameter settings

        # Precompute interps
        wind_speed = self.power_thrust_table["wind_speed"]

        cp = self.power_thrust_table["power"]
        self.fCpInterp = interp1d(wind_speed, cp, fill_value="extrapolate")

        ct = self.power_thrust_table["thrust"]
        self.fCtInterp = interp1d(wind_speed, ct, fill_value="extrapolate")

        # constants
        self.grid_point_count = self.ngrid * self.ngrid
        if np.sqrt(self.grid_point_count) % 1 != 0.0:
            raise ValueError("Turbine.grid_point_count must be the square of a number")

        self.reset_velocities()

        # initialize derived attributes
        self.grid = self._create_swept_area_grid()

        # Compute list of inner powers
        inner_power = np.array([self._power_inner_function(ws) for ws in wind_speed])
        self.powInterp = interp1d(wind_speed, inner_power, fill_value="extrapolate")

    def _create_swept_area_grid(self):
        # TODO: add validity check:
        # rotor points has a minimum in order to always include points inside
        # the disk ... 2?
        #
        # the grid consists of the y,z coordinates of the discrete points which
        # lie within the rotor area: [(y1,z1), (y2,z2), ... , (yN, zN)]

        # update:
        # using all the grid point because that how roald did it.
        # are the points outside of the rotor disk used later?

        # determine the dimensions of the square grid
        num_points = int(np.round(np.sqrt(self.grid_point_count)))

        pt = self.rloc * self.rotor_radius
        # syntax: np.linspace(min, max, n points)
        horizontal = np.linspace(-pt, pt, num_points)

        vertical = np.linspace(-pt, pt, num_points)

        # build the grid with all of the points
        grid = [(h, vertical[i]) for i in range(num_points) for h in horizontal]

        # keep only the points in the swept area
        if self.use_points_on_perimeter:
            grid = [
                point
                for point in grid
                if np.hypot(point[0], point[1]) <= self.rotor_radius
            ]
        else:
            grid = [
                point
                for point in grid
                if np.hypot(point[0], point[1]) < self.rotor_radius
            ]

        return grid

    def _power_inner_function(self, yaw_effective_velocity):
        """
        This method calculates the power for an array of yaw effective wind
        speeds without the air density and turbulence correction parameters.
        This is used to initialize the power interpolation method used to
        compute turbine power.
        """

        # Now compute the power
        cptmp = self._fCp(
            yaw_effective_velocity
        )  # Note Cp is also now based on yaw effective velocity
        return (
            0.5
            * (np.pi * self.rotor_radius ** 2)
            * cptmp
            * self.generator_efficiency
            * yaw_effective_velocity ** 3
        )

    def _fCp(self, at_wind_speed):
        wind_speed = self.power_thrust_table["wind_speed"]
        if at_wind_speed < min(wind_speed):
            return 0.0
        else:
            _cp = self.fCpInterp(at_wind_speed)
            if _cp.size > 1:
                _cp = _cp[0]
            return float(_cp)

    def _fCt(self, at_wind_speed):
        wind_speed = self.power_thrust_table["wind_speed"]
        if at_wind_speed < min(wind_speed):
            return 0.99
        else:
            _ct = self.fCtInterp(at_wind_speed)
            if _ct.size > 1:
                _ct = _ct[0]
            if _ct > 1.0:
                _ct = 0.9999
            return float(_ct)

    # Public methods

    def change_turbine_parameters(self, turbine_change_dict):
        """
        Change a turbine parameter and call the initialize function.

        Args:
            turbine_change_dict (dict): A dictionary of parameters to change.
        """
        for param in turbine_change_dict:
            self.logger.info(
                "Setting {} to {}".format(param, turbine_change_dict[param])
            )
            setattr(self, param, turbine_change_dict[param])
        self._initialize_turbine()

    def calculate_swept_area_velocities(
        self, local_wind_speed, coord, x, y, z, additional_wind_speed=None
    ):
        """
        This method calculates and returns the wind speeds at each
        rotor swept area grid point for the turbine, interpolated from
        the flow field grid.

        Args:
            wind_direction (float): The wind farm wind direction (deg).
            local_wind_speed (np.array): The wind speed at each grid point in
                the flow field (m/s).
            coord (:py:obj:`~.utilities.Vec3`): The coordinate of the turbine.
            x (np.array): The x-coordinates of the flow field grid.
            y (np.array): The y-coordinates of the flow field grid.
            z (np.array): The z-coordinates of the flow field grid.

        Returns:
            np.array: The wind speed at each rotor grid point
            for the turbine (m/s).
        """
        u_at_turbine = local_wind_speed

        # TODO:
        # # PREVIOUS METHOD========================
        # # UNCOMMENT IF ANY ISSUE UNCOVERED WITH NEW MOETHOD
        # x_grid = x
        # y_grid = y
        # z_grid = z

        # yPts = np.array([point[0] for point in self.grid])
        # zPts = np.array([point[1] for point in self.grid])

        # # interpolate from the flow field to get the flow field at the grid
        # # points
        # dist = [np.sqrt((coord.x1 - x_grid)**2 \
        #      + (coord.x2 + yPts[i] - y_grid) **2 \
        #      + (self.hub_height + zPts[i] - z_grid)**2) \
        #      for i in range(len(yPts))]
        # idx = [np.where(dist[i] == np.min(dist[i])) for i in range(len(yPts))]
        # data = [np.mean(u_at_turbine[idx[i]]) for i in range(len(yPts))]
        # # PREVIOUS METHOD========================

        # Use this if no saved points (curl)
        if self.flow_field_point_indices is None:
            # # NEW METHOD========================
            # Sort by distance
            flow_grid_points = np.column_stack([x.flatten(), y.flatten(), z.flatten()])

            # Set up a grid array
            y_array = np.array(self.grid)[:, 0] + coord.x2
            z_array = np.array(self.grid)[:, 1] + self.hub_height
            x_array = np.ones_like(y_array) * coord.x1
            grid_array = np.column_stack([x_array, y_array, z_array])

            ii = np.argmin(distance_matrix(flow_grid_points, grid_array), axis=0)
        else:
            ii = self.flow_field_point_indices

        # return np.array(data)
        if additional_wind_speed is not None:
            return (
                np.array(u_at_turbine.flatten()[ii]),
                np.array(additional_wind_speed.flatten()[ii]),
            )
        else:
            return np.array(u_at_turbine.flatten()[ii])

    def return_grid_points(self, coord):
        """
        Retrieve the x, y, and z grid points on the rotor.

        Args:
            coord (:py:obj:`~.utilities.Vec3`): The coordinate of the turbine.

        Returns:
            np.array, np.array, np.array:

                - x grid points on the rotor.
                - y grid points on the rotor.
                - xzgrid points on the rotor.
        """
        y_array = np.array(self.grid)[:, 0] + coord.x2
        z_array = np.array(self.grid)[:, 1] + self.hub_height
        x_array = np.ones_like(y_array) * coord.x1

        return x_array, y_array, z_array

    def update_velocities(
        self, u_wake, coord, flow_field, rotated_x, rotated_y, rotated_z
    ):
        """
        This method updates the velocities at the rotor swept area grid
        points based on the flow field freestream velocities and wake
        velocities.

        Args:
            u_wake (np.array): The wake deficit velocities at all grid points
                in the flow field (m/s).
            coord (:py:obj:`~.utilities.Vec3`): The coordinate of the turbine.
            flow_field (:py:class:`~.flow_field.FlowField`): The flow field.
            rotated_x (np.array): The x-coordinates of the flow field grid
                rotated so the new x axis is aligned with the wind direction.
            rotated_y (np.array): The y-coordinates of the flow field grid
                rotated so the new x axis is aligned with the wind direction.
            rotated_z (np.array): The z-coordinates of the flow field grid
                rotated so the new x axis is aligned with the wind direction.
        """
        # reset the waked velocities
        local_wind_speed = flow_field.u_initial - u_wake
        self.velocities = self.calculate_swept_area_velocities(
            local_wind_speed, coord, rotated_x, rotated_y, rotated_z
        )

    def reset_velocities(self):
        """
        This method sets the velocities at the turbine's rotor swept
        area grid points to zero.
        """
        self.velocities = np.array([0.0] * self.grid_point_count)

    def set_yaw_angle(self, yaw_angle):
        """
        This method sets the turbine's yaw angle.

        Args:
            yaw_angle (float): The new yaw angle (deg).

        Examples:
            To set a turbine's yaw angle:

            >>> floris.farm.turbines[0].set_yaw_angle(20.0)
        """
        self._yaw_angle = yaw_angle

        # Vortex wind turbine
        # print('>>> turbine.py : set yaw VC_WT')
        self.yaw_pos = yaw_angle * np.pi/180 # Convert from degrees to radians
        # print('Yaw Angle',yaw_angle)
        # print('Yaw_pos',self.yaw_pos)

        # Transformation matrix for rotating vector around yaw angle
        c,s=np.cos(self.yaw_pos),np.sin(self.yaw_pos)
        self.T_wt2g  = np.asarray([c,-s,0,s,c,0,0,0,1]).reshape(3,3)
        # Rotating the shaft vector so that its coordinate follow the new yaw position
        self.e_shaft_g=np.dot(self.T_wt2g , self.e_shaft_g0)

    def update_position(self,r_hub):
        self.r_hub=np.asarray(r_hub).ravel().reshape(3,1)

    def compute_induction(self, Ind_Opts, rotated_x, rotated_y, rotated_z, CT0=None):
        """
        Computes induction from the turbine as a result of the blockage effect. Applied to velocity
        field to simulate the induction zone of a turbine.

        INPUTS:
            Ind_Opts (dict): Dictionary of inputs to model the resulting
                turbine induction zone as a result of the blockage effect.
            rotated_x (np.array): The x-coordinates of the flow field grid
                rotated so the new x axis is aligned with the wind direction.
            rotated_y (np.array): The y-coordinates of the flow field grid
                rotated so the new x axis is aligned with the wind direction.
            rotated_z (np.array): The z-coordinates of the flow field grid
                rotated so the new x axis is aligned with the wind direction.
        """
        self.Ind_Opts = Ind_Opts

        if Ind_Opts['induction']: # Can remove (won't be called unless induction)
            if Ind_Opts['Ct_test']:
                print('Ct-test')
                # update vortex cylinder velocity and loading
                r_bar_cut = 0.11
                r_bar_tip = 0.9
                if CT0 is None:
                    CT0       = self.Ct
                print('CT0: ', CT0)
                self.R = self.rotor_diameter/2*Ind_Opts['Rfact']
                nCyl      = 1 # For now
                Lambda    = np.inf
                vr_bar    = np.linspace(0,1.0,100)
                Ct_AD     = Ct_const_cutoff(CT0,r_bar_cut,vr_bar,r_bar_tip) # TODO change me to distributed
                gamma_t_Ct = None
                self.update_loading(r=vr_bar*self.R, VC_Ct=Ct_AD, Lambda=Lambda, nCyl=nCyl, gamma_t_Ct=gamma_t_Ct)
                self.gamma_t= self.gamma_t*Ind_Opts['GammaFact']
                root  = False
                longi = False
                tang  = True
                # print('.',end='')
                ux,uy,uz = self.compute_u(rotated_x,rotated_y,rotated_z,root=root,longi=longi,tang=tang, only_ind=True, no_wake=False, Decay=False, Model = Ind_Opts['Model'], ground=Ind_Opts['Ground'],R_far_field=Ind_Opts['R_far_field'])
            else:
                # update vortex cylinder velocity and loading
                r_bar_cut = 0.01
                # r_bar_cut = 0.11
                # r_bar_tip = 0.9
                # print("------Ct:", self.Ct)
                if CT0 is None:
                    CT0       = self.Ct
                # print('CT0: ', CT0)
                self.R = self.rotor_diameter/2*Ind_Opts['Rfact']
                nCyl      = 1 # For now
                Lambda    = 30 # if >20 then no swirl
                # Lambda    = np.inf
                vr_bar    = np.linspace(0,1.0,100)
                Ct_AD     = Ct_const_cutoff(CT0,r_bar_cut,vr_bar) # TODO change me to distributed
                # Ct_AD     = Ct_const_cutoff(CT0,r_bar_cut,vr_bar,r_bar_tip) # TODO change me to distributed
                gamma_t_Ct = None
                self.update_loading(r=vr_bar*self.R, VC_Ct=Ct_AD, Lambda=Lambda, nCyl=nCyl, gamma_t_Ct=gamma_t_Ct)
                self.gamma_t= self.gamma_t*Ind_Opts['GammaFact']
                # print('gamma_t: ', self.gamma_t)
                root  = False
                longi = False
                tang  = True
                # print('.',end='')
                ux,uy,uz = self.compute_u(rotated_x,rotated_y,rotated_z,root=root,longi=longi,tang=tang, only_ind=True, no_wake=True, Decay=True, Model = Ind_Opts['Model'], ground=Ind_Opts['Ground'],R_far_field=Ind_Opts['R_far_field'])

        return ux,uy,uz

    def update_loading(self,r=None,VC_Ct=None,Gamma=None,Lambda=None,nCyl=1,gamma_t_Ct=None):
        """
        VC_Ct differs from Ct in that for a vortex cylinder VC_Ct is constant along the blade and
        zero at the root and the tip
        """
        """
        Computes relevant parameters when the turbine loading is updated, mainly, gamma_t,
        the intensity of the tangential vorticity sheet.
        The ditributon will be determined based on the inputs, with one these three approaches:
           1. VC_Ct(r) distribution
           2. Gamma(r) distribution
           3. gamma_t(VC_Ct(r)) function

        INPUTS:
          r: radial coordinates at which VC_Ct or Gamma are provided
          VC_Ct: local thrust coefficient (VC_Ct(r), array), or total thrust coefficient (CT, scalar)
          Gamma:  bound circulation (Gamma(r), array), or total rotor circulation (Gamma_tot, scalar)
          Lambda: tip speed ratio (assumed infinite if None)
          nCyl : number of cylindrical model used in the spanwise direction (default is 1)
                 The circulation (gamma_t) will be determined for each of the radial cylinder
          gamma_t_Ct: function that provides gamma_t as function of VC_Ct (or gamma_t as function of CT)
        """
        # Update vortex cylinder average velocity at turbine
        self.U0_g = np.asarray([self.average_velocity,0,0]).ravel().reshape(3,1)

        U0=np.linalg.norm(self.U0_g)
        # print('Turbineprint('Turbine Avg U:',self.average_velocity)

        # --- Reinterpolating loading to number of cylinders if needed
        if nCyl is not None:
            if nCyl==1:
                vr0= np.array([0.995*self.R])
                if VC_Ct is not None:
                    VC_Ct =np.array([np.mean(VC_Ct)])
                if Gamma is not None:
                    Gamma =np.array([np.mean(Gamma)])
            else:
                vr0= np.linspace(0.005,0.995,nCyl)*self.R
                if VC_Ct is not None:
                    VC_Ct = np.interp(vr0,r,VC_Ct)
                else:
                    Gamma = np.interp(vr0,r,Gamma)
            r=vr0

        # Updating Lambda
        if Lambda is None:
            Lambda=self.Lambda
        if Lambda is None:
            raise Exception('Provide `Lambda` for update_loading. (Note: `Lambda=np.Inf` supported) ')
        Omega = Lambda*U0/self.R
        #print('U0',U0)
        #print('VC_Ct',VC_Ct)

        # Computing and storing gamma distribution and loading
        if gamma_t_Ct is not None:
            if VC_Ct is None:
                raise Exception('Provide `Ct` along `gamma_t_Ct`')
            self.gamma_t = gamma_t_Ct(VC_Ct)
            self.gamma_l=None # TODO
            self.Gamma_r=None # TODO
        elif VC_Ct is not None:
            self.gamma_t,self.gamma_l,self.Gamma_r,misc=WakeVorticityFromCt(r,VC_Ct,self.R,U0,Omega)
        elif Gamma is not None:
            self.gamma_t,self.gamma_l,self.Gamma_r,misc=WakeVorticityFromGamma(r,Gamma,self.R,U0,Omega)
        else:
            raise Exception('Unknown loading spec')
        #self.gamma_t=self.gamma_t*1.06
        #print('gamma_t    ',self.gamma_t)
        #print('gamma_l    ',self.gamma_l)
        #print('Gamma_r    ',self.Gamma_r)
        #print('Gamma_/2piR',-self.Gamma_r/(2*np.pi*self.R))
        #print(misc)
        self.Lambda=Lambda
        self.r=r
        self.VC_Ct=VC_Ct

    def compute_u(self, Xg, Yg, Zg, only_ind=False, longi=False, tang=True, root=False, no_wake=False, ground=None, Decay=False, Model=None, R_far_field=6):
        """
        INPUTS:
            Xg, Yg, Zg: Control points in global coordinates where the flow is to be computed.
            only_ind: if true, only induction is returned (without the free stream)

            longi, tang, root: booleans specifying which component of vorticity is considered.
                               Default is `tang` only
            no_wake: boolean, if true: the induced velocity in the wake is set to 0.
                     Typically set to true when combining with wake models.

            Model : string in ['VC','VCFF','SS','VD']
                   'VCFF': Vortex cylinder with far-field approximation (fastest)
                   'VC': Vortex cylinder
                   'SS': Self similar model of Troldborg et al.  (not good close to rotor)
                   'VD': Self similar model of Troldborg et al.  (not good close to rotor)
        """
        # --- Optional argument overriding self
        if ground is None:
            ground=self.Ground
        if Model is None:
            Model=self.Model

        # Control points in "Cylinder coordinate system" (rotation only)
        T_c2g=np.dot(self.T_wt2g,self.T_c2wt)
        Xc,Yc,Zc = transform_T(T_c2g, Xg,Yg,Zg)
        # Detecting whether our vertical convention match, and define chi
        e_vert_c = np.dot(T_c2g.T , self.e_vert_g)
        # if self.chi is None:
        #     # TODO TODO chi needs induction effect!
        #     self.chi= np.sign(e_vert_c.ravel()[1])* (self.yaw_wind-self.yaw_pos)

        # TODO TODO chi needs induction effect!
        # self.chi= np.sign(e_vert_c.ravel()[1])* (self.yaw_wind-self.yaw_pos)
        # print('Chi: ', self.chi)
        if self.VC_Ct > 1:
            self.VC_Ct = 1
        self.chi= np.sign(e_vert_c.ravel()[1])* (self.yaw_wind-self.yaw_pos) * (1+0.3*(1-np.sqrt(1-self.VC_Ct[0])))
        # print('Chi_: ', self.chi)
        # self.chi = self.chi*1.5
        # print('Chi: ', self.chi)

        if self.gamma_t is None:
            raise Exception('Please set loading with `update_loading` before calling `compute_u`')

        uxc = np.zeros(Xg.shape)
        uyc = np.zeros(Xg.shape)
        uzc = np.zeros(Xg.shape)
        m=np.tan(self.chi)
        # Cylinder position in "Cylinder coordinate system) (rotation only)
        Xcyl, Ycyl, Zcyl = transform_T(T_c2g,np.array([self.r_hub[0]]), np.array([self.r_hub[1]]),  np.array([self.r_hub[2]]))
        # Translate control points such that origin is at rotor center. NOTE: not all routines use this
        Xc0,Yc0,Zc0=Xc-Xcyl[0],Yc-Ycyl[0],Zc-Zcyl[0]
        if ground:
            # Mirror control points are two time the hub height above the cylinder
            Yc0mirror=Yc0+2*Ycyl[0]
            Ylist=[Yc0,Yc0mirror]
            #print('>>> Ground effect',Ycyl[0])
        else:
            Ylist=[Yc0]

        # --- Root vortex influence
        if root and  (self.Gamma_r is not None) and self.Gamma_r!=0:
            for Y in Ylist:
                if np.abs(self.chi)>1e-7:
                    uxc0,uyc0,uzc0 = svc_root_u(Xc0,Y,Zc0,Gamma_r=self.Gamma_r,m=m,polar_out=False)
                else:
                    uxc0,uyc0,uzc0 =  vc_root_u(Xc0,Y,Zc0,Gamma_r=self.Gamma_r,polar_out=False)
                uxc += uxc0
                uyc += uyc0
                uzc += uzc0

        if len(self.gamma_t)==1:
            # --- Tangential and longi - ONE Cylinder only
            for iY,Y in enumerate(Ylist):
                if tang and (self.gamma_t!=0):
                    if np.abs(self.chi)>1e-7:
                        if Model =='VC':
                            uxc0,uyc0,uzc0 = svc_tang_u(Xc0,Y,Zc0,gamma_t=self.gamma_t,R=self.R,m=m,polar_out=False)
                            # print('-----------------Vortex Cylinder Skewed Model------------------')
                        else:
                            pass
                            # raise NotImplementedError('Model '+Model + ', with yaw.')
                    else:
                        if Model =='VC':
                                uxc0,uyc0,uzc0 = vc_tang_u        (Xc0,Y,Zc0, gamma_t=self.gamma_t, R=self.R, polar_out=False)
                        elif Model =='VCFF':
                            uxc0,uyc0,uzc0 = vc_tang_u_doublet(Xc0,Y,Zc0, gamma_t=self.gamma_t, R=self.R, polar_out=False,r_bar_Cut=R_far_field)
                        elif Model =='VD':
                            uxc0,uyc0,uzc0 = doublet_line_u(Xc0, Y, Zc0, dmz_dz = self.gamma_t * self.R**2 * np.pi)
                        elif Model =='SS':
                            uzc0 = ss_u          (Xc0, Y, Zc0, gamma_t=self.gamma_t, R=self.R)
                            uxc0=uzc0*0
                            uyc0=uzc0*0
                        else:
                            raise NotImplementedError('Model'+Model)
                    uxc += uxc0
                    uyc += uyc0
                    uzc += uzc0
                if longi and (self.gamma_l is not None) and self.gamma_l!=0 :
                    if np.abs(self.chi)>1e-7:
                        if Model =='VC':
                            uxc0,uyc0,uzc0 = svc_longi_u(Xc0,Y,Zc0,gamma_l=self.gamma_l,R=self.R,m=m,polar_out=False)
                        else:
                            raise NotImplementedError('Model '+Model + ', longi component.')
                    else:
                        if Model =='VC':
                            uxc0,uyc0,uzc0 = vc_longi_u (Xc0,Y,Zc0,gamma_l=self.gamma_l,R=self.R    ,polar_out=False)
                        else:
                            raise NotImplementedError('Model'+Model + ', longi component.')
                    uxc += uxc0
                    uyc += uyc0
                    uzc += uzc0
        else:
            # --- Tangential and longi - MULTI Cylinders
            if Model =='VC':
                nr   = len(self.r)
                nWT = 1
                # Control points are directly translated by routine
                gamma_t = self.gamma_t.reshape((nWT,nr))
#                 print('r      ',self.r)
#                 print('gamma_t',gamma_t)
                if self.gamma_l is not None:
                    gamma_l = self.gamma_l.reshape((nWT,nr))
                vR      = self.r.reshape((nWT,nr))
                vm       = m* np.ones((nWT,nr))
                if tang:
                    if np.abs(self.chi)>1e-7:
                        uxc0,uyc0,uzc0 = svcs_tang_u(Xc,Yc,Zc,gamma_t=gamma_t,R=vR,m=vm,Xcyl=Xcyl,Ycyl=Ycyl,Zcyl=Zcyl,Ground=ground)
                    else:
                        uxc0,uyc0,uzc0 = vcs_tang_u (Xc,Yc,Zc,gamma_t=gamma_t,R=vR    ,Xcyl=Xcyl,Ycyl=Ycyl,Zcyl=Zcyl, Ground=ground)
                    uxc += uxc0
                    uyc += uyc0
                    uzc += uzc0
                if longi and (self.gamma_l is not None):
                    if np.abs(self.chi)>1e-7:
                        uxc0,uyc0,uzc0 = svcs_longi_u(Xc,Yc,Zc,gamma_l=gamma_l,R=vR,m=vm,Xcyl=Xcyl,Ycyl=Ycyl,Zcyl=Zcyl, Ground=ground)
                    else:
                        uxc0,uyc0,uzc0 = vcs_longi_u (Xc,Yc,Zc,gamma_l=gamma_l,R=vR      ,Xcyl=Xcyl,Ycyl=Ycyl,Zcyl=Zcyl, Ground=ground)
                    uxc += uxc0
                    uyc += uyc0
                    uzc += uzc0
            else:
                raise NotImplementedError('Model'+Model, 'with multiple cylinders')
#         if no_wake:
# #             uxc[:]=0
# #             uyc[:]=0
# #             uzc[:]=1
#             # Zero wake induction
#             bDownStream=Zc0>=-0.20*self.R
# #             bDownStream=Zc0>=0
#             Rc = np.sqrt(Xc0**2 + Yc0**2)
#             bRotorTube = Rc<self.R*1.001 # we give a margin since VD and VC have fields very dissimilar at R+/-eps
#             bSelZero = np.logical_and(bRotorTube,bDownStream)
#             uxc[bSelZero]=0
#             uyc[bSelZero]=0
#             uzc[bSelZero]=0

        # Transform back to global
        uxg = T_c2g[0,0]*uxc+T_c2g[0,1]*uyc+T_c2g[0,2]*uzc
        uyg = T_c2g[1,0]*uxc+T_c2g[1,1]*uyc+T_c2g[1,2]*uzc
        uzg = T_c2g[2,0]*uxc+T_c2g[2,1]*uyc+T_c2g[2,2]*uzc

        # Decay
        if Decay:
            bDownStream=Xg>=(Yg-self.r_hub[1])*np.tan(-self.yaw_pos)-0.20*self.R+self.r_hub[0]
            XDecay = np.ones(uxg.shape)
            # XDecay[bDownStream] = np.exp(-((Xg[bDownStream]-self.r_hub[0])/(self.R*2))**2)
            # XDecay[bDownStream] = np.exp(-((Xg[bDownStream]-self.r_hub[0])/(self.R*2)*self.VC_Ct)**2)
            # XDecay[bDownStream] = np.exp(-(((Xg[bDownStream]-self.r_hub[0])*np.cos(-self.yaw_pos)-(Yg[bDownStream]-self.r_hub[1])*np.sin(-self.yaw_pos))/(self.R*2))**2)
            XDecay[bDownStream] = np.exp(-(((Xg[bDownStream]-self.r_hub[0])*np.cos(-self.yaw_pos)-(Yg[bDownStream]-self.r_hub[1])*np.sin(-self.yaw_pos))/(self.R*2)*self.VC_Ct)**2)
            uxg*=XDecay
            uyg*=XDecay
            uzg*=XDecay

        if no_wake:
            # Zero wake induction
            # Remove wake downstream of turbine (include small region in front of turbine to ensure induction does not affect free stream velocity)
            bDownStream=Xg>=(Yg-self.r_hub[1])*np.tan(-self.yaw_pos)-0.20*self.R+self.r_hub[0]
            # Only remove wake if within vortex cylinder radius
            # Rc = np.sqrt((Yg-self.r_hub[1])**2 + (Zg-self.hub_height)**2)
            vortex_vector = np.sqrt((-(Zg-self.r_hub[2]))**2+((Yg-self.r_hub[1])-(Xg-self.r_hub[0])*np.tan(self.chi+self.yaw_pos))**2)
            Rc = vortex_vector/np.linalg.norm(np.array([1,np.tan(self.chi+self.yaw_pos),0]))
            bRotorTube = Rc<self.R*1.001 # we give a margin since VD and VC have fields very dissimilar at R+/-eps
            # Check if point is both downstream and within vortex cylinder radius
            bSelZero = np.logical_and(bRotorTube,bDownStream)
            uxg[bSelZero]=0
            uyg[bSelZero]=0
            uzg[bSelZero]=0

            # # Removes ground effect vortex cylinder wake
            # # Remove wake downstream of turbine (include small region in front of turbine to ensure induction does not affect free stream velocity)
            # bDownStream=Xg>=(Yg+self.r_hub[1])*np.tan(-self.yaw_pos)-0.20*self.R+self.r_hub[0]
            # vortex_vector = np.sqrt((-(Zg+self.r_hub[2]))**2+((Yg+self.r_hub[1])-(Xg-self.r_hub[0])*np.tan(self.chi+self.yaw_pos))**2)
            # Rc = vortex_vector/np.linalg.norm(np.array([1,np.tan(self.chi+self.yaw_pos),0]))
            # bRotorTube = Rc<self.R*1.001 # we give a margin since VD and VC have fields very dissimilar at R+/-eps
            # # Check if point is both downstream and within vortex cylinder radius
            # bSelZero = np.logical_and(bRotorTube,bDownStream)
            # uxg[bSelZero]=0
            # uyg[bSelZero]=0
            # uzg[bSelZero]=0

        # Add free stream if requested
        if not only_ind:
            uxg += self.U0_g[0]
            uyg += self.U0_g[1]
            uzg += self.U0_g[2]
        return uxg,uyg,uzg
    def TKE_to_TI(self, turbulence_kinetic_energy):
        """
        Converts a list of turbulence kinetic energy values to
        turbulence intensity.
        Args:
            turbulence_kinetic_energy (list): Values of turbulence kinetic
                energy in units of meters squared per second squared.
            wind_speed (list): Measurements of wind speed in meters per second.
        Returns:
            list: converted turbulence intensity values expressed as a decimal
            (e.g. 10%TI -> 0.10).
        """
        total_turbulence_intensity = (
            np.sqrt((2 / 3) * turbulence_kinetic_energy)
        ) / self.average_velocity
        return total_turbulence_intensity

    def TI_to_TKE(self):
        """
        Converts TI to TKE.
        Args:
            wind_speed (list): Measurements of wind speed in meters per second.
        Returns:
            list: converted TKE values
        """
        return ((self.average_velocity * self.current_turbulence_intensity) ** 2) / (2 / 3)

    def u_prime(self):
        """
        Converts a TKE to horizontal deviation component.
        Args:
            wind_speed (list): Measurements of wind speed in meters per second.
        Returns:
            list: converted u_prime values in meters per second
        """
        tke = self.TI_to_TKE()
        return np.sqrt(2 * tke)

    # Getters & Setters
    @property
    def yaw_wind(self):
        """ NOTE: this is wind angle not wind direction, measured with same convention as yaw:
            - around the axis e_vert
        """
        u_horz = self.U0_g - np.dot(self.U0_g.T,self.e_vert_g)*self.e_vert_g
        e_w    = u_horz/np.linalg.norm(u_horz)
        sign = np.sign  ( np.dot(np.cross(self.e_horz_g.T, self.U0_g.T),self.e_vert_g) )
        if sign==0:
            yaw_wind = np.arccos(np.dot(e_w.T,self.e_horz_g))
        else:
            yaw_wind = sign * np.arccos(np.dot(e_w.T,self.e_horz_g))
        return yaw_wind.ravel()[0]

    @property
    def turbulence_parameter(self):
        """
        This property calculates and returns the turbulence correction
        parameter for the turbine, a value used to account for the
        change in power output due to the effects of turbulence.

        Returns:
            float: The value of the turbulence parameter.
        """
        if not self.use_turbulence_correction:
            return 1.0
        else:
            # define wind speed, ti, and power curve components
            ws = np.array(self.power_thrust_table["wind_speed"])
            cp = np.array(self.power_thrust_table["power"])
            ws = ws[np.where(cp != 0)]
            ciws = ws[0]  # cut in wind speed
            cows = ws[len(ws) - 1]  # cut out wind speed
            speed = self.average_velocity
            ti = self.current_turbulence_intensity

            if ciws >= speed or cows <= speed or ti == 0.0 or math.isnan(speed):
                return 1.0
            else:
                # define mean and standard deviation to create normalized pdf with sum = 1
                mu = speed
                sigma = ti * mu
                if mu + sigma >= cows:
                    xp = np.linspace((mu - sigma), cows, 100)
                else:
                    xp = np.linspace((mu - sigma), (mu + sigma), 100)
                pdf = norm.pdf(xp, mu, sigma)
                npdf = np.array(pdf) * (1 / np.sum(pdf))

                # calculate turbulence parameter (ratio of corrected power to original power)
                return np.sum([npdf[k] * self.powInterp(xp[k]) for k in range(100)]) / (
                    self.powInterp(mu)
                )

    @property
    def current_turbulence_intensity(self):
        """
        This method returns the current turbulence intensity at
        the turbine expressed as a decimal fraction.

        **Note:** This is a virtual property used to "get" or "set" a value.

        Args:
            value (float): Value to set.

        Returns:
            float: Value currently set.

        Examples:
            To get the turbulence intensity for a turbine:

            >>> current_turbulence_intensity = floris.farm.turbines[0].turbulence_intensity()
        """
        return self._turbulence_intensity

    @current_turbulence_intensity.setter
    def current_turbulence_intensity(self, value):
        self._turbulence_intensity = value

    @property
    def rotor_radius(self):
        """
        This method returns the rotor radius of the turbine (m).

        **Note:** This is a virtual property used to "get" a value.

        Returns:
            float: The rotor radius of the turbine.

        Examples:
            To get the rotor radius for a turbine:

            >>> rotor_radius = floris.farm.turbines[0].rotor_radius()
        """
        return self.rotor_diameter / 2.0

    @property
    def yaw_angle(self):
        """
        This method gets or sets the turbine's yaw angle.

        **Note:** This is a virtual property used to "get"  or "set" a value.

        Args:
            value (float): Value to set.

        Returns:
            float: Value currently set.

        Examples:
            To set the yaw angle for each turbine in the wind farm:

            >>> yaw_angles = [20.0, 10.0, 0.0]
            >>> for yaw_angle, turbine in
            ... zip(yaw_angles, floris.farm.turbines):
            ...     turbine.yaw_angle = yaw_angle

            To get the current yaw angle for each turbine in the wind
            farm:

            >>> yaw_angles = []
            >>> for i, turbine in enumerate(floris.farm.turbines):
            ...     yaw_angles.append(turbine.yaw_angle())
        """
        return self._yaw_angle

    @yaw_angle.setter
    def yaw_angle(self, value):
        self._yaw_angle = value

    @property
    def tilt_angle(self):
        """
        This method gets the turbine's tilt angle.

        **Note:** This is a virtual property used to "get"  or "set" a value.

        Args:
            value (float): Value to set.

        Returns:
            float: Value currently set.

        Examples:
            To get the current tilt angle for a turbine:

            >>> tilt_angle = floris.farm.turbines[0].tilt_angle()
        """
        return self._tilt_angle

    @tilt_angle.setter
    def tilt_angle(self, value):
        self._tilt_angle = value

    @property
    def average_velocity(self):
        """
        This property calculates and returns the cube root of the
        mean cubed velocity in the turbine's rotor swept area (m/s).

        Returns:
            float: The average velocity across a rotor.

        Examples:
            To get the average velocity for a turbine:

            >>> avg_vel = floris.farm.turbines[0].average_velocity()
        """
        # remove all invalid numbers from interpolation
        data = self.velocities[np.where(~np.isnan(self.velocities))]
        avg_vel = np.cbrt(np.mean(data ** 3))
        if np.isnan(avg_vel):
            avg_vel = 0
        elif np.isinf(avg_vel):
            avg_vel = 0

        return avg_vel

    @property
    def Cp(self):
        """
        This property returns the power coeffcient of a turbine.

        This property returns the coefficient of power of the turbine
        using the rotor swept area average velocity, interpolated from
        the coefficient of power table. The average velocity is
        calculated as the cube root of the mean cubed velocity in the
        rotor area.

        **Note:** The velocity is scalled to an effective velocity by the yaw.

        Returns:
            float: The power coefficient of a turbine at the current
            operating conditions.

        Examples:
            To get the power coefficient value for a turbine:

            >>> Cp = floris.farm.turbines[0].Cp()
        """
        # Compute the yaw effective velocity
        pW = self.pP / 3.0  # Convert from pP to pW
        yaw_effective_velocity = self.average_velocity * cosd(self.yaw_angle) ** pW

        return self._fCp(yaw_effective_velocity)

    @property
    def Ct(self):
        """
        This property returns the thrust coefficient of a turbine.

        This method returns the coefficient of thrust of the yawed
        turbine, interpolated from the coefficient of power table,
        using the rotor swept area average velocity and the turbine's
        yaw angle. The average velocity is calculated as the cube root
        of the mean cubed velocity in the rotor area.

        Returns:
            float: The thrust coefficient of a turbine at the current
            operating conditions.

        Examples:
            To get the thrust coefficient value for a turbine:

            >>> Ct = floris.farm.turbines[0].Ct()
        """
        return self._fCt(self.average_velocity) * cosd(self.yaw_angle)  # **self.pP

    @property
    def power(self):
        """
        This property returns the power produced by turbine (W),
        adjusted for yaw and tilt.

        Returns:
            float: Power of a turbine in watts.

        Examples:
            To get the power for a turbine:

            >>> power = floris.farm.turbines[0].power()
        """
        # Update to power calculation which replaces the fixed pP exponent with
        # an exponent pW, that changes the effective wind speed input to the power
        # calculation, rather than scaling the power.  This better handles power
        # loss to yaw in above rated conditions
        #
        # based on the paper "Optimising yaw control at wind farm level" by
        # Ervin Bossanyi

        # Compute the yaw effective velocity
        pW = self.pP / 3.0  # Convert from pP to w
        yaw_effective_velocity = self.average_velocity * cosd(self.yaw_angle) ** pW

        # Now compute the power
        return (
            self.air_density
            * self.powInterp(yaw_effective_velocity)
            * self.turbulence_parameter
        )

    @property
    def aI(self):
        """
        This property returns the axial induction factor of the yawed
        turbine calculated from the coefficient of thrust and the yaw
        angle.

        Returns:
            float: Axial induction factor of a turbine.

        Examples:
            To get the axial induction factor for a turbine:

            >>> aI = floris.farm.turbines[0].aI()
        """
        return (
            0.5
            / cosd(self.yaw_angle)
            * (1 - np.sqrt(1 - self.Ct * cosd(self.yaw_angle)))
        )

# --------------------------------------------------------------------------------}
# --- Helper functions for geometry
# --------------------------------------------------------------------------------{
def transform_T(T_a2b,Xb,Yb,Zb):
    Xa=T_a2b[0,0]*Xb+T_a2b[1,0]*Yb+T_a2b[2,0]*Zb
    Ya=T_a2b[0,1]*Xb+T_a2b[1,1]*Yb+T_a2b[2,1]*Zb
    Za=T_a2b[0,2]*Xb+T_a2b[1,2]*Yb+T_a2b[2,2]*Zb
    return Xa,Ya,Za

max_stars_repo_name: tangsmall/floris

max_issues_repo_name: tangsmall/floris

max_forks_repo_name: tangsmall/floris

reason: import numpy,from scipy


text:
#numpy modules
import sys
sys.path = ['/nfs/gns/homes/willj/anaconda3/envs/GTEx/lib/python3.5/site-packages'] + sys.path
import numpy as np
import pickle
#Keras modules
from keras.models import Sequential, Model
from keras.layers import Convolution2D, MaxPooling2D, GlobalAveragePooling2D, Input, Dense
from keras.applications.inception_v3 import InceptionV3
from keras.optimizers import SGD
from keras.preprocessing.image import ImageDataGenerator
from keras.utils import np_utils
from keras.models import load_model
#Sklearn modules
from sklearn.model_selection import train_test_split
#Scipy modules
from scipy.misc.pilutil import imresize
import argparse
import os
import pdb

def main():
    tissues_types = ['Lung',
     'Artery - Tibial',
     'Heart - Left Ventricle',
     'Breast - Mammary Tissue',
     'Brain - Cerebellum',
     'Pancreas',
     'Testis',
     'Liver',
     'Ovary',
     'Stomach']

    raw_X = []
    tissue_labels = []

    tile_number = args['tile_number']
    tile_level_index = args['tile_level_index']
    for t in tissues_types:
        print ('Loading {}:'.format(t))
        [rX, tl, rID] = pickle.load(open('data/processed/patches/data_{}_{}_{}_check.py'.format(t,tile_number,tile_level_index), 'rb'))
        raw_X.extend(rX)
        tissue_labels += tl

    print ('normalizing data')
    print (len(raw_X))
    X = (np.array(raw_X,dtype=np.float16) / 255)

    if args['grey_scale'] == '1':
        print ('making greyscale')
        new_X = np.zeros_like(X)
        mean_X = X.mean(3)
        new_X[:,:,:,0] = mean_X
        new_X[:,:,:,1] = mean_X
        new_X[:,:,:,2] = mean_X

        X = new_X

    classes, labels = np.unique(tissue_labels, return_inverse=True)
    pdb.set_trace()

    # X = np.array([imresize(x,(299,299)) for x in raw_X])
    y = np_utils.to_categorical(labels)

    print ('split train test set')
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)

    print ('data loaded')

    print ('checking if model exists: models/inception_{}_{}_gs{}_check.h5'.format(tile_number,tile_level_index,args['grey_scale']))
    print (os.path.isfile('models/inception_{}_{}_gs{}_check.h5'.format(tile_number,tile_level_index,args['grey_scale'])))
    if os.path.isfile('models/inception_{}_{}_gs{}_check.h5'.format(tile_number,tile_level_index,args['grey_scale'])):
        model = load_model('models/inception_{}_{}_gs{}_check.h5'.format(tile_number,tile_level_index,args['grey_scale']))
        print ('loading pretrained model')
        print ('Evaluating')
        loss, acc = model.evaluate(X_test,y_test)
        print ("loss: {}, acc: {}".format(loss,acc))
    else:
        print ('training model')
        inception_model = InceptionV3(weights='imagenet', include_top=False)

        x = inception_model.output

        x = GlobalAveragePooling2D()(x)
        x = Dense(1024, activation='relu')(x)
        predictions = Dense(10, activation='softmax')(x)

        model = Model(input=inception_model.input, output=predictions)

        for layer in inception_model.layers:
            layer.trainable = False

        model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'], verbose=2)

        datagen = ImageDataGenerator()

        datagen.fit(X_train)

        history1 = model.fit_generator(datagen.flow(X_train, y_train, batch_size=32), samples_per_epoch=len(X_train), nb_epoch=10, validation_data=(X_test, y_test))

        for layer in model.layers[:172]:
            layer.trainable = False
        for layer in model.layers[172:]:
            layer.trainable = True

        model.compile(optimizer=SGD(lr=0.0001, momentum=0.9), loss='categorical_crossentropy', metrics=['accuracy'], verbose=2)
        model.evaluate(X_test,y_test)

        history2 = model.fit_generator(datagen.flow(X_train, y_train, batch_size=32), samples_per_epoch=len(X_train), nb_epoch=30, validation_data=(X_test, y_test))
        pickle.dump([history1.history,history2.history], open('models/histories_{}_{}_gs{}_check.py'.format(tile_number,tile_level_index,args['grey_scale']),'wb'))
        model.save('models/inception_{}_{}_gs{}_check.h5'.format(tile_number,tile_level_index, args['grey_scale']))

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Description of your program')
    parser.add_argument('-n','--tile_number', help='Description for foo argument', required=True)
    parser.add_argument('-l','--tile_level_index', help='Description for foo argument', required=True)
    parser.add_argument('-g','--grey_scale', help='Description for foo argument', required=True)
    args = vars(parser.parse_args())
    main()

max_stars_repo_name: willgdjones/GTEx

max_issues_repo_name: willgdjones/GTEx

max_forks_repo_name: willgdjones/GTEx


text:
from PyQt4 import QtGui
from orangewidget import widget, gui
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas

class OWPlotSimple(widget.OWWidget):
    name = "Plot Simple"
    id = "orange.widgets.data.widget_name"
    description = ""
    icon = "icons/plot_simple.png"
    author = ""
    maintainer_email = ""
    priority = 10
    category = ""
    keywords = ["list", "of", "keywords"]
    inputs = [{"name": "oasysaddontemplate-data",
                "type": np.ndarray,
                "doc": "",
                "handler": "do_plot" },
                ]

    def __init__(self):
        super().__init__()
        self.figure_canvas = None

    def do_plot(self,custom_data):
        x = custom_data[0,:]
        y = custom_data[-1,:]
        x.shape = -1
        y.shape = -1
        fig = plt.figure()
        plt.plot(x,y,linewidth=1.0, figure=fig)
        plt.yscale('log')
        plt.xlabel('Angle (degrees)')
        plt.ylabel('Reflectivity')
        plt.grid(True)
        if self.figure_canvas is not None:
            self.mainArea.layout().removeWidget(self.figure_canvas)
        self.figure_canvas = FigureCanvas(fig) #plt.figure())
        self.mainArea.layout().addWidget(self.figure_canvas)

if __name__ == '__main__':
    app = QtGui.QApplication([])
    ow = OWPlotSimple()
    a = np.array([
        [  8.47091837e+04,  8.57285714e+04,   8.67479592e+04, 8.77673469e+04,] ,
        [  1.16210756e+12,  1.10833975e+12,   1.05700892e+12, 1.00800805e+12]
        ])
    ow.do_plot(a)
    ow.show()
    app.exec_()
    ow.saveSettings()

max_stars_repo_name: suracefm/oasys-dynXRD

max_issues_repo_name: suracefm/oasys-dynXRD

max_forks_repo_name: suracefm/oasys-dynXRD


text:
from os import getcwd
import sys
sys.path.append(getcwd() + '/..')   # Add src/ dir to import path
import traceback
import logging
from os.path import join

from pymongo import MongoClient
import pandas as pd
from pandas.io.json import json_normalize
import numpy as np
from bson.objectid import ObjectId

from libs.utilsInitialProcessing import invertCollectionPriority
from entityExtraction import idGenerator
from libs.mongoLib import updateContentDocs, getContentDocsWithEntities, getContentDocsWithInherentTags
from libs.osLib import loadYaml

def mergeEntitiesAndInherent(entityDf, inherentTagDf, idSize):
    inherentTagDf['mention'] = inherentTagDf['normalized']
    inherentTagDf['relationshipType'] = 'InherentMention'
    inherentTagDf['entityId'] = pd.Series([idGenerator(idSize) for _ in range(inherentTagDf.shape[0])])
    entityDf = entityDf.append(inherentTagDf, ignore_index=True)
    return entityDf

def standardizeIds(df):

    linkedDf = df[df.entityId.str.startswith('Q')]
    uniqueQIDs = linkedDf.entityId.unique()
    normalizedTags = df.normalized.unique()

    df['droppedQIDs'] = None

    for tag in normalizedTags:
        specificDf = df.loc[df.normalized == tag]
        conflictingIds = specificDf.entityId.unique()

        # If there's only one ID associated with that tag, it's all good.
        if len(conflictingIds) == 1:
            continue
        else:
            QIDs = [id for id in conflictingIds if id in uniqueQIDs]

            if len(QIDs) == 0:
                # If there's no QIDs among the conflicting ones, choose any of the forged IDs and standardize that one.
                df.loc[df.normalized == tag, 'entityId'] = conflictingIds[0]

            elif len(QIDs) == 1:
                # If there's exactly one QID among the conflicting ones, that one substitutes the remaining.
                df.loc[df.normalized == tag, 'entityId'] = QIDs[0]

            else:
                # If there are conflicting QIDs, choose the first one by default but keep the other ones for possible ambiguity settlement.
                df.loc[df.normalized == tag, 'entityId'] = QIDs[0]
                for index, row in df.loc[df.normalized == tag].iterrows():
                    df.at[index, 'droppedQIDs'] = QIDs
    return df

def prepareEntityCollection(df):
    output = []
    uniqueIds = df.index.unique()
    for qid in uniqueIds:
        specificDf = df.loc[qid].to_frame().transpose() if isinstance(df.loc[qid], pd.Series) else df.loc[qid]

        types = specificDf.type.unique().tolist()
        mentionForms = specificDf.mention.unique().tolist()
        normalizedForms = specificDf.normalized.unique().tolist()

        x = specificDf[['_id', 'relationshipType']].reset_index(drop=True).rename(columns={'_id': 'id'}).T
        x = x.to_dict()
        x = x.values()
        associatedContent = list(x)

        newDataPoint = {
            'id': qid,
            'types': types,
            'mentionForms': mentionForms,
            'normalizedForms': normalizedForms,
            'associatedContent': associatedContent,
        }

        if specificDf['droppedQIDs'].notna().any():
            newDataPoint['droppedQIDs'] = specificDf['droppedQIDs'][0]

        output.append(newDataPoint)
    return output

if __name__ == '__main__':

    # Set up logger
    root = logging.getLogger()
    root.setLevel(logging.DEBUG)

    idSize = 6

    try:
        # Load config
        configDir = '../../configs/'
        config = loadYaml(join(configDir, 'main.yaml'))
        inherentTags = {p: loadYaml(join(configDir, configFile))['inherentTags'] for p, configFile in
                                config['platforms'].items()}
        # Set up DB
        client = MongoClient()
        db = client['digitalMe']
        collectionCont = db['content']
        collectionEnt = db['entities']

        # Query DB for content with extracted entities
        entityDf = getContentDocsWithEntities(collectionCont)
        entityDf['relationshipType'] = 'ImpliedMention'

        # Query DB for tags inherent to data (not extracted entities)
        inherentTagDf = getContentDocsWithInherentTags(collectionCont, inherentTags)

        # Ensure entities with equal names have the same QID
        entityDf = mergeEntitiesAndInherent(entityDf, inherentTagDf, idSize)
        entityDf = standardizeIds(entityDf)

        # Prepare data for DB
        entityDf.set_index('entityId', inplace=True)
        entityCollectionData = prepareEntityCollection(entityDf)

        # Save it to DB
        insertedDocs = collectionEnt.insert_many(entityCollectionData)
        insertedIds = insertedDocs.inserted_ids

        # Update content docs with tags
        contentDocsPayload = invertCollectionPriority(entityCollectionData, insertedIds)
        updateContentDocs(collectionCont, 'tags', contentDocsPayload)

    except Exception as ex:
        print(traceback.format_exc())

max_stars_repo_name: andre-cavalheiro/Digital-Me

max_issues_repo_name: andre-cavalheiro/Digital-Me

max_forks_repo_name: andre-cavalheiro/Digital-Me


text:
from flask import Flask, request, jsonify
from flask_cors import CORS

import pandas as pd
import numpy as np

from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error

app = Flask(__name__)
CORS(app)

@app.route('/api/', methods=['POST'])
def check_score():
    data = request.get_json()
    print(data)
    old_intercept = data['old_intercept']
    new_intercept = data['new_intercept']
    old_coef = np.array(data['old_coef'])
    new_coef = np.array(data['new_coef'])
    n = data['n']

    df = pd.read_csv('./data/Fish.csv')
    _, df_test = train_test_split(df, test_size=0.2, shuffle=True, random_state=12)

    X_test = df_test[['Height', 'Width']]
    y_test = df_test['Weight']

    model = LinearRegression()

    model.intercept_ = old_intercept
    model.coef_ = old_coef
    pred_old = model.predict(X_test)

    model.intercept_ = (n * old_intercept + new_intercept) / n + 1
    model.coef_ = (n * old_coef + new_coef) / n + 1
    pred_fl = model.predict(X_test)

    old_score = np.sqrt(mean_squared_error(y_test, pred_old))
    fl_score = np.sqrt(mean_squared_error(y_test, pred_fl))
    result = {'score': fl_score,
                'old_score': old_score,
                'best': 1 if fl_score <= old_score else 0}
    return jsonify(result)

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')

max_stars_repo_name: Jebq/federatez

max_issues_repo_name: Jebq/federatez

max_forks_repo_name: Jebq/federatez