text:
#!/usr/bin/env python3
# ver 2.1 - coding python by Hyuntae Jung on 1/31/2019
#           instead of ml_wr.py, we divide several files.
# ver 2.2 - add #ensembles option on 2/21/2019
# ver 2.3 - add polymer blend model options on 5/30/2019
# ver 3.0 - add three state by adding empty particle on 10/28/2019

import argparse
parser = argparse.ArgumentParser(
	formatter_class=argparse.ArgumentDefaultsHelpFormatter,
	description='input data pre-processing (grid interpolation) of Widom-Rowlinson model')
## args
parser.add_argument('-i', '--input', default='confout.gro', nargs='?',
	help='input gro file (will be read only initial coordinate)')
parser.add_argument('-g', '--grid', default=15, nargs='?', type=int,
	help='number of slices on original cell (not super cell)')
parser.add_argument('-s', '--nsuper', default=2, nargs='?', type=int,
	help='super cell scaling of input gro file')
parser.add_argument('-name', '--name', default='WR', nargs='?',
	help='model name (WR/PB)')
parser.add_argument('-itp', '--interp', default='three-states', nargs='?',
	help='interpolation method (ex. grid/rbf and nearest/linear/cubic/three-states')
parser.add_argument('-n_ensembles', '--n_ensembles', default=0, nargs='?', type=int,
	help='generate # ensembles by trans, flip, and switch axes (randomly #generated up to # you set, but 0 = min.#, negative = max.#)')
parser.add_argument('-seed', '--seed', default=1985, nargs='?', type=int,
	help='random seed to shuffle for augmentation')
parser.add_argument('-debug', '--debug', action='store_true',
	help='(debug) output gro file for interpolation result')
parser.add_argument('-o', '--output', default='confout.gro', nargs='?',
	help='output npy file for input file (ex. confout.gro.npy)')
parser.add_argument('args', nargs=argparse.REMAINDER)
parser.add_argument('-v', '--version', action='version', version='%(prog)s 3.0')
# read args
args = parser.parse_args()
# check args
print(" input arguments: {0}".format(args))

# import modules
import numpy as np
import scipy as sc
import mdtraj as md
import math
import copy

# set variables
input_gro_file = args.input
n_grid = args.grid
supercell_scale = args.nsuper
output_file = args.output
np.random.seed(args.seed)

# read gro file (super cell 2x2x2
#  to consider periodic boundary condition for interpolation)
print(" ... reading gro file ...")
traj=md.load(input_gro_file)
gro_xyz=traj.xyz[0] # read initial coordinate in time
gro_box=traj.unitcell_lengths[0] # read initial coordinate in time
if (gro_box[0] != gro_box[1]) or (
	gro_box[0] != gro_box[2]) or (
	gro_box[1] != gro_box[2]):
	raise ValueError("cell dimension of input gro file is not isotropic.")

# make color map
# should be select depending on your model.
print(" ... making color map ...")
idx_a = traj.top.select("name A")
idx_b = traj.top.select("name B")
gro_color=np.zeros(traj.top.n_atoms)
if "WR" in args.name: # for WR model,
	print(" activate assigning colors for WR model ")
	gro_color[idx_a] = 0.
	gro_color[idx_b] = 1.
elif "PB" in args.name: # for PB model
	print(" activate assigning colors for PB model ")
	gro_color[idx_a] = 1.
	gro_color[idx_b] = -1.
else:
	raise ValueError("wrong model name, args.name")

print(" ... interpolating ...")
# make mesh grid
x_grid=np.linspace(0,gro_box[0],n_grid*supercell_scale)
xi, yi, zi = np.meshgrid(x_grid, x_grid, x_grid)
interp_module, interp_fn=(args.interp).split("-")
if 'rbf' in interp_module:
	if not (('cubic' in interp_fn) or ('linear' in interp_fn)):
		raise ValueError("wrong argument args.interp, {}".format(args.interp))
	from scipy.interpolate import Rbf
	# radial basis function interpolator instance

	rbfi = Rbf(gro_xyz[:,0], gro_xyz[:,1], gro_xyz[:,2], gro_color, function=interp_fn, smooth=0.0)
	interp_color = rbfi(xi, yi, zi) # interpolated values, shape=[n_grid*supecell_scale,...,...]
	#print("n_color_interpolated = {}".format(len(interp_color)))
elif 'grid' in interp_module:
	if not (('nearest' in interp_fn) or ('linear' in interp_fn)):
		raise ValueError("wrong argument args.interp, {}".format(args.interp))
	if 'nearest' in interp_fn:
		print("nearest interpolation is not tested yet..")
	from scipy.interpolate import griddata
	interp_color = griddata(gro_xyz, gro_color, (xi, yi, zi), method=interp_fn)
elif 'three' in interp_module:
	grid_size = x_grid[1] - x_grid[0]
	add_xyz = []
	# check if the grid overlaps any A/B particles.
	#  otherwise, add it to gro_xyz and gro_color to reflect empty space
	for i in np.arange(n_grid*supercell_scale):
		for j in np.arange(n_grid*supercell_scale):
			for k in np.arange(n_grid*supercell_scale):
				trial_xyz=np.array([xi[i,j,k],yi[i,j,k],zi[i,j,k]])
				over_x = np.abs(gro_xyz[:,0] - trial_xyz[0]) < grid_size/2.
				over_y = np.abs(gro_xyz[:,1] - trial_xyz[1]) < grid_size/2.
				over_z = np.abs(gro_xyz[:,2] - trial_xyz[2]) < grid_size/2.
				over_xy = np.logical_and(over_x,over_y)
				over = np.logical_and(over_z,over_xy)
				if int(np.sum(over)) == 0:
					add_xyz.append(trial_xyz)

	# adding if there exists
	if len(add_xyz) != 0:
		print("we add {} empty particles".format(len(add_xyz)))
		add_xyz = np.array(add_xyz)
		add_xyz = add_xyz.reshape(-1,3)
		if "WR" in args.name:
			add_color = np.repeat(0.5, len(add_xyz))
		elif "PB" in args.name:
			add_color = np.repeat(0., len(add_xyz))
		append_xyz = np.append(gro_xyz,add_xyz)
		gro_xyz = append_xyz.reshape(-1,3)
		gro_color = np.append(gro_color,add_color)
	else:
		print("nothing change with grid-linear. Might be not necessary to consider three spin states.")
	from scipy.interpolate import griddata
	interp_color = griddata(gro_xyz, gro_color, (xi, yi, zi), method='linear')
else:
	raise ValueError("the argument keyword does not match, {} -> {} {}".format(
		args.interp,interp_module,interp_fn))

# remove edges (or nan elements) by slicing
if supercell_scale > 1.:
	print(" ... reducing to original cell ...")
	slice_s = int(n_grid/float(supercell_scale))
	slice_e = slice_s + n_grid
	grid_color=interp_color[slice_s:slice_e,slice_s:slice_e,slice_s:slice_e]
	print(" result (#NaNs): {} -> {}".format(np.sum(np.isnan(interp_color)),np.sum(np.isnan(grid_color))))
	print(" result (#INFs): {} -> {}".format(np.sum(np.isinf(interp_color)),np.sum(np.isinf(grid_color))))
	if (np.sum(np.isnan(grid_color)) > 0.) or (np.sum(np.isinf(grid_color))):
		raise RuntimeError(" Should check why Nan or INF is/are in color map.")

# make variation coordinates of the cell
#  by tranlation, flipping, and switching axes.
print(" ... adding variety of copied cells ...")
max_shift=np.shape(grid_color)[0]
if args.n_ensembles == 0:
	# generate smallest # of copied systems
	print(" ... activate least # of copied systems ...")
	n_systems = 1+3+(max_shift-1)*3+3
	data_out = np.empty([n_systems,max_shift,max_shift,max_shift])
	count=0
	data_out[count] = copy.copy(grid_color)
	count+= 1
	# 1. flip
	for i_flip in range(0,3):
		data_out[count] = np.flip(grid_color, i_flip)
		count += 1
	# 2. shift (up to box dimension)
	for j in range(0,3):
		for i in range(1,max_shift):
			data_out[count] = np.roll(grid_color, i, axis=j)
			count += 1
	# 3. switch axes
	data_out[count] = np.moveaxis(grid_color, 0, 1)
	data_out[count+1] = np.moveaxis(grid_color, 0, 2)
	data_out[count+2] = np.moveaxis(grid_color, 1, 2)
	count += 3
elif args.n_ensembles < 0:
	# generate many # copied systems
	print(" ... generate as many as possible ...")
	n_systems = 1+(1+(1+(1+4*max_shift)*max_shift)*max_shift)*3
	data_out = np.empty([n_systems,max_shift,max_shift,max_shift])
	count=0
	data_out[count] = copy.copy(grid_color)
	count+= 1
	# 1. flip
	for i_flip in range(0,3):
		flip_out = np.flip(grid_color, i_flip)
		data_out[count] = copy.copy(flip_out)
		count += 1
		# 2. shift
		for i in range(0,max_shift):
			cand1 = np.roll(flip_out, i, axis=0)
			data_out[count] = copy.copy(cand1)
			count += 1
			for j in range(0,max_shift):
				cand2 = np.roll(cand1, j, axis=1)
				data_out[count] = copy.copy(cand2)
				count += 1
				for k in range(0,max_shift):
					cand3 = np.roll(cand2, k, axis=2)
					data_out[count] = copy.copy(cand3)
					count += 1
					# 3. switch axes
					data_out[count] = np.moveaxis(cand3, 0, 1)
					data_out[count+1] = np.moveaxis(cand3, 0, 2)
					data_out[count+2] = np.moveaxis(cand3, 1, 2)
					count += 3
else:
	# generate many # copied systems
	print(" ... generate fixed #ensembles ...")
	n_systems = args.n_ensembles
	settings=np.array([[0, 0, 0, 0, 0]]) # original
	#make #random setting for flip, shift, switch, symmetric
	# when asking for more than original data
	while len(settings) < n_systems:
		temp_setting = np.append(np.random.randint(low=0, high=4, size=2),
			np.random.randint(low=0, high=max_shift+1, size=3))
		try:
			settings = np.vstack((settings, temp_setting))
		except ValueError:
			raise RuntimeError("error ", settings, temp_setting)
		settings = np.unique(settings, axis=0)

	if len(settings) != n_systems:
		raise RuntimeError("generating settings has problem in size.")

	# make data_out
	data_out = np.empty([n_systems,max_shift,max_shift,max_shift])
	count=0
	for i_set in settings:
		if i_set[0] != 3:
			flip_out = np.flip(grid_color, i_set[0])
		else:
			flip_out = grid_color
		if i_set[2] != max_shift:
			cand1 = np.roll(flip_out, i_set[2], axis=0)
		else:
			cand1 = flip_out
		if i_set[3] != max_shift:
			cand2 = np.roll(cand1, i_set[3], axis=0)
		else:
			cand2 = cand1
		if i_set[4] != max_shift:
			cand3 = np.roll(cand2, i_set[4], axis=0)
		else:
			cand3 = cand2
		if i_set[1] == 0:
			data_out[count] = np.moveaxis(cand3, 0, 1)
		elif i_set[1] == 1:
			data_out[count] = np.moveaxis(cand3, 0, 2)
		elif i_set[1] == 2:
			data_out[count] = np.moveaxis(cand3, 1, 2)
		else:
			data_out[count] = cand3
		count = count + 1

	if count != n_systems:
		raise RuntimeError("generating ensembles has problem in size.")

# so many ensembles...? (does it really help?)
if count != n_systems:
	raise ValueError("something wrong loop to get system copies")

# (debugging) save pdb file to see color map on grid
if args.debug:
	for i in range(n_systems):
		grid_color = data_out[i]
		print(" ... making {} th debug pdb file ...".format(i))
		f = open(args.input+'.'+str(i)+'.debug.pdb','w')
		f.write("TITLE debug color map on meshgrid \n")
		f.write("CRYST1 {:>8.3f} {:>8.3f} {:>8.3f}  90.00  90.00  90.00 P 1\n".format(
			gro_box[0]/2.,gro_box[0]/2.,gro_box[0]/2.))
		f.write("MODEL        1\n")
		new_x_grid=np.linspace(0,gro_box[0]/2.,(n_grid+1.))
		nx_pts, ny_pts, nz_pts = np.shape(grid_color)
		i_atom = 0
		for ix_pts in range(nx_pts):
			for iy_pts in range(ny_pts):
				for iz_pts in range(nz_pts):
					f.write("ATOM  {:>5}  PTS MSH {:>5}     {:>7.3f} {:>7.3f} {:>7.3f}  1.00 {:>5.2f} \n".format(
						i_atom+1,i_atom+1,new_x_grid[ix_pts],new_x_grid[iy_pts],new_x_grid[iz_pts],
						grid_color[ix_pts,iy_pts,iz_pts]*10.))
					i_atom += 1
		f.write("TER \n")
		f.write("ENDMDL \n")
		f.close()

