text string |
|---|
#!/usr/bin/env python3
from os import mkdir, listdir
from os.path import isdir, isfile
#import time
import datetime
import numpy as np
from matplotlib import pyplot as plt
from scipy.optimize import brute, least_squares
import h5py
from LoLIM.utilities import processed_data_dir, v_air, antName_is_even, BoundingBox... |
<reponame>nancypareta/Stress-detection-Techniques-and-Chat-Bot-Depression-Therapy
from scipy.spatial import distance as dist
from imutils.video import VideoStream
from imutils import face_utils
import numpy as np
import imutils
import time
import dlib
import cv2
import matplotlib.pyplot as plt
from keras.prepr... |
import pandas as pd
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
import seaborn as sns
import os
def load_systems(file_name, exclude_reps=0, delim=','):
"""
Reads scenario data from a .csv file (assumes comma delimited).
Assumes that each column represents a scenario.
Returns a... |
<reponame>dfm/starry_process
from starry_process.sp import StarryProcess
from starry_process.wigner import R
from starry_process.defaults import defaults
from starry_process.size import Spot
import numpy as np
from tqdm import tqdm
from scipy.stats import beta as Beta
from scipy.stats import lognorm as LogNormal
import... |
import os
import numpy as np
from . import reporting
from . import printer
from .dims import *
import pandas as pd
def create_section(title, desc, subsects, figures_list):
assert isinstance(title, str)
assert isinstance(desc, str)
assert isinstance(figures_list, list)
section = reporting.Section(titl... |
<filename>src/pasio/cached_log.py
import numpy as np
import scipy.special
# Works only with non-negative integer values
class LogComputer:
def __init__(self, shift = 0, cache_size = 1048576):
self.cache_size = cache_size
self.shift = shift
self.precomputed = np.log(np.arange(self.cache_size... |
<gh_stars>1-10
import csv
import sklearn as sk
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from pprint import pprint
from sklearn.cross_validation import cross_val_score, KFold
from scipy.stats import sem
from sklearn.naive_bayes import MultinomialNB
from sklearn.svm import LinearSVC
from sklea... |
import os
import subprocess
import sys
import time
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import streamlit as st
from PIL import Image
from scipy.stats import kurtosis, probplot, shapiro, skew
from generate_features import generate_feature... |
# -*- coding:
# Project: Linear Regression
import pandas as pd
import numpy as np
import math
import pylab
import statsmodels.api as sm
from statsmodels.formula.api import ols
from sklearn.model_selection import train_test_split
import scipy.stats as spstats
import seaborn as sns
import matplotlib.pyplot as pl... |
import os
from os import path
import matplotlib.pyplot as plt
import numpy as np
# import torch.fft as fft
from scipy.fftpack import fft
import pandas as pd
from skeleton_tools.openpose_layouts.body import BODY_25_LAYOUT
from skeleton_tools.utils.tools import read_json
def plot_fft(data_numpy, title, filename):
... |
<filename>tests/test_core.py
import itertools
from pytest import fixture, raises, mark
import scipy.sparse as sp
import numpy as np
from numpy.testing import assert_allclose, assert_almost_equal
import quimb as qu
stypes = ("csr", "csc", "bsr", "coo")
@fixture
def od1():
return qu.rand_matrix(3)
@fixture
def... |
import pandas as pd
import numpy as np
import re
import datetime as dt
import math
import geopandas as gpd
import h3 # h3 bins from uber
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.preprocessing import StandardScaler, minmax_scale, MinMaxScaler
from sklearn.cluster import KMeans
from sklearn.clus... |
<filename>pypfopt/objective_functions.py<gh_stars>1-10
"""
The ``objective_functions`` module provides optimisation objectives, including the actual
objective functions called by the ``EfficientFrontier`` object's optimisation methods.
These methods are primarily designed for internal use during optimisation (via
scipy... |
# -*- coding: utf-8 -*-
# import statements
from scipy.constants import milli, hour, minute, femto
from matplotlib import pyplot
from pprint import pprint
from datetime import date
from sigfig import round
from numpy import log10, nan
from math import inf
import cobra
import pandas
import warnings, json, re, os
... |
<gh_stars>0
import numpy as np
import pandas as pd
# import geopandas as gpd
from IPython.display import Image
# from shapely.geometry import Point, Polygon
from math import factorial
import datetime
import time
import scipy
from statsmodels.sandbox.regression.predstd import wls_prediction_std
from sklearn.linear_model... |
<gh_stars>0
#Copyright (c) 2019 ETH Zurich
#Author: <NAME>
#Licensed under the Apache License, Version 2.0 (see LICENSE file, on the main directory)
import pickle
import time
from sklearn.externals import joblib
from sklearn.metrics import confusion_matrix
import numpy as np
import sys, os
import imp
import tensorflow ... |
# -*- coding: utf-8 -*-
"""
Contains functions to find the time-zero and to interpolate the data.
"""
import numpy as np
import skultrafast.dv as dv
import scipy.ndimage as nd
import matplotlib.pyplot as plt
#from skultrafast.fitter import _coh_gaussian
from scipy.linalg import lstsq
from scipy.optimize import least_... |
# -*- coding: UTF-8 -*-
from sympy import pi, sin
from scipy.sparse.linalg import spsolve
from sympde.calculus import dot, div
from sympde.topology import VectorFunctionSpace, ScalarFunctionSpace
from sympde.topology import ProductSpace
from sympde.topology import element_of
from sympde.topology import ... |
from . import kepmsg, kepstat, kepfunc, keparray
import math
import numpy as np
from scipy import optimize, ndimage
from scipy.optimize import fmin_powell, fmin_tnc, fmin, leastsq
from scipy.ndimage import interpolation
from scipy.ndimage.interpolation import shift
def leastsquares(fitfunc, pinit, xdata, ydata, yerr,... |
<filename>kml_analysis_pkg/internal_gaps/__init__.py
import warnings
warnings.filterwarnings("ignore")
from datetime import datetime
import os
import pandas as pd
import numpy as np
import re
import nltk
import sys
#For Text Segmentation
import word2vec
from sklearn.feature_extraction.text import CountVectorizer
#F... |
from scipy import misc, signal
import mrcfile
import numpy as np
from aspire.utils.numeric import xp
from aspire.utils import ensure
class Micrograph:
def __init__(self, filepath, margin=None, shrink_factor=None, square=False, gauss_filter_size=None, gauss_filter_sigma=None):
self.filepath = filepath
... |
# !/usr/bin/env python3
# ------------------------------------------------------------------------
# Copyright (c) 2021 megvii-model. All Rights Reserved.
# ------------------------------------------------------------------------
# Modified from Sparse-RCNN(github: https://github.com/PeizeSun/SparseR-CNN) created by <N... |
import numpy as np
import cv2
import os
from tqdm import tqdm
import matplotlib.pyplot as plt
from scipy import interp
from lbp_module.texture import base_lbp, improved_lbp, hamming_lbp, completed_lbp, extended_lbp
import sklearn
from sklearn.svm import SVC
from sklearn.model_selection import cross_val_score
from sklea... |
# -*- coding: utf-8 -*-
from PySide2 import QtCore, QtWidgets
from hardware import (
ArduinoUno,
KeithleySource,
KeithleyMultimeter,
OceanSpectrometer,
ThorlabMotor,
)
from tests.tests import (
MockArduinoUno,
MockKeithleySource,
MockKeithleyMultimeter,
MockOceanSpectrometer,
M... |
<reponame>gwpark-git/dynamics_of_networks_and_colloids
from numpy import *
from analysis_hist_R_from_data import *
from scipy.linalg import norm
def coord_XYZ_to_SPE(XYZ_arr):
r = norm(XYZ_arr)
theta = arccos(XYZ_arr[2]/r)
phi = arctan2(XYZ_arr[1], XYZ_arr[0])
return asarray([r, theta, phi])
def inde... |
<reponame>shersonb/python-transcode<filename>transcode/filters/video/pullup/__init__.py
#!/usr/bin/python
from .. import zoned
from ...base import CacheResettingProperty
from transcode.util import cached, numpify
import numpy
from fractions import Fraction as QQ
import itertools
from av.video import VideoFrame
from col... |
import matplotlib.pyplot as plt
import scipy
import colorsys
import json
import sys
import os
import copy
plt.figure(1, figsize=(8, 12))
emin = -0.5
emax = 1
with open(sys.argv[1], "r") as fin:
jin = json.load(fin)
energy_scale = 27.21138505
bands = jin["bands"]
x_axis = jin["header"]["x_axis"]
x_ticks = jin["... |
<filename>libs/doubleDQN.py<gh_stars>1-10
# Setting the environment
from unityagents import UnityEnvironment
# please do not modify the line below
env = UnityEnvironment(file_name="Banana_Linux/Banana.x86_64")
# get the default brain
brain_name = env.brain_names[0]
brain = env.brains[brain_name]
# Setting the environm... |
from collections import namedtuple
import numpy as np
from scipy.interpolate import Akima1DInterpolator as Akima
import openmdao.api as om
"""United States standard atmosphere 1976 tables, data
obtained from http://www.digitaldutch.com/atmoscalc/index.htm"""
USatm1976Data = namedtuple('USatm1976Data', ['alt', 'temp... |
<reponame>stinsong4100/chemev
import scipy.integrate, numpy as np
import totradpres
# Calculation of number and mass of stars that go SN Type Ia in a
# given stellar mass range.
EPSSNIA = 1e-7
dFracBinSNIa = 0.05
dGamma_2nd = 2.0
dMBmin = 3.0
dMBmax = 16.0
dMSNIImin = 8.0
# Integrand for secondary mass function: p... |
"""
USED -> IMAGE CLASS
"""
import copy
import os
import time
import warnings
from typing import Union
import logging
import numpy as np
import pandas as pd
from pydicom import FileDataset, Sequence, Dataset
from luna.radiology.mirp.utilities import get_version
# Monolithic classes.....
class ImageClass:
# Clas... |
<reponame>kandrio/emoFeatExtract
import numpy as np
import math
from scipy.stats import iqr
from pyAudioAnalysis import audioFeatureExtraction as afe
from scipy import fft
def signalToFrames(signal, window, step):
"""Divides given signal in frames of length of 'window' using
a 'step'. Returns numpy array of f... |
<filename>deepthought3/datasets/mpi2015/Importer.py
"""
Created on Jan 19, 2015
@author: sstober
"""
import os
import glob
import logging
log = logging.getLogger(__name__)
import numpy as np
from deepthought3.util.fs_util import load, save
from scipy.io import loadmat
def load_eeglab_data(filepath, xlsx_metadat... |
<filename>do_benchmark_fastcluster.py
"""
Copyright (C) 2020, <NAME>, https://www.gagolewski.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation ... |
import csv
import argparse
import numpy as np
import scipy.stats as stats
class data_group:
def __init__(self, group_name, data_array):
self.group_name = group_name
self.data_array = data_array
self.mean = np.mean(np.array(data_array))
self.sd = np.std(np.array(data_a... |
<reponame>jdsika/TUM_HOly<filename>openrave/docs/source/tutorials/openravepy_examples/saving_viewer_image.py
"""Save a 640x480 image from the viewer.
"""
from openravepy import *
import scipy
import time
env = Environment() # create openrave environment
env.SetViewer('qtcoin')
env.Load('data/lab1.env.xml') # load a sim... |
from abc import ABC
from typing import Tuple
import numpy as np
from scipy import signal
class BaseLoader(ABC):
"""Base class which contains the data related to a single day/night of of a
single subject. There is a classmethod for every support file format which
can be used to read in the file and store ... |
import time
import warnings
import numpy as np
from scipy import signal
from tikreg import models, utils as tikutils
from tikreg import models
from tikreg import spatial_priors, temporal_priors
from fusilib.config import DATA_ROOT
def get_peak_info(time, data, sumfunc=np.median):
'''
time : 1D np.array
... |
<reponame>rsln-s/QCommunity<filename>qcommunity/optimization/cobyla.py
# QAOA parameter optimization using COBYLA
from qcommunity.optimization.obj import get_obj_val, get_obj
from scipy.optimize import minimize
import numpy as np
def optimize_obj(obj_val, num_parameters, params=None):
options = {}
try:
... |
<filename>pyiast/isotherms.py
"""
This module contains objects to characterize the pure-component adsorption
isotherms from experimental or simulated data. These will be fed into the
IAST functions in pyiast.py.
"""
from __future__ import absolute_import
from __future__ import print_function
from six.moves import range... |
<gh_stars>100-1000
import functools
import random
import numpy as np
import albumentations as ab
import scipy.ndimage as ndimage
from self_supervised_3d_tasks.preprocessing.utils.crop import crop_3d
from self_supervised_3d_tasks.preprocessing.utils.pad import pad_to_final_size_3d
from self_supervised_3d_tasks.data.pr... |
<filename>goodneighbors/__init__.py<gh_stars>1-10
import h5py, json, sys, math
import pandas as pd
import numpy as np
from sklearn.cluster import KMeans
from goodneighbors.plots import plot_counts_per_radius, plot_kmeans_evaluation, plot_cluster_composition
from sklearn.manifold import TSNE
from scipy.cluster.hierarchy... |
<filename>fullModelForSubmission2.py<gh_stars>0
import pandas as pd
import numpy as np
#import matplotlib
#import warnings
#import sklearn
##import gensim
#import scipy
#import numpy
#import json
#import nltk
#from nltk.stem import PorterStemmer
from nltk.tokenize import sent_tokenize
#import sys
#import csv
#import os... |
<gh_stars>1-10
import numpy as np
import json
import os
import networkx as nx
import matplotlib
matplotlib.use('Qt4Agg')
import matplotlib.pyplot as plt
import scipy as sp
import scipy.stats
from fetch import ml_tournament
DATA_REPO = '/'.join(os.path.dirname(os.path.realpath(__file__)).split('/')[:-1]) + '/data/'
d... |
from math import floor
import os
import numpy as np
import scipy.sparse as sp
import torch
from torch.utils.data import Dataset
class TemporalNetworkDataset(Dataset):
def __init__(self, path, generate_neg_examples=False, mode='train',
duplicate_examples=False, repeat_examples=False,
... |
<filename>PyCOBRA_beam.py
from abc import ABCMeta, abstractmethod
import numpy as np
from scipy.constants import e, m_p
def gaussian_generator(eps_geo, phase_space_tuple=('x', 'xp'), alpha=0, beta=1):
sigma = np.sqrt(eps_geo)
def generate(bunch):
n_macroparticles = bunch.n_macroparticles
x ... |
import os
import numpy as np
from scipy import *
from scipy.sparse import *
from scipy.sparse.linalg import inv
import time
import datetime
def normalize_similarity(similarity_result):
pairs = sorted(similarity_result.iteritems(), key = lambda (k, v): v, reverse = True)
result = dict()
max_similarity = pai... |
<reponame>bertrand-faure/popcorn
# !/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 15 13:46:27 2021.
@author: quenot
"""
from pagailleIO import saveEdf,openImage,openSeq,save3D_Edf
import glob
from numpy.fft import fftshift as fftshift
from numpy.fft import ifftshift as ifftshift
from numpy.fft im... |
import numpy as np
from crowddynamics.core.geometry import geom_to_linear_obstacles
from crowddynamics.simulation.agents import Circular, ThreeCircle, NO_TARGET, \
Agents, AgentGroup
from crowddynamics.simulation.field import Field
from crowddynamics.simulation.logic import Reset, InsideDomain, Integrator, \
... |
<reponame>MistSC/kaldi-pdnn-nctu-mllab<filename>run_timit/svae/VFAE.py<gh_stars>1-10
from __future__ import print_function
from collections import OrderedDict
import os
import sys
import timeit
import scipy.io as sio
import numpy as np
import theano
import theano.tensor as T
import nnet as nn
import criteria as er
i... |
from Crypto.Util import number as crypto
import numpy as np
import time
from sympy import mod_inverse
import random
from math import gcd
import matplotlib.pyplot as plt
from src.RSA_Attack import *
class Client():
def __init__(self):
self.n = None
self.e = None
self.d = None
def encryp... |
import numpy as np
import matplotlib.pyplot as plt
import glob, os
import scipy.constants as sc
import scipy.odr as sdr
def gaussian_ba(b,x):
return b[2]*np.exp(-(x-b[0])**2/2/(b[1]**2))+b[3]+b[4]*x
def gauss_fit_ba(datax,datay,errory,beta0=[0,1,1,0,0]):
mod = sdr.Model(gaussian_ba)
dat = sdr.RealData(dat... |
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import multivariate_normal as mvn
cov = np.array([[1,0.8],[0.8,3]]) # a covariance matrix
mu = np.array([0,2])
r = mvn.rvs(mean=mu,cov=cov,size=10000)
#plt.scatter(r[:,0],r[:,1])
# using numpy only
r1 = np.random.multivariate_normal(mean=mu,cov... |
import numpy as np
import logging
from scipy.stats import truncnorm
def selection(Z):
"""
Characterising selecting the top K Models from vector Z as a linear
combination.
input
Z : "Feature vector" with a normal distribution.
K : Number of selections.
... |
<reponame>Tristan-Anderson/Slifer_Lab
"""
<NAME>
<EMAIL>
Proceed Formally.
"""
from slifercal import sliferCal
import tkinter as tk
import tkinter.scrolledtext as scrolledtext
from tkinter import filedialog
from statistics import mode
from matplotlib import pyplot as plt
from matplotlib.backends.backend_tkagg import ... |
#!/usr/bin/python
# -*- coding:utf-8 -*-
import numpy as np
from scipy import stats
import matplotlib as mpl
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
if __name__ == '__main__':
x1, x2 = np.mgrid[-5:5:51j, -5:5:51j]
x = np.stack((x1, x2), axis=2)
... |
<gh_stars>0
# ============================================================================
# ============================================================================
# Copyright (c) 2021 <NAME>. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file exce... |
import os
import numpy as np
from scipy.stats import mode
from tensorflow.keras.models import Model
from tensorflow.keras.models import Sequential
from tensorflow.keras.models import load_model
from tensorflow.keras.layers import Concatenate
from tensorflow.keras.models import clone_model
# Only trainable f... |
import os
import numpy as np
import pickle
import astropy.units as u
import astropy.constants as const
import nexoclom.math as mathMB
from nexoclom.atomicdata import atomicmass
def sputdist(velocity, U, alpha, beta, species):
mspecies = atomicmass(species)
v_b = np.sqrt(2*U/mspecies)
v_b = v_b.to(u.km/u.s... |
#!/usr/bin/env python
# Use pixel difference and Kirsch filter to pick series of random points
import georasters as gr
import numpy as np
import matplotlib.pyplot as plt
from scipy import ndimage
import random
import string
import csv
diff_gr = gr.from_file('./output/diff.tif')
ndv, xsize, ysize, geot, projection, ... |
<filename>cliques_test.py
"""Pipeline for building the triangular cliques graph."""
import main_pipelines as mp
import networkx as nx
import matplotlib.pyplot as plt
import pickle
from random import seed
from random import random
from scipy.stats import bernoulli
import build_generic_network as bgn
import community as... |
<gh_stars>1-10
from pylab import *
from scipy import special
def exactSol(T):
Nt = T*0.0
for i in range(T.shape[0]):
t = T[i]
t1 = pi*special.erf(1/sqrt(2)*min(6,2*pi/t))
t2 = t/sqrt(2*pi)*(1-exp(-min(6,2*pi/t)**2/2))
Nt[i] = t1-t2
return Nt
def exactEnergySol(T):
Et = ... |
<gh_stars>1-10
""" Seismic Crop Batch."""
import string
import random
from copy import copy
import numpy as np
import segyio
import cv2
from scipy.signal import butter, lfilter, hilbert
from ..batchflow import FilesIndex, Batch, action, inbatch_parallel
from ..batchflow.batch_image import transform_actions # pylint: ... |
<gh_stars>0
# Copyright (c) 2016-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
"""Defines a ... |
import inspect
import numpy as np
import statistics
from autogoal.ml.utils import LabelEncoder, check_number_of_labels
METRICS = []
def register_metric(func):
METRICS.append(func)
return func
def find_metric(*types):
for metric_func in METRICS:
signature = inspect.signature(metric_func)
... |
<gh_stars>0
# Loading Basics
from colorama import init, Back, Fore
init(autoreset=True) #to convert termcolor to wins color
from os.path import basename as bs
myname = bs(__file__).split('.')[0] # This py-script's name
import sys, struct
from importlib import import_module as im
from flask import Flask, request, rende... |
import os
import sys
import numpy as np
import scipy as sp
import scipy.constants as sc
import constants as c
import utils
import scipy.interpolate as spi
import time
import taurex_ggchem
import progressbar
libdir = os.path.dirname(os.path.realpath(__file__))
moddir = os.path.join(libdir, 'modules')
ratedir = os.path.... |
'''
Reference: https://stackoverflow.com/questions/20915502/speedup-scipy-griddata-for-multiple-interpolations-between-two-irregular-grids
<NAME> (<EMAIL>)
'''
from scipy.spatial import qhull
import numpy as np
from numba import jit
def interp_weights(x, X):
nx, nX = x.size, X.size
bounds = np.zeros((nX, 2), ... |
<gh_stars>0
from typing import Tuple
import numpy as np
from scipy import ndimage
from table_annotator.types import Rectangle, Point, Table
BORDER_OFFSET = 5
ROW_COLUMN_WIDTH = 3
def get_dimensions(image: np.ndarray) -> Tuple[int, int]:
"""Returns the width and height of the given image on disc."""
return i... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 4 11:07:16 2021
@author: arnep
"""
from scipy import optimize
import numpy as np
import json
from scipy.stats import norm
def llik_gaussian(v, F):
"""
Log likelihood function of a Gaussian model, based on the prediction error
decomposit... |
# Universidade Federal de Viçosa - Campus Rio Paranaíba
# Sistemas de Informação - Processamento Digital de Imagens
#
# Professor: <NAME>
# Autores:
# - MatheusRV (3929)
# - iguit0 (3902)
# - ThiagoMunich (3628)
#
# Filtragem espacial para aguçamento - Máscara de nitidez e high-boost
# Como E... |
<reponame>MaayanLab/creeds<gh_stars>1-10
'''
ORMs for signature, signatures in the MongoDB and collection of signatures.
'''
import os, sys, json
import hashlib
from collections import Counter
import numpy as np
import pandas as pd
import scipy.sparse as sp
import requests
from joblib import Parallel, delayed
from .g... |
<gh_stars>0
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 29 11:41:45 2021
@author: marco
"""
from scipy.integrate import odeint
import numpy as np
import matplotlib.pyplot as plt
# %matplotlib inline
!pip install mpld3
import mpld3
mpld3.enable_notebook()
"""### Föränderlig $R_{0}$"""
def plotseird(t, S, E, I, R,... |
<filename>networkrepository_run_analysis.py
"""
A script that analyzes the graph data downloaded from http://networkrepository.com
.. moduleauthor:: <NAME> <<EMAIL>>
"""
from __future__ import unicode_literals
from future import standard_library
standard_library.install_aliases()
from builtins import object, range
imp... |
from __future__ import absolute_import, division, print_function
import os
from scipy import constants
from vivarium.core.process import Process
from vivarium.library.make_media import Media
from vivarium.library.look_up import LookUp
from vivarium.library.rate_law_utilities import load_reactions
from vivarium.librar... |
<reponame>vschorp/raisimLib<filename>raisimGymTorch/raisimGymTorch/helper/output_helper.py
import numpy as np
from scipy.spatial.transform import Rotation
from matplotlib import pyplot as plt
import torch
import os
class EvaluationVisualizer:
def __init__(self, max_steps, ob_dim, save_path, is_delta=False):
... |
'''
1. Exploit inconsistencies in implied volatility across different strike prices
2. Market make when spreads are large, without becoming overly exposed to risk
3. Hedge positions to reduce risk
TODO: Make sure 4000 position limit is not exceeded.
Check if profit is actually made.
If options automatically expire, do... |
<filename>generate_seg.py
# System libs
import os
import argparse
from distutils.version import LooseVersion
# Numerical libs
import numpy as np
import torch
import torch.nn as nn
from scipy.io import loadmat
import csv
import sys
sys.path
sys.path.append('semantic_segmentation')
from mit_semseg.dataset import TestData... |
import numpy as np
from scipy.interpolate import splev
from pwtools.num import Spline
def test_spline():
x = np.linspace(0,10,100)
y = np.sin(x)
spl = Spline(x,y)
assert (y - spl(x) < spl.eps).all()
assert (y - splev(x, spl.tck) < spl.eps).all()
assert not spl.is_mono()
np.testing.assert_ar... |
<gh_stars>1-10
import json
import os
from scipy import misc
import dlib
import tqdm
import numpy as np
import cv2
import sys
sys.path.append('./..')
from utils import utils
shape_predictor_path = "../model/shape_predictor_68_face_landmarks.dat"
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predi... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: winston
"""
import numpy as np
from keras.models import Model
from keras.layers import Dense, Input
from keras.optimizers import Adam
from scipy.io import loadmat
from sklearn.metrics import f1_score
from utils import getPaths, cc_coef, evaluation_metrics
from... |
import torch
import torch.nn.functional as F
import scipy.sparse as sp
from copy import copy
from torch_geometric.data import Data
from torch_geometric.transforms import BaseTransform
from torch_geometric.utils import degree, to_scipy_sparse_matrix, from_scipy_sparse_matrix
from graphwar.utils import scipy_normalize
... |
<gh_stars>1-10
#!/usr/bin/env python
# Author: <NAME>
def merge_pfisr_with_gitm_potentials(PhiX, PhiY, XadaptGrids, YadaptGrids, pfisrTimes, weimerSimulationList, gridRes, mergeParameter, plotPotentials, savePotentials):
'''
This function merges the potentials calculated from PFISR estimates with the
... |
from itertools import product
from typing import List, Tuple
import torch
import numpy as np
from sympy import sympify, to_dnf
from sympy.logic import simplify_logic
from torch_explain.logic.nn.utils import _collect_parameters
def explain_class(model: torch.nn.Module, x: torch.tensor = None, concept_names: list = N... |
#%% Step 1 (import python modules)
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import scipy.stats as st
# Import SAFE modules:
from SAFEpython import PAWN
import SAFEpython.plot_functions as pf # module to visualize the results
from SAFEpython.model_execution import model_execution # module... |
<reponame>dtklinh/Protein-Rigid-Domains-Estimation<gh_stars>0
# -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
#
# MDAnalysis --- https://www.mdanalysis.org
# Copyright (c) 2006-2017 The MDAnalysis Development Team and contributors
# (see the... |
import cv2
import numpy as np
from scipy.special import expit
def refined_box(left, top, width, height):
right = left + width
bottom = top + height
original_vert_height = bottom - top
top = int(top + original_vert_height * 0.15)
bottom = int(bottom - original_vert_height * 0.05)
margin = ((b... |
<reponame>vishalbelsare/examples<filename>examples/monetary_shocks/optimization_functions.py
from scipy.optimize import minimize
from numba import jit
# on the next cython update try cdef double F(..)
@jit
def F(xx, prices_non_labor, wage, gamma, one_by_gamma, l, one_minus_l):
price_labor = xx[-1]
summation ... |
import numpy as np
from pathlib import Path
import pandas as pd
import h5py
import matplotlib.pyplot as plt
import obspy
import bisect
from pyproj import Geod
import sys
sys.path.append('./src/S_EqT_codes/src/')
sys.path.append('./src/PickNet')
import tensorflow as tf
from data_preprocessing import build_phase_dict
im... |
#!/usr/bin/env python
"""
Assumptions:
* ciphertext is only uppercase English letters that represent lowercase English letters - no spaces, no special characters, no numbers, etc.
"""
import sys
import operator
import scipy as sp
import matplotlib.pyplot as plt
import enchant
def convertLettersToDecimal... |
<filename>src/shortrate_model_vasicek.py
''' Implementation of vasicek class incorporating key calcultions '''
# import businessdate as bdte
import numpy as np
from scipy.stats import norm as norm_dist
# import pandas as pd
from interest_rate_hjm import hjm_model
class short_rate_vasicek(hjm_model):
''' implement... |
#!/usr/bin/python
import sys
import time
import numpy as np
from scipy import linalg, stats
def rsvd(X, dstar, power_iters=2, delta=10):
""" Perform rsvd algorithm on input matrix.
Method must be supplied dstar.
Returns truncated svd (U,S,V).
Parameters
----------
X : int matrix
Matrix of n x m integers,... |
'''
Defining distributions and their stats most common for project management.
'''
import numpy as np
import scipy.stats as st
import matplotlib.pyplot as plt
def fit(data,dist_type):
'''
Fit a distribution on data using maximum likelihood method
'''
try:
data=np.concatenate(data).ravel()
... |
import pytheia as pt
import numpy as np
import cv2
from scipy.spatial.transform import Rotation as R
import time
dtype = np.float64
nr_runs = 100000
Deg2Rad = 180.0/np.pi
r1 = 15 * Deg2Rad
r2 = -10 * Deg2Rad
R1 = R.from_rotvec(np.array([r1, 0, 0]))
R2 = R.from_rotvec(np.array([0, r2, 0]))
R_gt = (R1.as_matrix() @ R2.... |
<filename>md_davis/common/schlitters_entropy.py
import argparse
import mdtraj
import numpy
from scipy.constants import Boltzmann, hbar, R, u, nano
CONSTANT = (Boltzmann * numpy.exp(1)**2 * 298.15 * nano**2 * u) / (hbar**2)
def get_arguments():
""" Get filename and arguments from the commandline """
parser = ... |
import sys
import seaborn as sns
import prince
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import scipy.cluster.hierarchy as sch
from sklearn.cluster import KMeans, DBSCAN, Birch, MeanShift, \
SpectralClustering, AffinityPropagation, FeatureAgglomeration, Agglomerati... |
from numpy import zeros, diag, eye, exp, sqrt
from scipy.linalg import kron
def PortfolioMomentsLogN(v_tnow, h, LogN_loc, LogN_disp):
# This function computes the expectation, the standard deviation and the skewness
# of a portfolio's P&L which is lognormally distributed.
# INPUTS
# v_tnow :... |
import pickle as p
import os
import numpy as np
import argparse
from scipy.stats import ks_2samp
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--path_results', type=str, default=None, help='path for saving results')
args = parser.parse_args()
alpha = 0.01
pri... |
<filename>ttskit/waveglow/mel2samp.py
# *****************************************************************************
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following condit... |
"""
Additional strategies from Axelrod's first tournament.
"""
import random
from typing import Dict, List, Tuple
from axelrod.action import Action
from axelrod.player import Player
from axelrod.random_ import random_choice
from axelrod.strategy_transformers import FinalTransformer
from scipy.stats import chisquare
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.