text string |
|---|
<gh_stars>1-10
from pynm import pynm
import numpy as np
import pandas as pd
import scipy.stats as sp
import math
import pytest
from pynm.util import *
import matplotlib.pyplot as plt
from unittest.mock import patch
from sklearn.model_selection import train_test_split
def model(age, sex, offset):
noise = np.random... |
"""
Performs similarity matrix on image patches
Returns a csv file with the approximate lat, lon and the ten closest images
STATUS: hacky -- uses json created locally because postgres database not set up
"""
import os
import json
import numpy as np
from scipy import spatial
print(__doc__)
def get_lat_lon_model(... |
import random, math, cmath, pylab, os
#Introduce the periodic boundary conditions via the modular distance between two 2D vectors x, y:
def dist(x,y):
d_x = abs(x[0] - y[0]) % 1.0 #distance between the first compononents of two vectors in modulo 1
d_x = min(d_x, 1.0 - d_x) #the modular distance is the minimum ... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 11 11:32:27 2018
@author: gregz
"""
import glob
import os.path as op
import numpy as np
import sys
from astropy.io import fits
from distutils.dir_util import mkpath
from input_utils import setup_parser, set_daterange, setup_logging
from utils import biweight_location
fr... |
# coding: utf-8
# In[1]:
get_ipython().magic(u'matplotlib inline')
import os
if os.name != 'nt':
from bq.edx2bigquery.edx2bigquery import bqutil
import pycountry
import pandas as pd
import numpy as np
import scipy
import sklearn
from sklearn.datasets import fetch_mldata
from sklearn.cluster import KMeans
f... |
<filename>src/brainexercises/rl/classic/mountaincar_net.py
#!/usr/bin/env python
from __future__ import print_function
import numpy
from scipy import mean
from matplotlib import pyplot as plt
from pybrain.rl.environments.classic.mountaincar import MountainCar
from pybrain.rl.agents import LearningAgent
from pybrain... |
import sys
import numpy as np
import scipy.spatial.distance as distance
from Graph import EventGraph
if len(sys.argv) > 2 and sys.argv[2].endswith('hop'):
pass
else:
if sys.argv[0] == "":
import fasttext
ft = fasttext.load_model(f'{sys.argv[1]}/cc.zh.300.bin')
else:
... |
# -*- coding: utf-8 -*-
""" About processing Sparse Matrix
Author: Hunchbrown - <NAME>
Last Modified: 2020.07.20
About processing Sparse Matrix
"""
import numpy as np
import scipy.sparse as sp
from sklearn.feature_extraction.text import TfidfTransformer
def to_sparse_matrix(dataframe, playlist2idx, item2idx, mode,... |
<filename>PythonCode/Ch04/ch4Python.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ch4Python.py Statistical significance of mean.
import numpy as np
from scipy import stats
y = [3.34,4.97,4.15,5.40,5.21,4.56,3.69,5.86,4.58,6.94,5.57,5.62,6.87]
# Convert daa to vector.
y = np.array(y)
n = len(y)
# Find zero ... |
#!/usr/local/sci/bin/python
# PYTHON3
#
# Author: <NAME>
# Created: 8 January 2016
# Last update: 6 March 2020
# Location: /data/local/hadkw/HADCRUH2/UPDATE2014/PROGS/PYTHON/
# GitHub: https://github.com/Kate-Willett/Climate_Explorer/PYTHON/
# -----------------------
# CODE PURPOSE AND OUTPUT
# ----------------------... |
<gh_stars>1-10
# -*- coding: utf-8 -*-
"""This module implements regularized least square restoration methods
adapted to 3D data.
The two methods it gathers are
* **Smoothed SubSpace (3S) algorith**,
* **Smoothed Nuclear Norm (SNN) algorithm**.
"""
import time
import numpy as np
import numpy.linalg as lin
import sc... |
import numpy as np
import pandas as pd
import h5py
from sklearn.feature_extraction.text import CountVectorizer
from scipy.sparse import save_npz, load_npz
from tools import pad_integers
# Importing the data
indir = 'C:/data/addm/'
corpus = pd.read_csv(indir + 'corpus_with_lemmas_clean.csv')
text = corpus.dx
target =... |
<reponame>Alber6/MCFNL2021
import numpy as np
import matplotlib.pyplot as plt
from scipy.constants import speed_of_light, epsilon_0, mu_0
eta_0 = np.sqrt(mu_0/epsilon_0)
class Panel:
def __init__(self, thickness, epsilon_r = 1.0, sigma = 0.0, mu_r = 1.0):
self.thickness = thickness
self.epsilon_... |
<gh_stars>1-10
# python3
"""Spectral Decomposition."""
from absl import app
import numpy as np
import scipy.stats
from src.lib import ops
def spectral_decomp(ndim: int):
"""Implement and verify spectral decomposition theorem."""
# The spectral theorem says that a Hermitian matrix can be written as
# the sum ... |
<reponame>dhruvsharma95/ga-learner-dst-repo
# --------------
# Importing header files
import numpy as np
import pandas as pd
from scipy.stats import mode
import warnings
warnings.filterwarnings('ignore')
#Reading file
bank_data = pd.read_csv(path)
#Code starts here
# Step - 1
categorical_var = b... |
import cmath
import math
import svgwrite
import sys
golden_ratio = (1 + math.sqrt(5)) / 2
interior_angle = math.pi/5
class Point:
def __init__(self, val, color):
self.val = val
self.color = color
# Get the linear coordinates from a complex number (Polar coordinate)
def lin_coord(A):
return (A... |
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 20 11:27:34 2018
@author: <NAME>
"""
import pandas as pd
import re
import json
from statistics import *
import sys
import time
class StatsWrapper(object):
"""
Collection of tools for statistics wrapper.
"""
errors = []
status = 1
def get_valid_filename(self, s):
... |
<reponame>SvenPVoigt/ImageMKS
import numpy as np
from numpy.fft import fftshift
from mkl_fft import fftn, ifftn
# import rdf_cells as rdf
# import kernels_cells as kernels
from scipy import ndimage
from skimage.measure import regionprops
from skimage.morphology import watershed
def gBlur(img, sigma):
ogS = img.sh... |
<filename>src/test_baracca.py
import os
import scipy.io
import json
import numpy as np
import pickle
import cv2
import torch
import time
from torch.utils.data import DataLoader
# Import Datasets
from src.Datasets.Baracca import Baracca
# Import Model
from src.models.refinement import LinearModel
from src.models.refi... |
<reponame>bhishanpdl/Fun_Repos<filename>Powerball_Lottery/powerball_probability.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Date : Jun 13, 2017 Tue
# Last update :
#
# Required answer: 292,201,338
# Imports
from scipy.misc import comb
import sympy
import math
# How to calculate combinations in pytho... |
<filename>examples/synthesis_real_only.py
# -*- coding: utf-8 -*-
import numpy as np
import time
import torch
import scipy.optimize as opt
import pywph as pw
#######
# INPUT PARAMETERS
#######
M, N = 256, 256
J = 6
L = 4
dn = 2
norm = "auto" # Normalization
pbc = True # Periodic boundary conditions
device =... |
<filename>notebooks/minlib/FigSupp5.GuideCoverage.py
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:light
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.3'
# jupytext_version: 1.0.0
# kernelspec:
# display_name: Python 3
# language: python... |
# Copyright (c) 2020, <NAME>
# Licensed under the BSD 3-clause license (see LICENSE.txt)
# ---------------------------------------------------------
# Base classes for feedforward, convolutional and recurrent
# neural network (DNN, CNN, RNN) models in pytorch
# -------------------------------------------------------... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 8 21:02:48 2020
@author: ttrollie
"""
import numpy as np
from matplotlib import pyplot as plt
import time
from numpy import random
from scipy.optimize import curve_fit
import Graph_study as gs
import json
def graphe_init(n0,N,qm):
if n0<... |
"""
Module for working with Bernstein polynomials.
"""
import numpy as np
import sympy as sp
import typing
import vorpy.realfunction.bernstein
import vorpy.symbolic
def bernstein_embedding (*, source_degree:int, dest_degree:int) -> np.ndarray:
"""
NOTE: Not sure if this is totally right -- need to implement c... |
#!/usr/bin/env python
import pdb,sys,os
from scipy.stats import spearmanr
class Distance:
def __init__(self,fromx,toy):
if len(fromx)!=len(toy):
print('error! the length of x and y must match')
sys.exit(0)
self.fromx=fromx
self.toy=toy
def euclidean_distance(self):
S=0
for i in range(len(self.... |
<filename>doc/source/tutorial/examples/morphology_binary_dilation_erosion.py
import matplotlib.pyplot as plt
import numpy as np
import scipy.ndimage
# code for ball taken from
# https://github.com/scikit-image/scikit-image/blob/main/skimage/morphology/footprints.py#L225-L252
# and therefore same as `from skimage.morph... |
from __future__ import absolute_import, division, print_function
import tensorflow as tf
import numpy as np
from scipy.spatial.distance import pdist, squareform
from collections import defaultdict
from stg_node import *
from utils.learning import *
from utils.learning import _SUPER_SECRET_EVAL_KEY
from multimodal_gene... |
import h5py
import numpy as np
import os
import re
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.Alphabet import IUPAC
from BCBio.GFF import GFFExaminer # pip install bcbio-gff
from BCBio import GFF # might be redundant
import sys
import glob
import pandas as pd
import pickle
from collections import OrderedDic... |
# solve the stiff linear system
#
# dY/dt = A Y
#
# / -alpha beta \
# with A = | |
# \ alpha -beta /
#
# this has the analytic solution for Y_B(0) = 0 of
#
# Y_B/Y_A = [ exp{(alpha+beta) t} - 1 ] / [ (beta/alpha) exp{(alpha+beta) t} + 1]
#
# this shows that a characteristic timesc... |
import numpy as np
import matplotlib.pyplot as plt
import os
from scipy import signal
from natsort import natsorted
import sklearn.metrics.pairwise as sktest
#
# parser = argparse.ArgumentParser(description='Rank extraction')
#
# parser.add_argument(
# '--arch',
# type=str,
# default='vgg_16_bn',
# cho... |
<filename>orphics/symcoupling.py<gh_stars>1-10
from __future__ import print_function
import numpy as np
from sympy import Symbol,Function
import sympy
from pixell import fft as efft, enmap
from orphics import maps,io,stats,cosmology,lensing
import os,sys
"""
Routines to reduce and evaluate symbolic mode coupling integ... |
<filename>eecs/models/browning.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
.. py:currentmodule:: eecs.models.Browning
.. moduleauthor:: <NAME> <<EMAIL>>
Cross section models from Browning.
"""
###############################################################################
# Copyright 2019 <NAME>
#
# License... |
<gh_stars>1-10
from scipy import sparse
import numpy as np
from .tools import normalize,normalize_backward,cross_backward
class TriMeshAdjacencies:
"""this class stores adjacency matrices and methods that use this adjacencies. Unlike the TriMesh class there are no vertices stored in this class"""
def __init... |
from __future__ import division
from itertools import combinations
import numpy as np
import time
import os
import datetime
import logging
from scipy.spatial.distance import cdist
import scipy.io as sio
from sklearn.model_selection import KFold, GridSearchCV
from regressor import VectorRegressor
class Timer(object):... |
<filename>sktime/transformers/single_series/boxcox.py
#!/usr/bin/env python3 -u
# coding: utf-8
# copyright: sktime developers, BSD-3-Clause License (see LICENSE file)
__author__ = ["<NAME>"]
__all__ = ["BoxCoxTransformer"]
import pandas as pd
from scipy.special import boxcox
from scipy.special import inv_boxcox
from... |
<filename>DCT/DCT_of_Image.py<gh_stars>0
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 9 10:37:33 2021
@author: <NAME> -- U18EC105
"""
# Libraries to Use
import cv2 as cv
import scipy.fft as spfft
import numpy as np
import matplotlib.pyplot as plotty
# Functions to be used
# 1. 2D Discrete Cosine Transform
d... |
<filename>run_lbp.py
# Copyright (c) 2019-present, <NAME>. All Rights Reserved.
#
# This source code is licensed under the license found in the LICENSE file in
# the root directory of this source tree.
import os
import pickle
from catalyst.utils.image import imread
import cv2
import fire
import numpy as np
import pan... |
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 20 08:06:35 2021
@author: <NAME>
"""
import time
import pandas as pd
import pickle
import matplotlib.pyplot as plt
from scipy.ndimage.filters import uniform_filter1d
from datetime import date, datetime, timedelta
import country_converter as coco
import ... |
<filename>paper_exp_lastmin.py
# -*- coding: utf-8 -*-
"""
Created on Fri May 28 21:07:00 2021
@author: chait
"""
import matplotlib.pyplot as plt
import numpy as np
from utils import *
from rrt_paths import *
from sd_metric import *
from heatmap import *
import copy
import matplotlib.animation as animation
import cv... |
<filename>tmeval/evaluation/util.py
import scipy.optimize as so
import numpy as np
def align_topics(labels_a, labels_b, num_topics):
"""
Align topic labels from two different topic models
:param labels_a: list[(topic_number, weight)]
:param labels_b: list[(topic_number, weight)]
:param num_topics... |
import numpy as np
import xarray as xr
from datetime import date
import scipy.ndimage as ndimage
def mhwdetect(t, pctile=90, windowHalfWidth=5, smoothPercentile=True, smoothPercentileWidth=31, minDuration=5, joinAcrossGaps=True, maxGap=2, maxPadLength=False, coldSpells=False, alternateClimatology=False, Ly=False):
... |
<gh_stars>0
import numpy as np
import sklearn
from sklearn import model_selection
import logistic_regressor as lr
from sklearn import linear_model
import scipy.io
from sklearn.model_selection import KFold
######################################################################################
# The sigmoid function ... |
import logging
import os
import pickle
import numpy as np
import pandas as pd
import torch
from sklearn.metrics import pairwise_distances
from torch.utils.data import Dataset, dataset
from scipy.sparse import coo_matrix
import json
import copy
FloatTensor = torch.FloatTensor
LongTensor = torch.LongTensor
IntTensor =... |
<gh_stars>0
"""
Created on Wed Jun 17 14:01:23 2020
read the 2D maps and stores them in data/
@author: Jyotika.bahuguna
"""
import os
import glob
import numpy as np
import pylab as pl
import scipy.io as sio
from copy import copy, deepcopy
import pickle
import matplotlib.cm as cm
import pdb
import h5py
import pand... |
from scipy.stats import linregress
import numpy as np
class Errors:
def finderrors(self, y, x, timer, position ,n):
model = linregress(x,y)
slope = model.slope
intercept = model.intercept
line = slope*x + intercept
#Calculate the standard error in the regr... |
<filename>py_google_trends/connection.py
""" connection.py -- handles the communication with google trends server """
from .errors import *
import requests
import datetime
import time
import json
import math
import statistics
class connection:
def __init__(self, params):
if 'start_time' not in params or ... |
#!/usr/bin/env python3
import numpy as np
import argparse
import sys,math
sys.path.append(sys.path[0] + '/..')
import growthclasses as gc
from scipy.stats import poisson
import itertools
def func_xexp(ax1,ax2,params):
m1,m2 = gc.getInoculumMatrices(ax1,ax2)
n = m1 + m2
x = np.zeros(np.shape(n)... |
<reponame>jgd10/pySALESetup_legacy<filename>pySALESetup/objectclasses.py
from __future__ import print_function
from __future__ import absolute_import
import random
import warnings
import numpy as np
from PIL import Image
from math import ceil
try:
import cPickle as pickle
except:
import pickle
import scipy.spe... |
import sys, os, glob, argparse, matplotlib
matplotlib.use('Agg') # for cron
sys.path.append('../')
import numpy as np
import netCDF4 as nc
import datetime as DT
import plotting.operationalPlots as oP
import matplotlib.pyplot as plt
from scipy.interpolate import RectBivariateSpline
from getdatatestbed import getDataFRF... |
import numpy as np
import imagehash
import argparse
import pathlib
import os
import scipy.spatial
import PIL.Image
import seaborn as sns
import matplotlib.pyplot as plt
from weedcoco.utils import check_if_approved_image_extension
sns.set_theme(color_codes=True)
ap = argparse.ArgumentParser(description=__doc__)
ap.ad... |
#!/usr/bin/env python3
import sys
import copy
from scipy import stats
MIN_NUM_ELEM = 3
def get_list_value(sample):
list_value = []
for cluster in sample:
temp = []
for key1 in cluster:
for key2 in cluster[key1]:
temp.append(cluster[key1][key2])
list_value.... |
"""
Helper script that creates visualisations for findsong's debug info
"""
from argparse import ArgumentParser
from itertools import groupby, islice
from os import listdir
from os.path import isfile, join
import re
from matplotlib import collections as mc, colors, pyplot as plt, rc
import numpy as np
from scipy.io.wav... |
from scipy import integrate, linalg
import numpy as np
# 積分
# 2x + 5のこと
def func(x):
return 2*x + 5
# 2x + 5を積分すると
# 2 * 1/2 * x^2 + 5 * x + c
# すなわち
# x^2 + x^2 + c
# 5を代入すると
# 積分結果は50
# 誤差(cのこと)
res, err = integrate.quad(func, 0, 5)
print("積分結果:{0}, 誤差:{1}".format(res, err))
# 行列
# numpy
narray = np.array([[... |
import streamlit as st
import pandas as pd
import numpy as np
import os, cv2
import sys
import scipy.io
import random
from pathlib import Path
import json
import PIL
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
import matplotlib.patches as patches
def main():
# Render the readme as ma... |
"""Lower-level plotting tools.
Routines that may be of use to users wishing for more fine-grained control may
wish to use.
- ``make_1d_axes``
- ``make_2d_axes``
to create a set of axes and legend proxies.
"""
import numpy as np
import pandas
import matplotlib.pyplot as plt
from scipy.stats import gaussian_kde
from ... |
import sympy
from mathpad.units import seconds, meters, second, radians
from mathpad.dimensions import Angle
t = "t" * seconds
g = 9.81 * meters / second ** 2
pi = Angle(radians.units, sympy.pi) # type: ignore
def frac(numerator, denominator):
return sympy.Rational(numerator, denominator)
|
import sys
CENTERNET_PATH = './lib/'
sys.path.insert(0, CENTERNET_PATH)
from detectors.detector_factory import detector_factory
from opts import opts
import argparse
import glob
import os
import cv2
import json
import numpy as np
from scipy.spatial import distance
from sklearn.metrics import roc_curve, auc
import mat... |
# coding=utf-8
# Author: <NAME> Cruz <<EMAIL>>
#
# License: BSD 3 clause
import numpy as np
from scipy.stats import mode
from deslib.des.base import DES
class KNORAU(DES):
"""k-Nearest Oracles Union (KNORA-U).
This method selects all classifiers that correctly classified at least
one sample belong... |
# This file is part of GridCal.
#
# GridCal is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# GridCal is distributed in the hope that... |
<gh_stars>0
''' Class which converts raw text into embeddings. '''
from textblob import TextBlob
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.decomposition import TruncatedSVD
from sklearn.metrics.pairwise import cosine_similarity
from scipy.sparse import csr_matrix, hstack
def HAL(docs... |
import os
os.chdir('STARmap_AllenVISp/')
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use('qt5agg')
matplotlib.rcParams['pdf.fonttype'] = 42
matplotlib.rcParams['ps.fonttype'] = 42
import matplotlib.pyplot as plt
import scipy.stats as st
import pickle
with open ('data/SpaGE_pkl/Sta... |
import pandas as pd
from scipy.stats import chi2_contingency
data = pd.read_csv("ab_data.csv")
print(data.head())
# calculate contingency table here
ab_contingency = pd.crosstab(data.Web_Version, data.Purchased)
print(ab_contingency)
# run your chi square test here
chi2, pval, dof, expected = chi2_contingency(ab_con... |
"""
This tests image classification using a vision model.
"""
import numpy as np
import cv2
import pathlib
import vision
import statistics
def read_image(file: pathlib.Path):
image = cv2.imread(str(file), flags=cv2.IMREAD_COLOR)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
image = cv2.resize(image, (128... |
#!/usr/bin/env python
import copy
import numpy as np
import scipy
import matplotlib.pyplot as plt
from ugali.isochrone.parsec import Bressan2012
import ugali.utils.projector
import utils
class Isochrone(Bressan2012):
def __init__(self, distance_modulus):
age = 10.
metal_z = 0.0001
super(Iso... |
# %%
# For numerical calculations
import numpy as np
import pandas as pd
import scipy as sp
import math
import git
from scipy.integrate import odeint
from numpy import arange
from scipy.integrate import odeint
import scipy.optimize
from scipy.optimize import leastsq
from math import exp
from collections import Ordere... |
<gh_stars>0
# Features: Word Embeddings
# Models: SVM
import time
import pickle
import json
import argparse
from scipy.sparse import data
from thundersvm import *
from sklearn import svm
import gensim.downloader as api
import gensim
import spacy
import numpy as np
import pandas as pd
from typing import Union
from tqd... |
<reponame>usccolumbia/CSCE206_Projects
# -*- coding: utf-8 -*-
"""
Titration solver
University of South Carolina
CSCE206 Scientific Application Programming
Spring 2013 Final project
Created on Tue Nov 5 20:55:49 2013
"""
import re as re
from Tkinter import *
from tkMessageBox import *
from string import ascii... |
"""
Date: 07/05/2020
Author: <NAME>
"""
__all__ = ['Metropolis', 'GeodesicMC']
import numpy as np
import scipy.stats as st
import scipy.linalg as lng
from _stiefel_sampling import MatrixLangevin
class Metropolis(object):
_proposal = None
_like = None
_chain = None
def __init__(self, prop, like):
self._pr... |
<filename>phase2/Summaryconsumer.py
from kafka import KafkaConsumer, TopicPartition
from json import loads
from os import getenv
from sqlalchemy import create_engine
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import pymy... |
#MPC formulation
import numpy as np
from numba import njit
import random
from scipy.integrate import solve_ivp, simps
from scipy.optimize import differential_evolution, Bounds, minimize
from scipy.stats import truncnorm
from matplotlib import pyplot as plt
from configurations import *
import solve_ocp
def get_new_U_... |
## Portions of Code from, copyright 2018 <NAME>
from __future__ import absolute_import, division, print_function
import torch
import numpy as np
from scipy import ndimage
import png
def numpy2torch(array):
assert(isinstance(array, np.ndarray))
if array.ndim == 3:
array = np.transpose(array, (2, 0, ... |
# coding: utf-8
from __future__ import division, unicode_literals, print_function # for compatibility with Python 2 and 3
import os
try:
from dbox import prepare_photos
from utilities import *
except:
from .dbox import prepare_photos
from .utilities import *
import math
import cv2
import shutil
imp... |
<filename>gw/module/gwplot.py
#============================================================
# GW PLOT MODULE
# 2019.08.11 CREATED BY <NAME>
# 2019.10.09 UPDATED BY <NAME>
#============================================================
from astropy.coordinates import SkyCoord
from matplotlib import pyplot as plt
import li... |
<reponame>ubermag/discretisedfield<filename>discretisedfield/field_rotator.py
import warnings
import numpy as np
import discretisedfield as df
from scipy.interpolate import RegularGridInterpolator
from scipy.spatial.transform import Rotation
class FieldRotator:
r"""Rotate a field.
This class can be used to r... |
import argparse
import requests
import statistics
import time
def run_test(url, method="GET", body=None, json=None, runs=100, replica=1):
reps = []
for rep in range(replica):
times = []
responses = []
for i in range(runs):
t = time.perf_counter()
r = requests.re... |
<reponame>kisonecat/padeapprox
#! /usr/bin/env nix-shell
#! nix-shell -i python3 -p "python3.withPackages(ps: [ps.numpy ps.numba ps.mpmath ps.matplotlib])"
import numpy as np
from scipy.linalg import toeplitz
eps = np.finfo(np.float).eps
def padeapprox(f, m, n, tol=1e-14):
"""Pade approximation to a function or ... |
<gh_stars>100-1000
"""Affinity matrix refinemnet operations."""
import abc
import enum
import numpy as np
from scipy.ndimage import gaussian_filter
class RefinementName(enum.Enum):
"""The names of the refinement operations."""
CropDiagonal = enum.auto()
GaussianBlur = enum.auto()
RowWiseThreshold = enum.auto... |
#!/usr/bin/env python3
# Copyright (c) 2019 MindAffect B.V.
# Author: <NAME> <<EMAIL>>
#
# 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 th... |
# Generate sparse matrix multiply test cases
import numpy as np
import scipy.sparse as sps
def flatten(a):
'''Flatten a nested list'''
return [item for d in a for item in d]
def string_elements(a):
'''Convert elements of a list to strings'''
return [str(item) for item in a]
def matrix_vector_mult():
A =... |
import numpy as np
from pyyeti import ytools, nastran, locate
from pyyeti.nastran import op4, op2
from scipy.io import matlab
from nose.tools import *
def runcomp(nas, m):
matnas = m["nas"]
for name in matnas.dtype.names:
if isinstance(nas[name], dict):
for k in nas[name]:
... |
#
# Copyright 2012 by Idiap Research Institute, http://www.idiap.ch
#
# See the file COPYING for the licence associated with this software.
#
# Author(s):
# <NAME>, December 2012
#
import numpy as np
import scipy.signal as sp
import numpy.linalg as linalg
from . import core
class Autoregression:
"""
Class co... |
import numpy as np
from scipy import stats
def permute_ties(x, decreasing=True):
"""
"""
if decreasing:
x = -x
ranks = stats.rankdata(x, 'ordinal')
groups = stats.rankdata(x, 'min')
_permute_ties(ranks, groups)
def _permute_ties(ranks, groups, prev=0, l=[]):
if len(ranks) =... |
<filename>data/proteins/make_data.py<gh_stars>1-10
"""
Create simulated protein contact data
"""
import os
import sys
import numpy as np
from csb.bio.io import StructureParser
from ensemble_hic import kth_diag_indices
from ensemble_hic.forward_models import EnsembleContactsFWM
np.random.seed(42)
## Set this to true... |
<reponame>ahaselsteiner/viroconcom<filename>manual_tests/manual_test_fitting.py
import numpy as np
from scipy.optimize import curve_fit
from matplotlib import pyplot as plt
from virocon._fitting import (
fit_function,
fit_constrained_function,
convert_bounds_for_curve_fit,
)
from virocon import Dependenc... |
<reponame>lukas-weber/fftl-data
import numpy as np
import matplotlib.pyplot as plt
import scipy.optimize as spo
def fit_bootstrap(func, x, y, sigy, p0, samples=50):
popt0, _ = spo.curve_fit(func, x, y, p0=p0, maxfev=20000)
popts = []
for i in range(samples):
yr = y + np.random.normal(size=y.shape)... |
<filename>new_techniques/testexample.py
#!/usr/bin/env python3
import sympy as S
import simpy
import matplotlib.pyplot as plt
from src.solver import Solver
step = 0 # The number of integration steps
STOP_TIME = 1.5 # in seconds
data = dict() # The final resul... |
<gh_stars>1-10
import os
import cv2
import numpy as np
import time
import scipy.io as sio
from collections import OrderedDict
from tqdm import tqdm
import math
import insightface
import sklearn
from sklearn import preprocessing
from PIL import Image, ImageEnhance
model = insightface.app.FaceAnalysis()
ctx_id = 0
model... |
<reponame>HelloCoyen/mksc2<filename>mksc/feature/values/standard.py
import math
from scipy.stats import boxcox
def fix_standard(feature):
"""
对数据框中的数据进行正态化处理
Args:
feature: 待处理的数据框
Returns:
feature: 已处理数据框
standard_lambda: 对应特征的lambda值
"""
numeric_var = feature.selec... |
#!/usr/bin/python3
# -*- coding=utf-8 -*-
import numpy as np
import copy
from scipy.special import expit, softmax
def yolo3_head(predictions, anchors, num_classes, input_dims):
"""
YOLO Head to process predictions from YOLO models
:param num_classes: Total number of classes
:param anchors: YOLO style... |
# -*- coding: utf8
from __future__ import division, print_function
'''
Implements models based on linear regression. In general these models are
only wrappers to sklearn models.
'''
import numpy as np
from pyseries.data.base import TimeSeriesDataset
from pyseries.exceptions import ParameterException
from pyseries.ex... |
<filename>data-drift.py
'''
Data Drift automatically checks for statistical differences in data upon code changes.
Inputs: 2 dataframes for comparison. 1 dataframe could be the data used to train a model. The other is the current data used to make predictions
Ouput: A series of tests that dectect statistical differen... |
<reponame>aibhleog/Keck-Visiting-Scholar
'''
Code used to fix the internal flexure in one reference frame. We plan to compare to the actual FCS model to see the differences.
'''
__author__ = '<NAME>'
__email__ = '<EMAIL>'
__version__ = 'Oct2019'
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
f... |
"""
Analytic functions for this test are defined in "analytic_filter.ipynb" in the development/ directory.
"""
import inspect
import os
LOCATION = "/".join(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))).split("/")[:-1])
import sys
sys.path.insert(0, LOCATION)
from hmf import filters
import n... |
<gh_stars>1-10
import json
import statistics as stat
import numpy as np
import pandas as pd
import csv as csv
import os
from tqdm import tqdm
import networkx as nx
pwd = "/home/srivbane/shared/car<PASSWORD>/data/projects/sna-social-support/csv_data/"
epoch_day = 86400000 # accounting for milliseconds
rng = 21 ... |
import psutil
import numpy as np
from scipy.ndimage import zoom
class ImioLoadException(Exception):
pass
def check_mem(img_byte_size, n_imgs):
"""
Check how much memory is available on the system and compares it to the
size the stack specified by img_byte_size and n_imgs would take
once loaded... |
<filename>source_code/PE_partial_edit_counting_ver220118.py
#!/home/hkim/anaconda3/bin/python
import os, sys, pickle, time, subprocess, json, re, string, regex, random, collections, itertools
import subprocess as sp
import numpy as np
import scipy.stats as stats
import matplotlib as mpl
import pandas as pd
import mult... |
<reponame>yusuke61/drought_definition_issue
#!/usr/bin/env python
# To compare uncertainties in base variable with that of main results (for response to the reviewer) >>> SupFig.2&3, SupFig.6&7
# By <NAME>
# On 2021/08/03
import os
import sys
import time
import itertools
import numpy as np
import matplotlib as mpl
im... |
from sympy.physics.secondquant import (AntiSymmetricTensor, wicks,
F, Fd, NO, evaluate_deltas, substitute_dummies, Commutator,
simplify_index_permutations, PermutationOperator)
from sympy import (
symbols, expand, pprint, Number, latex
)
print
print "Calculates the Coupled-Cluster energy- and ampl... |
<filename>PFPhoton-ID-Evaluator.py
#############################################################################
# TESTING A SEQUENTIAL NEURAL NETWORK #
# #
# This code reads into testing CSV Files and the tr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.