# save file
print("save the file: [{},{},{},{}]".format(n_systems,max_shift,max_shift,max_shift))
np.save(output_file, data_out.flatten())
print("Done: make npy file for interpolation on grid")


text:
#!/usr/bin/env python

from scipy.misc import imread, imsave, imresize, imshow

img = imread('vim.png')
print img.dtype, img.shape

img_tinted = img * [1, 0.95, 0.9, 0.9] # here we multiply by 4-dim instead of 3-dim as it has 4 for svg images
img_tinted = imresize(img_tinted, (300, 300))

imsave('vim_tinted.png', img_tinted)
imshow(img)
imshow(img_tinted)

ext: py

max_stars_repo_name: DeercoderPractice/python

max_issues_repo_name: DeercoderPractice/python

max_forks_repo_name: DeercoderPractice/python

reason: from scipy


text:
import multiprocessing
import time
import math
from typing import ContextManager
import numpy as np
from joblib import Parallel, delayed
from tqdm import tqdm
from multiprocessing import Pool
from contextlib import contextmanager
from operator import itemgetter
from sklearn.metrics import average_precision_score, roc_auc_score
from dtw_utils import dtw_path
from size import getsize
from load_data import load_predicted_labels, load_test_labels
from save_data import (save_classification_data,
                       delete_classification_data,
                       save_current_test_data,
                       save_nn_with_false_label,
                       save_predicted_labels,
                       delete_predicted_labels)

def index_time_series_list(time_series_list, index):
    """indexes a python list, using a numpy array

    Args:
        time_series_list (List of time Series)
        index (numpy array)

    Returns:
        List of time Series: new time series list, indexed by the index array
    """
    new_time_series_list = []
    for i in index:
        new_time_series_list.append(time_series_list[i])
    return new_time_series_list

def classify(labvitals_list_train, labvitals_list_test, labels_train, labels_test, test_length_start, test_length,
             best_k=5, print_res=True, save_classification=False, num_cores=-1, result=True):
    """classifies the test data wrt the given train data

    Args:
        labvitals_list_train (List of time Series): List of time series for training
        labvitals_list_test (List of time Series): List of time series for testing
        labels_train (List of Integers): training labels
        labels_test (List of Integers): testing labels
        best_k (int, optional): number of nearest neighbors. Defaults to 5.
        print_res (bool, optional): Print results or not. Defaults to True.
        save_classification (bool, optional): Save the results of the classification.
                                              Defaults to False.
        sum_cores (int, optional): Number of cores for multitasking. Defaults to -1.

    Returns:
        float: mean auprc score
        float: mean roc auc score
    """
    # delete old data if one wants to save new data
    if save_classification:
        #delete_classification_data()
        pass

    # always delete this, needed for parallelization
    #delete_predicted_labels()

    cpu_count = multiprocessing.cpu_count()
    if num_cores == -1 or num_cores < 1 or num_cores > cpu_count:
        num_cores = cpu_count - 4

    knn(labvitals_list_train, labvitals_list_test,
        labels_train, test_length_start, test_length, k=best_k,
        save_classification=save_classification, num_cores=num_cores)

    # get predicted labels from database (they were saved in knn method)
    # resort them and only extract the labels and not the indices.
    if result:
        labels_test = load_test_labels()
        labels_test = sorted(labels_test, key=itemgetter(1))
        labels_test = list(map(list, zip(*labels_test)))[0]
        labels_test = [item for sublist in labels_test for item in sublist]
        pred_labels = load_predicted_labels()
        pred_labels = sorted(pred_labels, key=itemgetter(1))
        pred_labels = list(map(list, zip(*pred_labels)))[0]
        print(labels_test)
        print(pred_labels)

        mean_score_auprc = average_precision_score(labels_test, pred_labels)
        mean_score_roc_auc = roc_auc_score(labels_test, pred_labels)

        if print_res:
            print("Mean score_auprc:   {}".format(mean_score_auprc))
            print("Mean score_roc_auc: {}".format(mean_score_roc_auc))
    else:
        mean_score_auprc = -1
        mean_score_roc_auc = -1

    if save_classification:
        save_current_test_data(labvitals_list_test)

    return mean_score_auprc, mean_score_roc_auc

def knn(time_series_list_train, time_series_list_test, labels_train, test_length_start, test_length,
        k=5, save_classification=False, num_cores=-1):
    """perfomrs K nearest neighbors for the given train and test set.

    Args:
        time_series_list_train (List of time Series): List of time series for training
        time_series_list_test (List of time Series): List of time series for testing
        labels_train (List of Integers): training labels
        labels_test (List of Integers): testing labels
        k (int, optional): number of nearest neighbors. Defaults to 5.
        save_classification (bool, optional): Save the results of the classification.
                                              Defaults to False.

    Returns:
        float: auprc score
        float: roc auc score
    """
    pred_labels = []
    # iloc[:, 6:] just cuts off the first 6 columns,
    # since we don't need them for calculating anything
    number_of_channels = time_series_list_train[0].iloc[:, 6:].shape[1]

    # parallel call for the predict method
    """
    Parallel(n_jobs=num_cores, backend="loky")(delayed(predict)(input, parameters, i)
                                    for i, input in enumerate(inputs))
    """
    split = 100
    for it in range(math.ceil(test_length / split)):
        parameters = (pred_labels, number_of_channels, save_classification,
                  k, labels_train, time_series_list_train)

        # create progress bar for time_series_list_test
        inputs = tqdm(time_series_list_test[it*split:(it+1)*split], desc="Claculating DTW distance for entire test data",
                 leave=True, position=2)
        with poolcontext(processes=num_cores) as pool:
            print(test_length_start)
            print(len(inputs))
            r = pool.map_async(predict_unpack, [(input, parameters, i+it*split+test_length_start) for i, input in enumerate(inputs)])
            r.wait()
    # k_nearest_time_series:
    # [[nn_1, ..., nn_k], ..., [nn_1, ..., nn_k]]
    # one list for each test point

    # best_paths:
    # [ [[(), ..., ()], ..., [(), ..., ()]], ..., [[(), ..., ()], ..., [(), ..., ()]] ]
    # one list for each test point
    # one 1. inner list for each channel
    # one 2. inner list for each k nearest neighbor
    # each 2. inner list is a DTW path

    # best_distances:
    # [[], ..., []]

def predict(time_series_test, parameters, i):
    """predict the labels for the given test and train data

    Args:
        time_series_test (Pandas time Series): one test time series
        parameters (Tuple): Tuple of the other parameters:
                            pred_labels (List): List of the predicted labels
                            number_of_channels (int): Number of channels (labvitals)
                            save_classification (bool): Save classification data or not
                            k (int): k for k nearest neighbors
                            labels_train (List): List of training labels
                            time_series_list_train (List): List of training time series
        i (int): number of current test point to restore correct order in the end

    Returns:
        List: predicted labels (each test point gets appened and then
              the new list will be passed to this method again)
    """
    pred_labels, number_of_channels = parameters[0:2]
    save_classification, k = parameters[2:4]
    labels_train, time_series_list_train = parameters[4:6]
    distances_per_test_point = []
    best_paths_per_test_point = []
    dtw_matrices_per_test_point = []
    for time_series_train in tqdm(time_series_list_train, desc="Calculating DTW distance for one test point", leave=False):
        distances_per_train_point = []
        #best_paths_per_train_point = []
        #dtw_matrices_per_train_point = []
        for channel in range(number_of_channels):
            # distance from one test point to all training points
            s1 = np.array(time_series_test.iloc[:, 6:].iloc[:, [channel]])
            s2 = np.array(time_series_train.iloc[:, 6:].iloc[:, [channel]])
            dist = dtw_path(s1,s2)
            distances_per_train_point.append(dist)
            #best_paths_per_train_point.append(best_path)
            #dtw_matrices_per_train_point.append(dtw_matrix)

        #best_paths_per_test_point.append(best_paths_per_train_point)
        distances_per_test_point.append(distances_per_train_point)
        #dtw_matrices_per_test_point.append(dtw_matrices_per_train_point)

        #del distances_per_train_point, best_paths_per_train_point, dtw_matrices_per_train_point, best_path, dist
    distances_per_test_point = np.array(distances_per_test_point)
    distances = np.mean(distances_per_test_point, axis=1)
    sorted_distances = np.argsort(distances)
    nearest_neighbor_id = sorted_distances[:k]

    #print("{}".format(getsize((dtw_matrices_per_test_point, distances_per_test_point, distances, best_paths_per_test_point, time_series_list_train))))

    if save_classification:
        """
        save_classification_data((index_time_series_list(time_series_list_train, nearest_neighbor_id), i),
                                 (index_time_series_list(best_paths_per_test_point, nearest_neighbor_id), i),
                                 (index_time_series_list(distances, nearest_neighbor_id), i),
                                 (index_time_series_list(distances_per_test_point, nearest_neighbor_id), i),
                                 (index_time_series_list(dtw_matrices_per_test_point, nearest_neighbor_id), i))
        """
        save_classification_data((index_time_series_list(time_series_list_train, nearest_neighbor_id), i),
                                 (index_time_series_list(distances, nearest_neighbor_id), i))

    pred_label = labels_train[nearest_neighbor_id]
    # finds most frequently occurring label
    pred_label = np.bincount(pred_label).argmax()
    # this will always be saved since it is needed for parallelization
    save_predicted_labels((pred_label, i))

    find_nn_with_false_label(sorted_distances, labels_train, pred_label,
                             time_series_list_train, save_classification)

    #del time_series_list_train, best_paths_per_test_point, distances, distances_per_test_point, pred_label

    #return pred_labels

def predict_unpack(args):
    return predict(*args)

@contextmanager
def poolcontext(*args, **kwargs):
    pool = multiprocessing.Pool(*args, **kwargs)
    try:
        yield pool
    finally:
        time.sleep(2)
        pool.terminate()
        pool.join()
        pool.close()

def find_nn_with_false_label(sorted_distances, labels_train, pred_label,
                             time_series_list_train, save_classification):
    """find the nearest neighbor that has a different label than the predicted one and
       saves it if required. Method is useless if the result does not get saved.

    Args:
        sorted_distances (List): List of indices of sorted distances
        labels_train (List): List of trianing labels
        pred_label (List): List of predicted Lbales
        time_series_list_train (List of time Series): List of time series for training
        save_classification (bool, optional): Save the results of the classification.
                                              Defaults to False.
    """
    if save_classification:
        i = 0
        dist = sorted_distances[i]
        while labels_train[dist] == pred_label:
            i += 1
            dist = sorted_distances[i]
        nn_with_false_label = time_series_list_train[dist]
        save_nn_with_false_label(nn_with_false_label, true_label=pred_label, false_label=labels_train[dist])

reason: import numpy


text:
import copy
import numpy as np
from scipy import signal
import scipy.stats as st

curr_pos, cp, fname = 0, 0, 'frame'

def mad(x):
    """ Returns the median absolute deviation.

        **Parameters**

        x : double
            Data array

        **Returns**

        The median absolute deviation of input signal x.
    """
    return 1.4826 * np.median(np.abs(x - np.median(x)))

def quantiles(x, prob=[0, 0.25, 0.5, 0.75, 1]):
    """ Computes the five quantiles of the input vector,
        prob is a list of quantiles to compute.

        **Parameters**

        x : double
            Data array

        prob : double
            List of quantiles to compute

        **Returns**

        A vector containing all the computed quantilies for the input signal x.
    """
    return st.mstats.mquantiles(x, prob=prob)

def convolution(x, window):
    """ A scipy fftconvolution wrapper function.

        **Parameters**

        x : double
            Data array

        window : double
            Filter window

        **Returns**

        The convolution of the input signal with a predefined window (win).
    """
    return signal.fftconvolve(x, window, 'same')

def f(x, median, mad, thr):
    """ Auxiliary function, used by good_evts_fct.

        **Parameters**

        x : double
            Data array

        median : double
            Array contains median values

        mad : double
            Array contains mad values

        thr : double
            Filtering threshold

        **Returns**
        A numpy array containing the data for which the |X-median(X)|/mad(X) <
        thr.
    """
    return np.ndarray.all(np.abs((x - median)/mad) < thr)

def good_evts_fct(x, thr=3):
    """ Clean the spike events times.

        **Parameters**

        x : double
            Data array

        thr : double
            Threshold of filtering

        **Returns**
        A vector containing all the detected good events.
    """
    samp_median = np.apply_along_axis(np.median, 0, x)
    samp_mad = np.apply_along_axis(mad, 0, x)
    above = samp_median > 0

    samp_r = copy.copy(x)

    for i in range(len(x)):
        samp_r[i][above] = 0

    samp_median[above] = 0
    res = np.apply_along_axis(f, 1, samp_r, samp_median,
                              samp_mad, thr)
    return res

def cut_sgl_evt(x, position, before, after):
    """ Draw a singles event from the input data.

        **Parameters**

        x : double (array)
            Input data

        position : int
            The index (location) of the (peak of) the event.

        before : int
            How many points should be within the cut before the reference
            index / time given by position.

        after : int
            How many points should be within the cut after the reference
            index / time given by position.

        **Returns**
        A vector with the cuts on the different recording sites glued one after
        the other.
    """
    ns = x.shape[0]             # Number of recording sites
    dl = x.shape[1]             # Number of sampling points
    cl = before + after + 1     # The length of the cut
    cs = cl * ns                # The 'size' of a cut
    cut = np.zeros((ns, cl))
    idx = np.arange(-before, after + 1)
    keep = idx + position
    within = np.bitwise_and(0 <= keep, keep < dl)
    kw = keep[within]
    cut[:, within] = x[:, kw].copy()
    return cut.reshape(cs)

max_stars_repo_name: mgraupe/SPySort

max_issues_repo_name: mgraupe/SPySort

max_forks_repo_name: mgraupe/SPySort

reason: import numpy,import scipy,from scipy


text:
import numpy as np
from astropy.time import Time
from baselayer.app.env import load_env

_, cfg = load_env()
# The minimum signal-to-noise ratio to consider a photometry point as a detection
PHOT_DETECTION_THRESHOLD = cfg["misc.photometry_detection_threshold_nsigma"]

def test_mjd_to_iso_conversion(public_source):
    m1, m2 = list(
        zip(
            *[
                (Time(phot.iso.isoformat()[:-6], format='isot').mjd, phot.mjd)
                for phot in public_source.photometry
                if phot.snr and phot.snr > PHOT_DETECTION_THRESHOLD
            ]
        )
    )
    np.testing.assert_allclose(m1, m2)

max_stars_repo_name: bparazin/skyportal

max_issues_repo_name: bparazin/skyportal

max_forks_repo_name: bparazin/skyportal

reason: import numpy,from astropy


text:
from diatom import MoleculeData
import unittest
import numpy as np

class TestMoleculeData(unittest.TestCase):

    # def test_reduced_mass_type(self):
    #     mdata = MoleculeData()
    #     mdata._calculate_molecule_reduced_mass(1)

    def test_molecule_symbol_fail(self):

        mdata = MoleculeData()

        # pass
        self.assert_is_instance_of_float(mdata, '1H 1H')
        self.assert_is_instance_of_float(mdata, '1 H 1 H')
        self.assert_is_instance_of_float(mdata, '1 H 1H')
        self.assert_is_instance_of_float(mdata, '1H 1 H')
        self.assert_is_instance_of_float(mdata, ' 1H1H')
        self.assert_is_instance_of_float(mdata, '1H1H ')

        # fail
        self.assert_raised_error(mdata, 'H1H1')
        self.assert_raised_error(mdata, '1HH')
        self.assert_raised_error(mdata, 'H1H1H')

        self.assertTrue(
            mdata._calculate_molecule_reduced_mass('1H1H') < 1.0
        )

        self.assertRaises(
            AttributeError, mdata._calculate_molecule_reduced_mass, 1
        )

    def assert_raised_error(self, mdata, symbol):

        self.assertRaises(
            SystemExit, mdata._calculate_molecule_reduced_mass, symbol
        )

    def assert_is_instance_of_float(self, mdata, symbol):

        self.assertIsInstance(
            mdata._calculate_molecule_reduced_mass(symbol), float
        )

    def test_molecule_property(self):

        mdata = MoleculeData()

        # string should not work
        try:
            mdata.molecule = '58Ni1H'
        except SystemExit:
            pass

        # tuple or list of strings should work
        mdata.molecule = '58Ni1H',
        self.assertTrue(len(mdata.reduced_masses) == 1)

        mdata.molecule = ['58Ni1H']
        self.assertTrue(len(mdata.reduced_masses) == 1)

    def test_masses_property(self):

        mdata = MoleculeData()

        # number or string should not work
        try:
            mdata.masses = 1.0
        except TypeError:
            pass

        # tuple or list of numbers should work
        mdata.masses = 1.0,
        self.assertEqual(len(mdata.imasses), 1)

        mdata.masses = [1.0]
        self.assertEqual(len(mdata.imasses), 1)

    def test_jrange_and_jvalues_property(self):

        mdata = MoleculeData()

        mdata.jrange = 1, 5
        self.assertCountEqual(mdata.jqnumbers, np.array([1, 2, 3, 4, 5]))
        mdata.jqnumbers = np.array([], dtype=np.float64)

        mdata.jrange = 1, 1
        self.assertCountEqual(mdata.jqnumbers, np.array([1]))
        mdata.jqnumbers = np.array([], dtype=np.float64)

        mdata.jrange = 1, 0
        self.assertEqual(mdata.jqnumbers.shape[0], 0)
        mdata.jqnumbers = np.array([], dtype=np.float64)

        mdata.jvalues = 1, 12, 15, 3, 12, 4
        self.assertCountEqual(mdata.jqnumbers, np.array([1, 3, 4, 12, 15]))
        mdata.jrange = 1, 4
        self.assertCountEqual(mdata.jqnumbers, np.array([1, 2, 3, 4, 12, 15]))

        mdata.referencej = 2
        self.assertEqual(mdata.jqnumbers[0], 2)
        self.assertCountEqual(mdata.jqnumbers, set(mdata.jqnumbers))

    def test_parity_property(self):

        mdata = MoleculeData()

        mdata.parities = 1,
        self.assertEqual(len(mdata.pars), 1)

        mdata.parities = 1, 0
        self.assertCountEqual(mdata.pars, [0, 1])

        mdata.parities = 0
        self.assertEqual(len(mdata.pars), 1)

max_stars_repo_name: ihavalyova/Diatom

max_issues_repo_name: ihavalyova/Diatom

max_forks_repo_name: ihavalyova/Diatom


text:
"""
This module contains helpers to draw with evap code.
"""

import numpy as np
import matplotlib.pyplot as plt
import copy
import matplotlib.hatch
import matplotlib as mpl
import matplotlib.colors

import xhorizon as xh
from xhorizon.shell_junction import interpolators as interp
from helpers import irr

############## plot reglist ####################

## styles
rline_zero_sty      = dict(lw=1.5, c='0.48', zorder=11000)
singularity_sty     = dict(ls='dashed', dashes=(2,2))
rline_inf_sty       = dict(lw=1.5, c='0.48', zorder=10000)
rline_hor_sty       = dict(lw=0.4, c='k', zorder=9999)
rline_sty           = dict(ls='-', zorder=10, lw=.6, alpha=.5)
acc_shells_sty      = dict(lw=0.6, ls='dashed', dashes=(3,3), zorder=2000)
evap_shells_out_sty = acc_shells_sty
evap_shells_in_sty  = dict(lw=1., ls='dashed', dashes=(1,1.2), zorder=2000)
fill_horizons_sty   = dict(fc='none', ec='k', lw=0, hatch='c', zorder=9990)
fill_density_sty    = dict(zorder=100)
tick_sty            = dict(markersize=10, markeredgecolor='k', alpha=.3, zorder=100)

def drawreg(reglist, chainparams, fparams=dict()):
	"""
	Plot all regions in reglist.
	"""
	l=fparams['l']
	R=fparams['R']

	## lines
	rline_zero(reglist, sty=rline_zero_sty, sty2=singularity_sty, npoints=1001)
	rline_inf_col(reglist, sty=rline_inf_sty, npoints=5001, inf=100., M=0.5*R)
	rline_hor(reglist, sty=rline_hor_sty)
	acc_shells(reglist, chainparams, sty=acc_shells_sty, inf=100., npoints=1001)
	evap_shells_out(reglist, chainparams, sty=evap_shells_out_sty, inf=100., npoints=1001)
	evap_shells_in(reglist, chainparams, sty=evap_shells_in_sty, inf=100., npoints=1001)
	make_rlines(reglist, chainparams, l=l, R=R, Tevap=5., sty=rline_sty)
	vticks(reglist, dv=0.5, sty=tick_sty)
	uticks(reglist, du=0.5, sty=tick_sty)
	tticks(reglist, dt=0.5, sty=tick_sty)
	## plot
	for reg in reglist:
		reg.rplot()
	## fill
	fill_horizons(reglist, sty=fill_horizons_sty)
	fill_density(reglist, sty=fill_density_sty)

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

## being actually used ############

def rline_zero(reglist, npoints=5001, inf=100., sty={}, sty2={}):
	"""
	Add boundary lines to regions in reglist.
	"""
	for reg in reglist:
		for b in reg.blocks:
			if b.j==0:
				## style
				style = dict(lw=0.9, c='0.5', zorder=11000)
				style.update(sty)
				## singularity style
				if b.sgnf<0.:
					style.update(sty2)
				## cutoff style
				if reg.metfunc.info['Type'] in ['Hayward - de Sitter with Cutoff']:
					lw = 1.5*(1.+ 2.)
					style.update(lw=lw)
				## curve
				cv = xh.cm.rstarlines_special_2([0.], b.uvbounds, c=1.*reg.rparams['c'], sty=style, inf=1.*inf, npoints=1.*npoints, eps=1e-12)
				b.add_curves_uv(cv)

def rline_inf_col(reglist, npoints=5001, inf=100., sty={}, M=.5):
	"""
	Add boundary lines to regions in reglist.
	"""
	for reg in reglist:
		for b in reg.blocks:
			## outermost blocks only
			if b.j==len(b.master.metfunc.rj)-2:
				## style
				style = dict(c='0.5', zorder=10000)
				style.update(sty)
				## rstar value
				rstar = b.master.metfunc.rstar_ref[-1]
				## mass
				m = 0.
				if 'R' in b.master.metfunc.fparams.keys():
					m = 0.5 * b.master.metfunc.fparams['R']
				## linewidth
				lw0 = 1.*style['lw']
				lw = lw0 * (1.+2.*m/M)
				style.update(dict(lw=lw))
				## curve
				style.update(solid_capstyle='projecting')
				b.add_curves_uv(xh.cm.block_boundary_2(b, sty=style, inf=2., npoints=npoints)[-1:])
				style.update(solid_capstyle='butt')
				b.add_curves_uv(xh.cm.block_boundary_2(b, sty=style, inf=inf, npoints=npoints)[-1:])

def rline_hor(reglist, npoints=5001, sty={}):
	"""
	Add horizon lines to regions in reglist.
	"""
	for reg in reglist:
		for b in reg.blocks:
			## trapped blocks only
			if b.sgnf<0.:
				## style
				style = dict(lw=0.2, c='k', zorder=9999)
				style.update(sty)
				## rstar value
				rstar = b.master.metfunc.rstar_ref[-1]
				## curve
				cvs = xh.cm.block_boundary_2(b, sty=style, inf=100., npoints=npoints)
				if b.j==0:
					cvs = cvs[-1:]
				## add
				b.add_curves_uv(cvs)

def shell_col(x):
	Cmax = .8
	return np.array([1.,1.,1.]) - 0.33*(1.+2.*x)*Cmax

def acc_shells(reglist, chainparams, sty={}, inf=50., npoints=5001):
	"""
	Add boundary lines to regions in reglist.
	"""
	Rh = chainparams['Rh']
	v0 = chainparams['fs_v0']-1e-15
	m = chainparams['m']
	M = np.max(m)
	for i in range(len(reglist[:-1])):
		reg = reglist[i]
		## accretion only
		if Rh[i+1]>Rh[i]:
			##
			for b in reg.blocks:
				## mass
				dm = m[i+1] - m[i]
				print("ACC SHELL COLOR dm/M=%s"%(dm/M))
				col = shell_col(dm/M)
				## style
				style = dict(lw=0.2, ls='dashed', dashes=(4,4), c=1.*col, zorder=2000)
				style.update(sty)
				## v value
				vv = v0[i:i+1]
				## curve
				b.add_curves_uv(xh.cm.uvlines(vv, uv='v', uvbounds=b.uvbounds, sty=style, c=0., inf=inf, npoints=npoints))

def evap_shells_out(reglist, chainparams, sty={}, inf=100., npoints=5001):
	"""
	Add boundary lines to regions in reglist.
	"""
	Rh = chainparams['Rh']
	u0 = chainparams['fs_u0']-1e-15
	m = chainparams['m']
	M = np.max(m)
	for i in range(len(reglist[:-1])):
		reg = reglist[i]
		## evap only
		if Rh[i+1]<Rh[i]:
			## outgoing
			for b in reg.blocks:
				if b.bparams['epsu']>0.:
					if not np.isfinite(b.uvbounds['vmax']):
						## mass
						dm = - (m[i+1] - m[i])
						print("EVAP OUT SHELL COLOR dm/M=%s"%(dm/M))
						col = shell_col(dm/M)
						## style
						style = dict(lw=0.2, ls='dashed', dashes=(4,4), c=1.*col, zorder=2000)
						style.update(sty)
						## u value
						uu = u0[i:i+1]
						## curve
						b.add_curves_uv(xh.cm.uvlines(uu, uv='u', uvbounds=b.uvbounds, sty=style, c=0., inf=inf, npoints=npoints))

def evap_shells_in(reglist, chainparams, sty={}, inf=5., npoints=5001):
	"""
	Add boundary lines to regions in reglist.
	"""
	Rh = chainparams['Rh']
	u0 = chainparams['fs_u0']
	v0 = chainparams['fs_v0']-1e-15
	r0 = chainparams['fs_r0']
	m = chainparams['m']
	M = np.max(m)
	for i in range(len(reglist[:-1])):
		reg = reglist[i]
		## evap only
		if Rh[i+1]<Rh[i]:
			## uv value
			uu = u0[i:i+1]
			vv = v0[i:i+1]
			rr = r0[i:i+1]
			## ingoing
			for b in reg.blocks:
				## mass
				dm = - (m[i+1] - m[i])
				print("EVAP IN SHELL COLOR dm/M=%s"%(dm/M))
				col = shell_col(dm/M)
				## style
				style = dict(lw=0.9, ls=':', c=1.*col, zorder=2000)
				style.update(sty)
				## inner blocks
				if b.rj[1]<rr:
					## values
					u = np.sort(np.concatenate([np.linspace(-1e-3,-1.,npoints//2),np.linspace(1e-3,1.,npoints//2),np.linspace(-inf,inf,npoints)]))
					v = vv+0.*u
					## make curve
					cv = xh.curve()
					cv.uv = np.array([u,v])
					cv.sty.update(style)
					## add
					b.add_curves_uv([cv])
				## outer block
				elif b.rj[0]<rr and not np.isfinite(b.uvbounds['umax']):
					## values
					u = np.linspace(uu,inf,npoints)
					v = vv+0.*u
					## make curve
					cv = xh.curve()
					cv.uv = np.array([u,v])
					cv.sty.update(style)
					## add
					b.add_curves_uv([cv])

def fill_horizons(reglist, sty={}):
	##
	for i in range(len(reglist)):
		reg = reglist[i]
		for b in reg.blocks:
			if b.sgnf < 0.:
				style = dict(fc='none', ec='k', lw=0, hatch='.', zorder=9990)
				style.update(sty)
				b.fill(sty=style)

def fill_density(reglist, sty={}):
	## regions
	for reg in reglist:
		## linespacing
		x = np.arange(0.,10.1,.5)
		## default to zero
		density = 0.*x
		## vac spacetimes
		vac = ['Schwarzschild', 'Minkowski', 'Anti de Sitter', 'de Sitter', 'Hayward - de Sitter with Cutoff']
		if reg.metfunc.info['Type'] in vac:
			for b in reg.blocks:
				b.fill(dstyle(0.))
		## hayward
		if reg.metfunc.info['Type'] in ['Hayward', 'Hayward - Anti de Sitter', 'Hayward - de Sitter']:
			## get params
			l = reg.metfunc.fparams['l']
			R = reg.metfunc.fparams['R']
			## rcore and r
			rcore = (R*l**2.)**(1./3.)
			r = rcore * x
			rmax = 100.
			r = np.concatenate([r, np.array([rmax])])
			## density
			density = 1./(1.+x**3.)**2.   # rho/rho0 = 1/(1+x^3)^2
			## blocks
			for b in reg.blocks:
				## loop over radii
				for n in range(len(x)):
					## rr and rho
					rr = r[n:n+2]
					rho = density[n]
					## style
					style = dstyle(rho)
					## fill
					rvals=b.fill_between_r(rr, sty=style, npoints=1001, inf=50.)

def dstyle(rho, cm=plt.cm.Oranges, sty={}, ovr={}):
	"""
	Density rho in (0,1), output fill style.
	Since all Hayward have same l, all regions same scale.
	"""
	## style
	style = dict(fc='none', ec='none', lw=0, zorder=900)
	style.update(sty)
	## cnorm
	cmin, cmax = .1, .6
	cnorm = cmin + (cmax-cmin)*rho
	## color and alpha
	style.update(fc=cm(cnorm), alpha=.75)
	## override
	style.update(ovr)
	## return
	return style.copy()

def make_rlines(reglist, chainparams, l=.05, R=1., Tevap=None, sty={}):
	"""
	"""
	## params
	R = 1.*R
	l = 1.*l
	rcore = (R*l**2)**(1./3.)
	## general
	style = dict(ls='-', zorder=10, lw=.4, alpha=.2)
	style.update(sty)
	## l scale
	x = np.arange(0.,.5*R/l,.5)
	scale = l
	style.update(dict(c='c'))
	rlines(reglist, scale*x, sty=style, inf=10., npoints=2001.)
	## R scale
	x = np.arange(0.,20.01,.5)
	scale = R
	style.update(dict(c='m'))
	rlines(reglist, scale*x, sty=style, inf=25., npoints=1001.)
	## Tevap scale
	if Tevap is not None:
		x = np.arange(.8,25.01,.5)
		scale = Tevap
		style.update(dict(c='#0000f0'))
		rlines(reglist, scale*x, sty=style, inf=25., npoints=1001.)

def vticks(reglist, dv=1., inf1=100., inf2=50.+irr, sty={}):
	"""
	Remainder lets dv carry across regions.
	"""
	## init
	remainder = 0.
	## regions
	for reg in reglist:
		## blocks
		for b in reg.blocks:
			## last blocks only
			if b.j == len(reg.metfunc.rj)-2:
				## outer last blocks only
				if not np.isfinite(b.uvbounds['umin']):
					## get min and max
					vmin = np.max([b.uvbounds['vmin'], -inf2])
					vmax = np.min([b.uvbounds['vmax'],  inf2])
					## is it too small
					toosmall = False
					if vmax-vmin <= remainder:
						toosmall = True
					## if too small adjust remainder
					if toosmall==True:
						remainder = remainder - (vmax-vmin)
					## if big enough go
					if toosmall==False:
						## make array
						vv = remainder + np.arange(vmin, vmax, dv)
						## get new remainder
						remainder = dv - (vmax - vv[-1])
						## make and add curve
						crv = xh.curve()
						crv.uv = np.array([-inf1+0.*vv, 1.*vv])
						style = dict(markeredgecolor='k', alpha=0.3, ls='none', marker=(2,0,45), markersize=7, zorder=-100)
						style.update(sty)
						crv.sty.update(style)
						b.add_curves_uv([crv])

def uticks(reglist, du=1., inf1=100., inf2=50.+irr, sty={}):
	"""
	Remainder lets dv carry across regions.
	"""
	## init
	remainder = 0.
	## regions
	for reg in reglist:
		## blocks
		for b in reg.blocks:
			## last blocks only
			if b.j == len(reg.metfunc.rj)-2:
				## outer last blocks only
				if not np.isfinite(b.uvbounds['vmax']):
					## get min and max
					umin = np.max([b.uvbounds['umin'], -inf2])
					umax = np.min([b.uvbounds['umax'],  inf2])
					## is it too small
					toosmall = False
					if umax-umin <= remainder:
						toosmall = True
					## if too small adjust remainder
					if toosmall==True:
						remainder = remainder - (umax-umin)
					## if big enough go
					if toosmall==False:
						## make array
						uu = remainder + np.arange(umin, umax, du)
						## get new remainder
						remainder = du - (umax - uu[-1])
						## make and add curve
						crv = xh.curve()
						crv.uv = np.array([1.*uu, inf1+0.*uu])
						style = dict(markeredgecolor='k', alpha=.3, marker=(2,0,-45), ls='none', markersize=7, zorder=100)
						style.update(sty)
						crv.sty.update(style)
						b.add_curves_uv([crv])

def tticks(reglist, dt=1., inf1=1., inf2=50.+irr, sty={}):
	"""
	Remainder lets dt carry across regions.
	"""
	if reglist[0].metfunc.info['Type']=='Anti de Sitter':
		inf1 = 9.*reglist[0].metfunc.fparams['L']
		## init
		remainder = 0.
		## regions
		for reg in reglist:
			## blocks
			for b in reg.blocks:
				## last blocks only
				if b.j == len(reg.metfunc.rj)-2:
					## outer last blocks only
					if (not np.isfinite(b.uvbounds['vmax'])) or (not np.isfinite(b.uvbounds['umin'])):
						## get min and max
						umin = np.max([b.uvbounds['umin'], -inf2])
						umax = np.min([b.uvbounds['umax'],  inf2])
						vmin = np.max([b.uvbounds['vmin'], -inf2])
						vmax = np.min([b.uvbounds['vmax'],  inf2])
						tmin = 0.5*(vmin+umin)
						tmax = 0.5*(vmax+umax)
						## is it too small
						toosmall = False
						if tmax-tmin <= remainder:
							toosmall = True
						## if too small adjust remainder
						if toosmall==True:
							remainder = remainder - (tmax-tmin)
						## if big enough go
						if toosmall==False:
							print "HELLLOOOOOOOOO tticks"
							print tmin, tmax, dt
							## make array
							tt = remainder + np.arange(tmin, tmax, dt)
							## get new remainder
							remainder = dt - (tmax - tt[-1])
							## make and add curve
							crv = xh.curve()
							crv.tr = np.array([1.*tt,1.*inf1])
							style = dict(markeredgecolor='k', alpha=.3, marker=(2,0,90), ls='none', markersize=7, zorder=100)
							style.update(sty)
							crv.sty.update(style)
							b.add_curves_tr([crv])

## custom hatch
class CustomHatch(matplotlib.hatch.SmallFilledCircles):
    size = 0.1
    filled = True

    def __init__(self, hatch, density):
        density = 2
        self.num_rows = (hatch.count('c')) * density
        matplotlib.hatch.Circles.__init__(self, hatch, density)

## assign custom hatch
matplotlib.hatch._hatch_types.append(CustomHatch)

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

################# tools for drawing ########################################

def rlines(reglist, rvals, sty={}, npoints=2001, inf=25.):
	"""
	Add colorscaled lines of constant radius to region.
	Useful to check for matching.
	"""
	rvals = 1.*rvals
	for reg in reglist:
		for b in reg.blocks:
			for i in range(len(rvals)):
				if (b.rj[0]<rvals[i]) and (rvals[i]<b.rj[1]):
					style = dict(c='c', ls='-', lw=.5, zorder=1500)
					style.update(sty)
					rstarvals = 1.*b.master.metfunc.F(rvals[i:i+1])
					b.add_curves_uv(xh.cm.rstarlines_special_2(rstarvals, b.uvbounds, c=b.master.rparams['c'], sty=style, inf=1.*inf, npoints=1.*npoints))
	return reglist

def colorlines(reglist, rmin=1.1, rmax=25., dr=.5, sty={}, cm=plt.cm.hsv_r, npoints=2001, inf=25.):
	"""
	Add colorscaled lines of constant radius to region.
	Useful to check for matching.
	"""
	rvals = np.arange(rmin,rmax,dr)
	colvals = (rvals - np.min(rvals)) / (np.max(rvals) - np.min(rvals))
	cols = cm(colvals)
	for reg in reglist:
		for b in reg.blocks:
			for i in range(len(rvals)):
				if (b.rj[0]<rvals[i]) and (rvals[i]<b.rj[1]):
					style = dict(c=cols[i], ls='-', markersize=1, lw=.5, zorder=1500)
					style.update(sty)
					rstarvals = 1.*b.master.metfunc.F(rvals[i:i+1])
					b.add_curves_uv(xh.cm.rstarlines_special_2(rstarvals, b.uvbounds, c=b.master.rparams['c'], sty=style, inf=2.*inf, npoints=npoints))
	return reglist

def s0_lines(reglist, sty={}, npoints=1001, inf=50., eps=1e-24):
	"""
	"""
	for reg in reglist:
		for b in reg.blocks:
			x = np.array([(2.*reg.rparams['s0'] - eps)])
			style1 = dict(c='m', alpha=.5, lw=3, ls=':', zorder=5000)
			style2 = dict(c='c', alpha=.5, lw=3, ls=':', zorder=5000)
			style1.update(sty)
			style2.update(sty)
			b.add_curves_uv(xh.cm.uvlines( x, uv='uv', uvbounds=b.uvbounds, sty=style1, c=0., inf=inf, npoints=npoints))
			b.add_curves_uv(xh.cm.uvlines(-x, uv='uv', uvbounds=b.uvbounds, sty=style2, c=0., inf=inf, npoints=npoints))
	return reglist

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


text:
"""
The ``pvsystem`` module contains functions for modeling the output and
performance of PV modules and inverters.
"""

from __future__ import division

import logging
pvl_logger = logging.getLogger('pvlib')

import io
try:
    from urllib2 import urlopen
except ImportError:
    from urllib.request import urlopen

import numpy as np
import pandas as pd

from pvlib import tools

def systemdef(meta, surface_tilt, surface_azimuth, albedo, series_modules,
              parallel_modules):
    '''
    Generates a dict of system parameters used throughout a simulation.

    Parameters
    ----------

    meta : dict
        meta dict either generated from a TMY file using readtmy2 or readtmy3,
        or a dict containing at least the following fields:

            ===============   ======  ====================
            meta field        format  description
            ===============   ======  ====================
            meta.altitude     Float   site elevation
            meta.latitude     Float   site latitude
            meta.longitude    Float   site longitude
            meta.Name         String  site name
            meta.State        String  state
            meta.TZ           Float   timezone
            ===============   ======  ====================

    surface_tilt : float or Series
        Surface tilt angles in decimal degrees.
        The tilt angle is defined as degrees from horizontal
        (e.g. surface facing up = 0, surface facing horizon = 90)

    surface_azimuth : float or Series
        Surface azimuth angles in decimal degrees.
        The azimuth convention is defined
        as degrees east of north
        (North=0, South=180, East=90, West=270).

    albedo : float or Series
        Ground reflectance, typically 0.1-0.4 for
        surfaces on Earth (land), may increase over snow, ice, etc. May also
        be known as the reflection coefficient. Must be >=0 and <=1.

    series_modules : int
        Number of modules connected in series in a string.

    parallel_modules : int
        Number of strings connected in parallel.

    Returns
    -------
    Result : dict

        A dict with the following fields.

            * 'surface_tilt'
            * 'surface_azimuth'
            * 'albedo'
            * 'series_modules'
            * 'parallel_modules'
            * 'latitude'
            * 'longitude'
            * 'tz'
            * 'name'
            * 'altitude'

    See also
    --------
    pvlib.tmy.readtmy3
    pvlib.tmy.readtmy2
    '''

    try:
        name = meta['Name']
    except KeyError:
        name = meta['City']

    system = {'surface_tilt': surface_tilt,
              'surface_azimuth': surface_azimuth,
              'albedo': albedo,
              'series_modules': series_modules,
              'parallel_modules': parallel_modules,
              'latitude': meta['latitude'],
              'longitude': meta['longitude'],
              'tz': meta['TZ'],
              'name': name,
              'altitude': meta['altitude']}

    return system

def ashraeiam(b, aoi):
    '''
    Determine the incidence angle modifier using the ASHRAE transmission model.

    ashraeiam calculates the incidence angle modifier as developed in
    [1], and adopted by ASHRAE (American Society of Heating, Refrigeration,
    and Air Conditioning Engineers) [2]. The model has been used by model
    programs such as PVSyst [3].

    Note: For incident angles near 90 degrees, this model has a
    discontinuity which has been addressed in this function.

    Parameters
    ----------
    b : float
        A parameter to adjust the modifier as a function of angle of
        incidence. Typical values are on the order of 0.05 [3].
    aoi : Series
        The angle of incidence between the module normal vector and the
        sun-beam vector in degrees.

    Returns
    -------
    IAM : Series

        The incident angle modifier calculated as 1-b*(sec(aoi)-1) as
        described in [2,3].

        Returns nan for all abs(aoi) >= 90 and for all IAM values
        that would be less than 0.

    References
    ----------

    [1] Souka A.F., Safwat H.H., "Determindation of the optimum orientations
    for the double exposure flat-plate collector and its reflections".
    Solar Energy vol .10, pp 170-174. 1966.

    [2] ASHRAE standard 93-77

    [3] PVsyst Contextual Help.
    http://files.pvsyst.com/help/index.html?iam_loss.htm retrieved on
    September 10, 2012

    See Also
    --------
    irradiance.aoi
    physicaliam
    '''

    IAM = 1 - b*((1/np.cos(np.radians(aoi)) - 1))

    IAM[abs(aoi) >= 90] = np.nan
    IAM[IAM < 0] = np.nan

    return IAM

def physicaliam(K, L, n, aoi):
    '''
    Determine the incidence angle modifier using refractive
    index, glazing thickness, and extinction coefficient

    physicaliam calculates the incidence angle modifier as described in
    De Soto et al. "Improvement and validation of a model for photovoltaic
    array performance", section 3. The calculation is based upon a physical
    model of absorbtion and transmission through a cover. Required
    information includes, incident angle, cover extinction coefficient,
    cover thickness

    Note: The authors of this function believe that eqn. 14 in [1] is
    incorrect. This function uses the following equation in its place:
    theta_r = arcsin(1/n * sin(theta))

    Parameters
    ----------
    K : float
        The glazing extinction coefficient in units of 1/meters. Reference
        [1] indicates that a value of  4 is reasonable for "water white"
        glass. K must be a numeric scalar or vector with all values >=0. If K
        is a vector, it must be the same size as all other input vectors.

    L : float
        The glazing thickness in units of meters. Reference [1] indicates
        that 0.002 meters (2 mm) is reasonable for most glass-covered
        PV panels. L must be a numeric scalar or vector with all values >=0.
        If L is a vector, it must be the same size as all other input vectors.

    n : float
        The effective index of refraction (unitless). Reference [1]
        indicates that a value of 1.526 is acceptable for glass. n must be a
        numeric scalar or vector with all values >=0. If n is a vector, it
        must be the same size as all other input vectors.

    aoi : Series
        The angle of incidence between the module normal vector and the
        sun-beam vector in degrees.

    Returns
    -------
    IAM : float or Series
        The incident angle modifier as specified in eqns. 14-16 of [1].
        IAM is a column vector with the same number of elements as the
        largest input vector.

        Theta must be a numeric scalar or vector.
        For any values of theta where abs(aoi)>90, IAM is set to 0. For any
        values of aoi where -90 < aoi < 0, theta is set to abs(aoi) and
        evaluated.

    References
    ----------
    [1] W. De Soto et al., "Improvement and validation of a model for
    photovoltaic array performance", Solar Energy, vol 80, pp. 78-88,
    2006.

    [2] Duffie, John A. & Beckman, William A.. (2006). Solar Engineering
    of Thermal Processes, third edition. [Books24x7 version] Available
    from http://common.books24x7.com/toc.aspx?bookid=17160.

    See Also
    --------
    getaoi
    ephemeris
    spa
    ashraeiam
    '''
    thetar_deg = tools.asind(1.0 / n*(tools.sind(aoi)))

    tau = ( np.exp(- 1.0 * (K*L / tools.cosd(thetar_deg))) *
            ((1 - 0.5*((((tools.sind(thetar_deg - aoi)) ** 2) /
            ((tools.sind(thetar_deg + aoi)) ** 2) +
            ((tools.tand(thetar_deg - aoi)) ** 2) /
            ((tools.tand(thetar_deg + aoi)) ** 2))))) )

    zeroang = 1e-06

    thetar_deg0 = tools.asind(1.0 / n*(tools.sind(zeroang)))

    tau0 = ( np.exp(- 1.0 * (K*L / tools.cosd(thetar_deg0))) *
             ((1 - 0.5*((((tools.sind(thetar_deg0 - zeroang)) ** 2) /
             ((tools.sind(thetar_deg0 + zeroang)) ** 2) +
             ((tools.tand(thetar_deg0 - zeroang)) ** 2) /
             ((tools.tand(thetar_deg0 + zeroang)) ** 2))))) )

    IAM = tau / tau0

    IAM[abs(aoi) >= 90] = np.nan
    IAM[IAM < 0] = np.nan

    return IAM

def calcparams_desoto(poa_global, temp_cell, alpha_isc, module_parameters,
                      EgRef, dEgdT, M=1, irrad_ref=1000, temp_ref=25):
    '''
    Applies the temperature and irradiance corrections to
    inputs for singlediode.

    Applies the temperature and irradiance corrections to the IL, I0,
    Rs, Rsh, and a parameters at reference conditions (IL_ref, I0_ref,
    etc.) according to the De Soto et. al description given in [1]. The
    results of this correction procedure may be used in a single diode
    model to determine IV curves at irradiance = S, cell temperature =
    Tcell.

    Parameters
    ----------
    poa_global : float or Series
        The irradiance (in W/m^2) absorbed by the module.

    temp_cell : float or Series
        The average cell temperature of cells within a module in C.

    alpha_isc : float
        The short-circuit current temperature coefficient of the
        module in units of 1/C.

    module_parameters : dict
        Parameters describing PV module performance at reference
        conditions according to DeSoto's paper. Parameters may be
        generated or found by lookup. For ease of use,
        retrieve_sam can automatically generate a dict based on the
        most recent SAM CEC module
        database. The module_parameters dict must contain the
        following 5 fields:

            * a_ref - modified diode ideality factor parameter at
              reference conditions (units of eV), a_ref can be calculated
              from the usual diode ideality factor (n),
              number of cells in series (Ns),
              and cell temperature (Tcell) per equation (2) in [1].
            * I_L_ref - Light-generated current (or photocurrent)
              in amperes at reference conditions. This value is referred to
              as Iph in some literature.
            * I_o_ref - diode reverse saturation current in amperes,
              under reference conditions.
            * R_sh_ref - shunt resistance under reference conditions (ohms).
            * R_s - series resistance under reference conditions (ohms).

    EgRef : float
        The energy bandgap at reference temperature (in eV).
        1.121 eV for silicon. EgRef must be >0.

    dEgdT : float
        The temperature dependence of the energy bandgap at SRC (in 1/C).
        May be either a scalar value (e.g. -0.0002677 as in [1]) or a
        DataFrame of dEgdT values corresponding to each input condition (this
        may be useful if dEgdT is a function of temperature).

    M : float or Series (optional, default=1)
        An optional airmass modifier, if omitted, M is given a value of 1,
        which assumes absolute (pressure corrected) airmass = 1.5. In this
        code, M is equal to M/Mref as described in [1] (i.e. Mref is assumed
        to be 1). Source [1] suggests that an appropriate value for M
        as a function absolute airmass (AMa) may be:

        >>> M = np.polyval([-0.000126, 0.002816, -0.024459, 0.086257, 0.918093],
        ...                AMa) # doctest: +SKIP

        M may be a Series.

    irrad_ref : float (optional, default=1000)
        Reference irradiance in W/m^2.

    temp_ref : float (optional, default=25)
        Reference cell temperature in C.

    Returns
    -------
    Tuple of the following results:

    photocurrent : float or Series
        Light-generated current in amperes at irradiance=S and
        cell temperature=Tcell.

    saturation_current : float or Series
        Diode saturation curent in amperes at irradiance
        S and cell temperature Tcell.

    resistance_series : float
        Series resistance in ohms at irradiance S and cell temperature Tcell.

    resistance_shunt : float or Series
        Shunt resistance in ohms at irradiance S and cell temperature Tcell.

    nNsVth : float or Series
        Modified diode ideality factor at irradiance S and cell temperature
        Tcell. Note that in source [1] nNsVth = a (equation 2). nNsVth is the
        product of the usual diode ideality factor (n), the number of
        series-connected cells in the module (Ns), and the thermal voltage
        of a cell in the module (Vth) at a cell temperature of Tcell.

    References
    ----------
    [1] W. De Soto et al., "Improvement and validation of a model for
    photovoltaic array performance", Solar Energy, vol 80, pp. 78-88,
    2006.

    [2] System Advisor Model web page. https://sam.nrel.gov.

    [3] A. Dobos, "An Improved Coefficient Calculator for the California
    Energy Commission 6 Parameter Photovoltaic Module Model", Journal of
    Solar Energy Engineering, vol 134, 2012.

    [4] O. Madelung, "Semiconductors: Data Handbook, 3rd ed." ISBN
    3-540-40488-0

    See Also
    --------
    sapm
    sapm_celltemp
    singlediode
    retrieve_sam

    Notes
    -----
    If the reference parameters in the ModuleParameters struct are read
    from a database or library of parameters (e.g. System Advisor Model),
    it is important to use the same EgRef and dEgdT values that
    were used to generate the reference parameters, regardless of the
    actual bandgap characteristics of the semiconductor. For example, in
    the case of the System Advisor Model library, created as described in
    [3], EgRef and dEgdT for all modules were 1.121 and -0.0002677,
    respectively.

    This table of reference bandgap energies (EgRef), bandgap energy
    temperature dependence (dEgdT), and "typical" airmass response (M) is
    provided purely as reference to those who may generate their own
    reference module parameters (a_ref, IL_ref, I0_ref, etc.) based upon the
    various PV semiconductors. Again, we stress the importance of
    using identical EgRef and dEgdT when generation reference
    parameters and modifying the reference parameters (for irradiance,
    temperature, and airmass) per DeSoto's equations.

     Silicon (Si):
         * EgRef = 1.121
         * dEgdT = -0.0002677

         >>> M = np.polyval([-1.26E-4, 2.816E-3, -0.024459, 0.086257, 0.918093],
         ...                AMa) # doctest: +SKIP

         Source: [1]

     Cadmium Telluride (CdTe):
         * EgRef = 1.475
         * dEgdT = -0.0003

         >>> M = np.polyval([-2.46E-5, 9.607E-4, -0.0134, 0.0716, 0.9196],
         ...                AMa) # doctest: +SKIP

         Source: [4]

     Copper Indium diSelenide (CIS):
         * EgRef = 1.010
         * dEgdT = -0.00011

         >>> M = np.polyval([-3.74E-5, 0.00125, -0.01462, 0.0718, 0.9210],
         ...                AMa) # doctest: +SKIP

         Source: [4]

     Copper Indium Gallium diSelenide (CIGS):
         * EgRef = 1.15
         * dEgdT = ????

         >>> M = np.polyval([-9.07E-5, 0.0022, -0.0202, 0.0652, 0.9417],
         ...                AMa) # doctest: +SKIP

         Source: Wikipedia

     Gallium Arsenide (GaAs):
         * EgRef = 1.424
         * dEgdT = -0.000433
         * M = unknown

         Source: [4]
    '''

    M = np.max(M, 0)
    a_ref = module_parameters['a_ref']
    IL_ref = module_parameters['I_L_ref']
    I0_ref = module_parameters['I_o_ref']
    Rsh_ref = module_parameters['R_sh_ref']
    Rs_ref = module_parameters['R_s']

    k = 8.617332478e-05
    Tref_K = temp_ref + 273.15
    Tcell_K = temp_cell + 273.15

    E_g = EgRef * (1 + dEgdT*(Tcell_K - Tref_K))

    nNsVth = a_ref * (Tcell_K / Tref_K)

    IL = (poa_global/irrad_ref) * M * (IL_ref + alpha_isc * (Tcell_K - Tref_K))
    I0 = ( I0_ref * ((Tcell_K / Tref_K) ** 3) *
           (np.exp(EgRef / (k*(Tref_K)) - (E_g / (k*(Tcell_K))))) )
    Rsh = Rsh_ref * (irrad_ref / poa_global)
    Rs = Rs_ref

    return IL, I0, Rs, Rsh, nNsVth

def retrieve_sam(name=None, samfile=None):
    '''
    Retrieve latest module and inverter info from SAM website.

    This function will retrieve either:

        * CEC module database
        * Sandia Module database
        * CEC Inverter database

    and return it as a pandas dataframe.

    Parameters
    ----------

    name : String
        Name can be one of:

        * 'CECMod' - returns the CEC module database
        * 'CECInverter' - returns the CEC Inverter database
        * 'SandiaInverter' - returns the CEC Inverter database (CEC is only current inverter db available; tag kept for backwards compatibility)
        * 'SandiaMod' - returns the Sandia Module database

    samfile : String
        Absolute path to the location of local versions of the SAM file.
        If file is specified, the latest versions of the SAM database will
        not be downloaded. The selected file must be in .csv format.

        If set to 'select', a dialogue will open allowing the user to navigate
        to the appropriate page.

    Returns
    -------
    A DataFrame containing all the elements of the desired database.
    Each column represents a module or inverter, and a specific dataset
    can be retrieved by the command

    Examples
    --------

    >>> from pvlib import pvsystem
    >>> invdb = pvsystem.retrieve_sam(name='CECInverter')
    >>> inverter = invdb.AE_Solar_Energy__AE6_0__277V__277V__CEC_2012_
    >>> inverter
    Vac           277.000000
    Paco         6000.000000
    Pdco         6165.670000
    Vdco          361.123000
    Pso            36.792300
    C0             -0.000002
    C1             -0.000047
    C2             -0.001861
    C3              0.000721
    Pnt             0.070000
    Vdcmax        600.000000
    Idcmax         32.000000
    Mppt_low      200.000000
    Mppt_high     500.000000
    Name: AE_Solar_Energy__AE6_0__277V__277V__CEC_2012_, dtype: float64
    '''

    if name is not None:
        name = name.lower()

        if name == 'cecmod':
            url = 'https://sam.nrel.gov/sites/sam.nrel.gov/files/sam-library-cec-modules-2015-6-30.csv'
        elif name == 'sandiamod':
            url = 'https://sam.nrel.gov/sites/sam.nrel.gov/files/sam-library-sandia-modules-2015-6-30.csv'
        elif name in ['cecinverter', 'sandiainverter']: # Allowing either, to provide for old code, while aligning with current expectations
            url = 'https://sam.nrel.gov/sites/sam.nrel.gov/files/sam-library-cec-inverters-2015-6-30.csv'
        elif samfile is None:
            raise ValueError('invalid name {}'.format(name))

    if name is None and samfile is None:
        raise ValueError('must supply name or samfile')

    if samfile is None:
        pvl_logger.info('retrieving %s from %s', name, url)
        response = urlopen(url)
        csvdata = io.StringIO(response.read().decode(errors='ignore'))
    elif samfile == 'select':
        import Tkinter
        from tkFileDialog import askopenfilename
        Tkinter.Tk().withdraw()
        csvdata = askopenfilename()
    else:
        csvdata = samfile

    return _parse_raw_sam_df(csvdata)

def _parse_raw_sam_df(csvdata):
    df = pd.read_csv(csvdata, index_col=0, skiprows=[1,2])
    colnames = df.columns.values.tolist()
    parsedcolnames = []
    for cn in colnames:
        parsedcolnames.append(cn.replace(' ', '_'))

    df.columns = parsedcolnames

    parsedindex = []
    for index in df.index:
        parsedindex.append(index.replace(' ', '_').replace('-', '_')
                                .replace('.', '_').replace('(', '_')
                                .replace(')', '_').replace('[', '_')
                                .replace(']', '_').replace(':', '_')
                                .replace('+', '_').replace('/', '_')
                                .replace('"', '_').replace(',', '_'))

    df.index = parsedindex
    df = df.transpose()

    return df

def sapm(module, poa_direct, poa_diffuse, temp_cell, airmass_absolute, aoi):
    '''
    The Sandia PV Array Performance Model (SAPM) generates 5 points on a PV
    module's I-V curve (Voc, Isc, Ix, Ixx, Vmp/Imp) according to
    SAND2004-3535. Assumes a reference cell temperature of 25 C.

    Parameters
    ----------
    module : Series or dict
        A DataFrame defining the SAPM performance parameters.

    poa_direct : Series
        The direct irradiance incident upon the module (W/m^2).

    poa_diffuse : Series
        The diffuse irradiance incident on module.

    temp_cell : Series
        The cell temperature (degrees C).

    airmass_absolute : Series
        Absolute airmass.

    aoi : Series
        Angle of incidence (degrees).

    Returns
    -------
    A DataFrame with the columns:

        * i_sc : Short-circuit current (A)
        * I_mp : Current at the maximum-power point (A)
        * v_oc : Open-circuit voltage (V)
        * v_mp : Voltage at maximum-power point (V)
        * p_mp : Power at maximum-power point (W)
        * i_x : Current at module V = 0.5Voc, defines 4th point on I-V
          curve for modeling curve shape
        * i_xx : Current at module V = 0.5(Voc+Vmp), defines 5th point on
          I-V curve for modeling curve shape
        * effective_irradiance : Effective irradiance

    Notes
    -----
    The coefficients from SAPM which are required in ``module`` are:

    ========   ===============================================================
    Key        Description
    ========   ===============================================================
    A0-A4      The airmass coefficients used in calculating
               effective irradiance
    B0-B5      The angle of incidence coefficients used in calculating
               effective irradiance
    C0-C7      The empirically determined coefficients relating
               Imp, Vmp, Ix, and Ixx to effective irradiance
    Isco       Short circuit current at reference condition (amps)
    Impo       Maximum power current at reference condition (amps)
    Aisc       Short circuit current temperature coefficient at
               reference condition (1/C)
    Aimp       Maximum power current temperature coefficient at
               reference condition (1/C)
    Bvoco      Open circuit voltage temperature coefficient at
               reference condition (V/C)
    Mbvoc      Coefficient providing the irradiance dependence for the BetaVoc
               temperature coefficient at reference irradiance (V/C)
    Bvmpo      Maximum power voltage temperature coefficient at
               reference condition
    Mbvmp      Coefficient providing the irradiance dependence for the
               BetaVmp temperature coefficient at reference irradiance (V/C)
    N          Empirically determined "diode factor" (dimensionless)
    Cells_in_Series    Number of cells in series in a module's cell string(s)
    IXO        Ix at reference conditions
    IXXO       Ixx at reference conditions
    FD         Fraction of diffuse irradiance used by module
    ========   ===============================================================

    References
    ----------
    [1] King, D. et al, 2004, "Sandia Photovoltaic Array Performance Model",
    SAND Report 3535, Sandia National Laboratories, Albuquerque, NM.

    See Also
    --------
    retrieve_sam
    sapm_celltemp
    '''

    T0 = 25
    q = 1.60218e-19 # Elementary charge in units of coulombs
    kb = 1.38066e-23 # Boltzmann's constant in units of J/K
    E0 = 1000

    am_coeff = [module['A4'], module['A3'], module['A2'], module['A1'],
                module['A0']]
    aoi_coeff = [module['B5'], module['B4'], module['B3'], module['B2'],
                 module['B1'], module['B0']]

    F1 = np.polyval(am_coeff, airmass_absolute)
    F2 = np.polyval(aoi_coeff, aoi)

    # Ee is the "effective irradiance"
    Ee = F1 * ( (poa_direct*F2 + module['FD']*poa_diffuse) / E0 )
    Ee.fillna(0, inplace=True)
    Ee = Ee.clip_lower(0)

    Bvmpo = module['Bvmpo'] + module['Mbvmp']*(1 - Ee)
    Bvoco = module['Bvoco'] + module['Mbvoc']*(1 - Ee)
    delta = module['N'] * kb * (temp_cell + 273.15) / q

    dfout = pd.DataFrame(index=Ee.index)

    dfout['i_sc'] = (
        module['Isco'] * Ee * (1 + module['Aisc']*(temp_cell - T0)) )

    dfout['i_mp'] = ( module['Impo'] *
        (module['C0']*Ee + module['C1']*(Ee**2)) *
        (1 + module['Aimp']*(temp_cell - T0)) )

    dfout['v_oc'] = (( module['Voco'] +
        module['Cells_in_Series']*delta*np.log(Ee) + Bvoco*(temp_cell - T0) )
        .clip_lower(0))

    dfout['v_mp'] = ( module['Vmpo'] +
        module['C2']*module['Cells_in_Series']*delta*np.log(Ee) +
        module['C3']*module['Cells_in_Series']*((delta*np.log(Ee)) ** 2) +
        Bvmpo*(temp_cell - T0) ).clip_lower(0)

    dfout['p_mp'] = dfout['i_mp'] * dfout['v_mp']

    dfout['i_x'] = ( module['IXO'] *
        (module['C4']*Ee + module['C5']*(Ee**2)) *
        (1 + module['Aisc']*(temp_cell - T0)) )

    # the Ixx calculation in King 2004 has a typo (mixes up Aisc and Aimp)
    dfout['i_xx'] = ( module['IXXO'] *
        (module['C6']*Ee + module['C7']*(Ee**2)) *
        (1 + module['Aisc']*(temp_cell - T0)) )

    dfout['effective_irradiance'] = Ee

    return dfout

def sapm_celltemp(irrad, wind, temp, model='open_rack_cell_glassback'):
    '''
    Estimate cell and module temperatures per the Sandia PV Array
    Performance Model (SAPM, SAND2004-3535), from the incident
    irradiance, wind speed, ambient temperature, and SAPM module
    parameters.

    Parameters
    ----------
    irrad : float or Series
        Total incident irradiance in W/m^2.

    wind : float or Series
        Wind speed in m/s at a height of 10 meters.

    temp : float or Series
        Ambient dry bulb temperature in degrees C.

    model : string or list
        Model to be used.

        If string, can be:

            * 'open_rack_cell_glassback' (default)
            * 'roof_mount_cell_glassback'
            * 'open_rack_cell_polymerback'
            * 'insulated_back_polymerback'
            * 'open_rack_polymer_thinfilm_steel'
            * '22x_concentrator_tracker'

        If list, supply the following parameters in the following order:

            * a : float
                SAPM module parameter for establishing the upper
                limit for module temperature at low wind speeds and
                high solar irradiance.

            * b : float
                SAPM module parameter for establishing the rate at
                which the module temperature drops as wind speed increases
                (see SAPM eqn. 11).

            * deltaT : float
                SAPM module parameter giving the temperature difference
                between the cell and module back surface at the
                reference irradiance, E0.

    Returns
    --------
    DataFrame with columns 'temp_cell' and 'temp_module'.
    Values in degrees C.

    References
    ----------
    [1] King, D. et al, 2004, "Sandia Photovoltaic Array Performance Model",
    SAND Report 3535, Sandia National Laboratories, Albuquerque, NM.

    See Also
    --------
    sapm
    '''

    temp_models = {'open_rack_cell_glassback': [-3.47, -.0594, 3],
                   'roof_mount_cell_glassback': [-2.98, -.0471, 1],
                   'open_rack_cell_polymerback': [-3.56, -.0750, 3],
                   'insulated_back_polymerback': [-2.81, -.0455, 0],
                   'open_rack_polymer_thinfilm_steel': [-3.58, -.113, 3],
                   '22x_concentrator_tracker': [-3.23, -.130, 13]
                  }

    if isinstance(model, str):
        model = temp_models[model.lower()]
    elif isinstance(model, list):
        model = model

    a = model[0]
    b = model[1]
    deltaT = model[2]

    E0 = 1000. # Reference irradiance

    temp_module = pd.Series(irrad*np.exp(a + b*wind) + temp)

    temp_cell = temp_module + (irrad / E0)*(deltaT)

    return pd.DataFrame({'temp_cell': temp_cell, 'temp_module': temp_module})

def singlediode(module, photocurrent, saturation_current,
                resistance_series, resistance_shunt, nNsVth):
    '''
    Solve the single-diode model to obtain a photovoltaic IV curve.

    Singlediode solves the single diode equation [1]

    .. math::

        I = IL - I0*[exp((V+I*Rs)/(nNsVth))-1] - (V + I*Rs)/Rsh

    for ``I`` and ``V`` when given
    ``IL, I0, Rs, Rsh,`` and ``nNsVth (nNsVth = n*Ns*Vth)`` which
    are described later. Returns a DataFrame which contains
    the 5 points on the I-V curve specified in SAND2004-3535 [3].
    If all IL, I0, Rs, Rsh, and nNsVth are scalar, a single curve
    will be returned, if any are Series (of the same length), multiple IV
    curves will be calculated.

    The input parameters can be calculated using calcparams_desoto from
    meteorological data.

    Parameters
    ----------
    module : DataFrame
        A DataFrame defining the SAPM performance parameters.

    photocurrent : float or Series
        Light-generated current (photocurrent) in amperes under desired IV
        curve conditions. Often abbreviated ``I_L``.

    saturation_current : float or Series
        Diode saturation current in amperes under desired IV curve
        conditions. Often abbreviated ``I_0``.

    resistance_series : float or Series
        Series resistance in ohms under desired IV curve conditions.
        Often abbreviated ``Rs``.

    resistance_shunt : float or Series
        Shunt resistance in ohms under desired IV curve conditions.
        Often abbreviated ``Rsh``.

    nNsVth : float or Series
        The product of three components. 1) The usual diode ideal
        factor (n), 2) the number of cells in series (Ns), and 3) the cell
        thermal voltage under the desired IV curve conditions (Vth).
        The thermal voltage of the cell (in volts) may be calculated as
        ``k*temp_cell/q``, where k is Boltzmann's constant (J/K),
        temp_cell is the temperature of the p-n junction in Kelvin,
        and q is the charge of an electron (coulombs).

    Returns
    -------
    If ``photocurrent`` is a Series, a DataFrame with the following columns.
    All columns have the same number of rows as the largest input DataFrame.

    If ``photocurrent`` is a scalar, a dict with the following keys.

    * i_sc -  short circuit current in amperes.
    * v_oc -  open circuit voltage in volts.
    * i_mp -  current at maximum power point in amperes.
    * v_mp -  voltage at maximum power point in volts.
    * p_mp -  power at maximum power point in watts.
    * i_x -  current, in amperes, at ``v = 0.5*v_oc``.
    * i_xx -  current, in amperes, at ``V = 0.5*(v_oc+v_mp)``.

    Notes
    -----
    The solution employed to solve the implicit diode equation utilizes
    the Lambert W function to obtain an explicit function of V=f(i) and
    I=f(V) as shown in [2].

    References
    -----------
    [1] S.R. Wenham, M.A. Green, M.E. Watt, "Applied Photovoltaics"
    ISBN 0 86758 909 4

    [2] A. Jain, A. Kapoor, "Exact analytical solutions of the parameters of
    real solar cells using Lambert W-function", Solar Energy Materials
    and Solar Cells, 81 (2004) 269-277.

    [3] D. King et al, "Sandia Photovoltaic Array Performance Model",
    SAND2004-3535, Sandia National Laboratories, Albuquerque, NM

    See also
    --------
    sapm
    calcparams_desoto
    '''
    pvl_logger.debug('pvsystem.singlediode')

    # Find short circuit current using Lambert W
    i_sc = i_from_v(resistance_shunt, resistance_series, nNsVth, 0.01,
                    saturation_current, photocurrent)

    params = {'r_sh': resistance_shunt,
              'r_s': resistance_series,
              'nNsVth': nNsVth,
              'i_0': saturation_current,
              'i_l': photocurrent}

    __, v_oc = _golden_sect_DataFrame(params, 0, module['V_oc_ref']*1.6,
                                      _v_oc_optfcn)

    p_mp, v_mp = _golden_sect_DataFrame(params, 0, module['V_oc_ref']*1.14,
                                        _pwr_optfcn)

    # Invert the Power-Current curve. Find the current where the inverted power
    # is minimized. This is i_mp. Start the optimization at v_oc/2
    i_mp = i_from_v(resistance_shunt, resistance_series, nNsVth, v_mp,
                    saturation_current, photocurrent)

    # Find Ix and Ixx using Lambert W
    i_x = i_from_v(resistance_shunt, resistance_series, nNsVth,
                    0.5*v_oc, saturation_current, photocurrent)

    i_xx = i_from_v(resistance_shunt, resistance_series, nNsVth,
                    0.5*(v_oc+v_mp), saturation_current, photocurrent)

    # @wholmgren: need to move this stuff to a different function
#     If the user says they want a curve of with number of points equal to
#     NumPoints (must be >=2), then create a voltage array where voltage is
#     zero in the first column, and Voc in the last column. Number of columns
#     must equal NumPoints. Each row represents the voltage for one IV curve.
#     Then create a current array where current is Isc in the first column, and
#     zero in the last column, and each row represents the current in one IV
#     curve. Thus the nth (V,I) point of curve m would be found as follows:
#     (Result.V(m,n),Result.I(m,n)).
#     if NumPoints >= 2
#        s = ones(1,NumPoints); # shaping DataFrame to shape the column DataFrame parameters into 2-D matrices
#        Result.V = (Voc)*(0:1/(NumPoints-1):1);
#        Result.I = I_from_V(Rsh*s, Rs*s, nNsVth*s, Result.V, I0*s, IL*s);
#     end

    dfout = {}
    dfout['i_sc'] = i_sc
    dfout['i_mp'] = i_mp
    dfout['v_oc'] = v_oc
    dfout['v_mp'] = v_mp
    dfout['p_mp'] = p_mp
    dfout['i_x'] = i_x
    dfout['i_xx'] = i_xx

    try:
        dfout = pd.DataFrame(dfout, index=photocurrent.index)
    except AttributeError:
        pass

    return dfout

# Created April,2014
# Author: Rob Andrews, Calama Consulting

def _golden_sect_DataFrame(params, VL, VH, func):
    '''
    Vectorized golden section search for finding MPPT
    from a dataframe timeseries.

    Parameters
    ----------
    params : dict
        Dictionary containing scalars or arrays
        of inputs to the function to be optimized.
        Each row should represent an independent optimization.

    VL: float
        Lower bound of the optimization

    VH: float
        Upper bound of the optimization

    func: function
        Function to be optimized must be in the form f(array-like, x)

    Returns
    -------
    func(df,'V1') : DataFrame
        function evaluated at the optimal point

    df['V1']: Dataframe
        Dataframe of optimal points

    Notes
    -----
    This funtion will find the MAXIMUM of a function
    '''

    df = params
    df['VH'] = VH
    df['VL'] = VL

    err = df['VH'] - df['VL']
    errflag = True
    iterations = 0

    while errflag:

        phi = (np.sqrt(5)-1)/2*(df['VH']-df['VL'])
        df['V1'] = df['VL'] + phi
        df['V2'] = df['VH'] - phi

        df['f1'] = func(df, 'V1')
        df['f2'] = func(df, 'V2')
        df['SW_Flag'] = df['f1'] > df['f2']

        df['VL'] = df['V2']*df['SW_Flag'] + df['VL']*(~df['SW_Flag'])
        df['VH'] = df['V1']*~df['SW_Flag'] + df['VH']*(df['SW_Flag'])

        err = df['V1'] - df['V2']
        try:
            errflag = (abs(err)>.01).all()
        except ValueError:
            errflag = (abs(err)>.01)

        iterations += 1

        if iterations > 50:
            raise Exception("EXCEPTION:iterations exeeded maximum (50)")

    return func(df, 'V1'), df['V1']

def _pwr_optfcn(df, loc):
    '''
    Function to find power from ``i_from_v``.
    '''

    I = i_from_v(df['r_sh'], df['r_s'], df['nNsVth'],
                 df[loc], df['i_0'], df['i_l'])
    return I*df[loc]

def _v_oc_optfcn(df, loc):
    '''
    Function to find the open circuit voltage from ``i_from_v``.
    '''
    I = -abs(i_from_v(df['r_sh'], df['r_s'], df['nNsVth'],
                      df[loc], df['i_0'], df['i_l']))
    return I

def i_from_v(resistance_shunt, resistance_series, nNsVth, voltage,
             saturation_current, photocurrent):
    '''
    Calculates current from voltage per Eq 2 Jain and Kapoor 2004 [1].

    Parameters
    ----------
    resistance_series : float or Series
        Series resistance in ohms under desired IV curve conditions.
        Often abbreviated ``Rs``.

    resistance_shunt : float or Series
        Shunt resistance in ohms under desired IV curve conditions.
        Often abbreviated ``Rsh``.

    saturation_current : float or Series
        Diode saturation current in amperes under desired IV curve
        conditions. Often abbreviated ``I_0``.

    nNsVth : float or Series
        The product of three components. 1) The usual diode ideal
        factor (n), 2) the number of cells in series (Ns), and 3) the cell
        thermal voltage under the desired IV curve conditions (Vth).
        The thermal voltage of the cell (in volts) may be calculated as
        ``k*temp_cell/q``, where k is Boltzmann's constant (J/K),
        temp_cell is the temperature of the p-n junction in Kelvin,
        and q is the charge of an electron (coulombs).

    photocurrent : float or Series
        Light-generated current (photocurrent) in amperes under desired IV
        curve conditions. Often abbreviated ``I_L``.

    Returns
    -------
    current : np.array

    References
    ----------
    [1] A. Jain, A. Kapoor, "Exact analytical solutions of the parameters of
    real solar cells using Lambert W-function", Solar Energy Materials
    and Solar Cells, 81 (2004) 269-277.
    '''
    try:
        from scipy.special import lambertw
    except ImportError:
        raise ImportError('This function requires scipy')

    Rsh = resistance_shunt
    Rs = resistance_series
    I0 = saturation_current
    IL = photocurrent
    V = voltage

    argW = (Rs*I0*Rsh *
            np.exp( Rsh*(Rs*(IL+I0)+V) / (nNsVth*(Rs+Rsh)) ) /
            (nNsVth*(Rs + Rsh)) )
    lambertwterm = lambertw(argW)

    # Eqn. 4 in Jain and Kapoor, 2004
    I = -V/(Rs + Rsh) - (nNsVth/Rs)*lambertwterm + Rsh*(IL + I0)/(Rs + Rsh)

    return I.real

def snlinverter(inverter, v_dc, p_dc):
    '''
    Converts DC power and voltage to AC power using
    Sandia's Grid-Connected PV Inverter model.

    Determines the AC power output of an inverter given the DC voltage, DC
    power, and appropriate Sandia Grid-Connected Photovoltaic Inverter
    Model parameters. The output, ac_power, is clipped at the maximum power
    output, and gives a negative power during low-input power conditions,
    but does NOT account for maximum power point tracking voltage windows
    nor maximum current or voltage limits on the inverter.

    Parameters
    ----------
    inverter : DataFrame
        A DataFrame defining the inverter to be used, giving the
        inverter performance parameters according to the Sandia
        Grid-Connected Photovoltaic Inverter Model (SAND 2007-5036) [1].
        A set of inverter performance parameters are provided with pvlib,
        or may be generated from a System Advisor Model (SAM) [2]
        library using retrievesam.

        Required DataFrame columns are:

        ======   ============================================================
        Column   Description
        ======   ============================================================
        Pac0     AC-power output from inverter based on input power
                 and voltage (W)
        Pdc0     DC-power input to inverter, typically assumed to be equal
                 to the PV array maximum power (W)
        Vdc0     DC-voltage level at which the AC-power rating is achieved
                 at the reference operating condition (V)
        Ps0      DC-power required to start the inversion process, or
                 self-consumption by inverter, strongly influences inverter
                 efficiency at low power levels (W)
        C0       Parameter defining the curvature (parabolic) of the
                 relationship between ac-power and dc-power at the reference
                 operating condition, default value of zero gives a
                 linear relationship (1/W)
        C1       Empirical coefficient allowing Pdco to vary linearly
                 with dc-voltage input, default value is zero (1/V)
        C2       Empirical coefficient allowing Pso to vary linearly with
                 dc-voltage input, default value is zero (1/V)
        C3       Empirical coefficient allowing Co to vary linearly with
                 dc-voltage input, default value is zero (1/V)
        Pnt      AC-power consumed by inverter at night (night tare) to
                 maintain circuitry required to sense PV array voltage (W)
        ======   ============================================================

    v_dc : float or Series
        DC voltages, in volts, which are provided as input to the inverter.
        Vdc must be >= 0.
    p_dc : float or Series
        A scalar or DataFrame of DC powers, in watts, which are provided
        as input to the inverter. Pdc must be >= 0.

    Returns
    -------
    ac_power : float or Series
        Modeled AC power output given the input
        DC voltage, Vdc, and input DC power, Pdc. When ac_power would be
        greater than Pac0, it is set to Pac0 to represent inverter
        "clipping". When ac_power would be less than Ps0 (startup power
        required), then ac_power is set to -1*abs(Pnt) to represent nightly
        power losses. ac_power is not adjusted for maximum power point
        tracking (MPPT) voltage windows or maximum current limits of the
        inverter.

    References
    ----------
    [1] SAND2007-5036, "Performance Model for Grid-Connected Photovoltaic
    Inverters by D. King, S. Gonzalez, G. Galbraith, W. Boyson

    [2] System Advisor Model web page. https://sam.nrel.gov.

    See also
    --------
    sapm
    singlediode
    '''

    Paco = inverter['Paco']
    Pdco = inverter['Pdco']
    Vdco = inverter['Vdco']
    Pso = inverter['Pso']
    C0 = inverter['C0']
    C1 = inverter['C1']
    C2 = inverter['C2']
    C3 = inverter['C3']
    Pnt = inverter['Pnt']

    A = Pdco * (1 + C1*(v_dc - Vdco))
    B = Pso * (1 + C2*(v_dc - Vdco))
    C = C0 * (1 + C3*(v_dc - Vdco))

    # ensures that function works with scalar or Series input
    p_dc = pd.Series(p_dc)

    ac_power = ( Paco/(A-B) - C*(A-B) ) * (p_dc-B) + C*((p_dc-B)**2)
    ac_power[ac_power > Paco] = Paco
    ac_power[ac_power < Pso] = - 1.0 * abs(Pnt)

    if len(ac_power) == 1:
        ac_power = ac_power.ix[0]

    return ac_power

max_stars_repo_name: dacoex/pvlib-python

max_issues_repo_name: dacoex/pvlib-python

max_forks_repo_name: dacoex/pvlib-python

reason: import numpy,from scipy


text:
import numpy
from tabulate import tabulate
import platform
import sys
import os

'''
weeks: indices [0, 30) --> week no. [1, 30]
days: indices [0, 5) --> {Monday, Tuesday, Wednesday, Thursday, Friday}
times: indices [0, 9) --> {9 am, 10 am, 11 am, 12 pm, 1 pm, 2 pm, 3 pm, 4 pm, 5 pm}
'''
class Class:
	name = None
	lect = None
	room = None
	def __init__(self, name, lect, room):
		self.name = name
		self.lect = lect
		self.room = room

	def getProp(self):
		return (self.name, self.lect, self.room)

class Manager:
	FREE = Class("", "n/a", "n/a")
	classID = None
	classes = None
	TABLE = None
	DAY = {"Mon": 0, "Tue": 1, "Wed": 2, "Thur": 3, "Fri": 4}
	PERIOD = {"9 am": 0, "10 am": 1, "11 am": 2, "12 pm": 3, "1 pm": 4, "2 pm": 5, "3 pm": 6, "4 pm": 7, "5 pm": 8}
	def clearAll(self):
		self.classID = {"FREE": 0}
		self.classes = [self.FREE]
		self.TABLE = numpy.zeros((30, 5, 9), dtype = int)

	def addClass(self, name, lect, room):
		c = Class(name, lect, room)
		self.classes.append(c)
		self.classID[name] = len(self.classes) - 1

	def delClass(self, name):
		self.classes[self.classID[name]].name = ""
		self.classID[name] = 0

	def listClasses(self):
		print("Classes: ")
		for co in self.classes[1:]:
			c = co.getProp()
			if(c[0] != ""): print("{}; {}; {}".format(c[0], c[1], c[2]))

	def setClass(self, name, week, day, period):
		if(name in self.classID):
			if(type(week) !=  int):
				for w in self.wr(week[0], week[1]):
					if(self.TABLE[w - 1, self.DAY[day], self.PERIOD[period]] != 0): print("Overwriting something.")
					self.TABLE[w - 1, self.DAY[day], self.PERIOD[period]] = self.classID[name]
			else:
				self.TABLE[week - 1, self.DAY[day], self.PERIOD[period]] = self.classID[name]
		else: print("Class name not recognised.")

	def showTable(self, week, showList = False):
		WEEK = numpy.transpose(self.TABLE[week - 1])
		OUT = [["9 am"], ["10 am"], ["11 am"], ["12 pm"], ["1 pm"], ["2 pm"], ["3 pm"], ["4 pm"], ["5 pm"]]
		for i in range(len(OUT)):
			for p in WEEK[i]:
				OUT[i].append(self.classes[p].name)
		OUT = numpy.array(OUT)
		form = tabulate(OUT, headers = ["Time", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"], tablefmt = "grid")
		print(form)
		if(showList): self.listClasses()

	def wr(self, a, b):
		l = range(a, b+1)
		return l

	def save(self, name):
		npclasses = []
		for c in self.classes[1:]:
			npclasses.append(c.getProp())
		npclasses = numpy.array(npclasses)
		numpy.save("{}_table.npy".format(name), self.TABLE)
		numpy.save("{}_classes.npy".format(name), npclasses)

	def load(self, name):
		npclasses = numpy.load("{}_classes.npy".format(name))
		for tup in npclasses:
			self.addClass(tup[0], tup[1], tup[2])
		self.TABLE = numpy.load("{}_table.npy".format(name))

manager = Manager()

manager.clearAll()

print("Welcome to the Offical Matthew Smith Timetable Manager. Current instructions are in the README.md file on the GitHub repository.")

while(True):
	user = input(">> ")
	if(user == "exit()"): exit()
	elif(user == "cls"):
		if(platform.system() == "Windows"): os.system("cls")
		elif(platform.system() == "Linux"): os.system("clear")
		elif(platform.system() == "Darwin"): os.sytem("clear")
		else:
			print("Cannot clear screen. System is unknown.")
	else:
		try:
			exec("manager." + user)
		except:
			print("Failed. Check command and arguments.")

max_stars_repo_name: MatthewSmithPhysics/Timetable-Manager

max_issues_repo_name: MatthewSmithPhysics/Timetable-Manager

max_forks_repo_name: MatthewSmithPhysics/Timetable-Manager


text:
"""
Tests for IntensityTable.synthetic_intensities method.
"""

import numpy as np

from starfish.core.codebook.test.factories import codebook_array_factory
from starfish.core.types import Axes, Features
from ..intensity_table import IntensityTable

def test_synthetic_intensity_generation():
    """
    Create a 2-spot IntensityTable of pixel size (z=3, y=4, x=5) from a codebook with 3 channels
    and 2 rounds.

    Verify that the constructed Synthetic IntensityTable conforms to those dimensions, and given
    a known random seed, that the output spots decode to match a target in the input Codebook
    """
    # set seed to check that codebook is matched. This seed generates 2 instances of GENE_B
    np.random.seed(2)
    codebook = codebook_array_factory()
    num_z, height, width = 3, 4, 5
    intensities = IntensityTable.synthetic_intensities(
        codebook,
        num_z=num_z,
        height=height,
        width=width,
        n_spots=2,
    )

    # sizes should match codebook
    assert intensities.sizes[Axes.ROUND] == 2
    assert intensities.sizes[Axes.CH] == 3
    assert intensities.sizes[Features.AXIS] == 2

    # attributes should be bounded by the specified size
    assert np.all(intensities[Axes.ZPLANE.value] <= num_z)
    assert np.all(intensities[Axes.Y.value] <= height)
    assert np.all(intensities[Axes.X.value] <= width)

    # both codes should match GENE_B
    assert np.array_equal(
        np.where(intensities.values),
        [[0, 0, 1, 1],  # two each in feature 0 & 1
         [1, 2, 1, 2],  # one each in channel 1 & 2
         [1, 0, 1, 0]],  # channel 1 matches round 1, channel 2 matches round zero
    )


text:
"""
MIT License

Copyright (c) 2021 Ivan Sosnovik, Artem Moskalev
Copyright (c) 2018 Microsoft (Houwen Peng, Zhipeng Zhang)
"""

import os
import cv2
import argparse
import numpy as np
import yaml

import lib.models.models as models
from lib.tracker import SESiamFCTracker
from lib.utils import load_pretrain, cxy_wh_2_rect, get_axis_aligned_bbox, load_dataset, poly_iou, convert_color_RGB

def track(tracker, video, dataset_name):
    start_frame, toc = 0, 0

    tracker_path = os.path.join('result', dataset_name, 'SESiamFCTracker')
    if not os.path.exists(tracker_path):
        os.makedirs(tracker_path)

    if 'VOT' in dataset_name:
        baseline_path = os.path.join(tracker_path, 'baseline')
        video_path = os.path.join(baseline_path, video['name'])
        if not os.path.exists(video_path):
            os.makedirs(video_path)
        result_path = os.path.join(video_path, video['name'] + '_001.txt')
    else:
        result_path = os.path.join(tracker_path, '{:s}.txt'.format(video['name']))

    if os.path.exists(result_path):
        return

    regions = []
    image_files, gt = video['image_files'], video['gt']

    for f, image_file in enumerate(image_files):
        im = cv2.imread(image_file)
        im = convert_color_RGB(im)

        tic = cv2.getTickCount()

        if f == start_frame:  # init
            cx, cy, w, h = get_axis_aligned_bbox(gt[f])
            target_pos = np.array([cx, cy])
            target_sz = np.array([w, h])
            tracker.init(im, target_pos, target_sz)  # init tracker
            regions.append(1 if 'VOT' in dataset_name else gt[f])

        elif f > start_frame:  # tracking
            target_pos, target_sz = tracker.track(im)
            location = cxy_wh_2_rect(target_pos, target_sz)
            b_overlap = poly_iou(gt[f], location) if 'VOT' in dataset_name else 1
            if b_overlap > 0:
                regions.append(location)
            else:
                regions.append(2)
                start_frame = f + 5
        else:
            regions.append(0)

        toc += cv2.getTickCount() - tic

    with open(result_path, "w") as fin:
        if 'VOT' in dataset_name:
            for x in regions:
                if isinstance(x, int):
                    fin.write("{:d}\n".format(x))
                else:
                    p_bbox = x.copy()
                    fin.write(','.join([str(i) for i in p_bbox]) + '\n')
        else:
            for x in regions:
                p_bbox = x.copy()
                fin.write(
                    ','.join([str(i + 1) if idx == 0 or idx == 1 else str(i) for idx, i in enumerate(p_bbox)]) + '\n')

    toc /= cv2.getTickFrequency()
    print('Video: {:12s} Time: {:2.1f}s Speed: {:3.1f}fps'.format(video['name'], toc, f / toc))

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--checkpoint', required=True, type=str, help='pretrained model')
    parser.add_argument('--dataset', default='VOT2017', help='dataset test')
    parser.add_argument('--dataset_root', default=None)
    parser.add_argument('--cfg', required=True)
    args = parser.parse_args()

    with open(args.cfg) as f:
        tracker_config = yaml.load(f.read())

    # prepare model
    net = models.__dict__[tracker_config['MODEL']](padding_mode='constant')
    net = load_pretrain(net, args.checkpoint)
    net = net.eval().cuda()

    # prepare tracker
    tracker_config = tracker_config['TRACKER'][args.dataset]
    tracker = SESiamFCTracker(net, **tracker_config)
    print('Tracker')
    print(tracker)

    # prepare video
    dataset = load_dataset(args.dataset, root=args.dataset_root)
    video_keys = list(dataset.keys()).copy()

    # tracking all videos in benchmark
    for video in video_keys:
        track(tracker, dataset[video], dataset_name=args.dataset)

if __name__ == '__main__':
    main()

max_stars_repo_name: ISosnovik/SiamSE

max_issues_repo_name: ISosnovik/SiamSE

max_forks_repo_name: ISosnovik/SiamSE