text string |
|---|
import cv2
import numpy as np
from numpy.core.defchararray import array
#import matplotlib.pyplot as plt
# import speech_recognition as sr
# import time
# from gtts import gTTS
# import os
from scipy.spatial import distance as dist
from collections import OrderedDict
from contextlib import nullcontext
import... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""Create HTML reports."""
from contextlib import contextmanager
from copy import deepcopy
import os.path as op
import time
import warnings
import numpy as np
from scipy.signal import find_peaks, peak_prominences
import mne
from mne import read_proj, read_epochs, find_e... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 2 16:15:49 2021
@author: ichamseddine
"""
#%% Libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import sys
import warnings
import os
import seaborn as sns
from scipy.stats import mannwhitneyu, fisher_exact, chi2_co... |
import os
from argparse import ArgumentParser
import subprocess
import cantera as ct
import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
from pyjac import create_jacobian
from pyjac.utils import create_dir
from pyjac.libgen import build_type, generate_library
from pyjac.tests.test_... |
<gh_stars>10-100
"""`PrettyPrint`, `Frozen`, `Data`, `bijective26_name`, `cached`, `gamma`,
`unique`"""
import numpy as np
import sys
import abc
from scipy.special import factorial
from collections import OrderedDict as ODict
from functools import wraps
from string import ascii_uppercase
class PrettyPrint(object, ... |
# -*- Mode:Python; -*-
# /*
# * This program is free software; you can redistribute it and/or modify
# * it under the terms of the GNU General Public License version 2 as
# * published by the Free Software Foundation
# *
# * This program is distributed in the hope that it will be useful,
# * but WITHOUT ANY WARRA... |
<gh_stars>0
# External modules
import numpy as np
from scipy.sparse import linalg
# Local modules
from . import libspline
from .pyCurve import Curve
from .pySurface import Surface
from .utils import Error, _assembleMatrix, checkInput, closeTecplot, openTecplot, writeTecplot3D
class Volume(object):
"""
Create... |
<reponame>zivaharoni/dine
import pickle
import numpy as np
import scipy
import os
import time
from datetime import datetime
from collections import defaultdict as def_dict
import tensorflow as tf
from tensorflow.keras import backend as K
from tensorflow.keras.metrics import Metric, Mean, SparseCategoricalAccuracy, Spar... |
<gh_stars>1-10
# Compute ODT mean and rms velocity profiles. Plot results versus DNS.
# Run as: python3 stats.py case_name
# Values are in wall units (y+, u+).
# Scaling is done in the input file (not explicitly here).
import numpy as np
import glob as gb
import yaml
import sys
import matplotlib
matplotlib.use('PDF') ... |
<reponame>qiaojunfeng/yambo-aiida
# -*- coding: utf-8 -*-
"""helpers for many purposes"""
from __future__ import absolute_import
import numpy as np
from scipy.optimize import curve_fit
from matplotlib import pyplot as plt, style
import pandas as pd
import copy
import os
try:
from aiida.orm import Dict, Str, List, ... |
# Copyright 2019 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
import os, sys
import subprocess
import networkx as nx
import graphviz as gv
from scipy import stats
from scipy.cluster.hierarchy import distance, linkage, fcluster
from matplotlib import patches, pathe... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 13 16:10:15 2020
@author: aymanjabri
"""
from __future__ import division
from scipy.stats import multivariate_normal
import numpy as np
import sys
## can make more functions if required
class pluginClassifier(object):
def __init__(self,X_tra... |
<reponame>AditiRM/gpubootcamp<filename>hpc_ai/PINN/English/python/source_code/spring_mass/spring_mass_solver.py
from sympy import Symbol, Eq
import numpy as np
from simnet.solver import Solver
from simnet.dataset import TrainDomain, ValidationDomain
from simnet.data import Validation
from simnet.sympy_utils.geometry_1... |
import os
import tempfile
import pickle
from sympy.mpmath import *
def pickler(obj):
fn = tempfile.mktemp()
f = open(fn, 'wb')
pickle.dump(obj, f)
f.close()
f = open(fn, 'rb')
obj2 = pickle.load(f)
f.close()
os.remove(fn)
return obj2
def test_pickle():
obj = mpf('0.5')
... |
<reponame>zevgenia/Python_shultais<gh_stars>0
import fractions
f = fractions.Fraction(2, 3)
print(f + 1)
import fractions # подключение рациональных, дробрых чисел
f = fractions.Fraction(2, 3)# числитель 2 знаменатель 3
print(f) |
<filename>examples/LaTeX/lin_tran_check.py<gh_stars>100-1000
from __future__ import print_function
from sympy import symbols, sin, cos, simplify
from galgebra.ga import Ga
from galgebra.printer import Format, xpdf, Eprint, Print_Function, latex
from galgebra.lt import Symbolic_Matrix
def main():
# Print_Function(... |
<filename>scripts/sts.py
#!/usr/bin/env python
import numpy as np
import scipy.special as scsp
import argparse
import asetk.format.cp2k as cp2k
import asetk.util.progressbar as progressbar
import asetk.atomistic.constants as constants
import os.path
# Define command line parser
parser = argparse.ArgumentParser(
de... |
<gh_stars>1-10
r"""
Authors: <NAME>, <NAME>, <NAME>, <NAME>,
<NAME>
Filename: core.py
This file contains some useful objects for handling a finite-state
discrete-time Markov chain.
Definitions and Some Basic Facts about Markov Chains
----------------------------------------------------
Let :math:`\{X_t\}` ... |
#! /usr/bin/env python
"""
A set of functions for calculating flux weights given an array of energy and
cos(zenith) values based on the Honda atmospheric flux tables. A lot of this
functionality will be copied from honda.py but since I don't want to initialise
this as a stage it makes sense to copy it in to here so so... |
<filename>matchmaking/linear_regression_ranker.py<gh_stars>0
from typing import Callable, List, Dict
from discord.channel import TextChannel
from numpy import matrix
from sklearn.linear_model import LinearRegression
from statistics import stdev, mean
from matchmaking.match_finder import Match
from matchmaking.game_dat... |
import pickle
from sklearn import svm
import numpy as np
from scipy.misc import imresize
from sklearn import linear_model
def array_to_feature(array):
meanr = np.mean(array[:,:,0])
meang = np.mean(array[:,:,1])
meanb = np.mean(array[:,:,2])
sigmar =np.std(array[:,:,0])
sigmag =np.std(array[:,:,1])
... |
<reponame>JulyFaraway/ViNet-1
import sys
import os
import numpy as np
import cv2
import torch
from torch.types import Device
from model import VideoSaliencyModel
from scipy.ndimage.filters import gaussian_filter
from loss import kldiv, cc, nss
import argparse
from torch.utils.data import DataLoader
from dataloader imp... |
import wrapt
from functools import partial, reduce
from scipy import signal
import numpy as np
import qcodes
import qcodes.utils.validators as vals
"""
Define some modules for doing filtering on parameters as they come in. This is mainly
useful when we actually want to store some derived quantity (i.e. the differentia... |
<reponame>Dieg0Alejandr0/EquiBind
import copy
import math
import numpy as np
import torch
from rdkit import Chem
from rdkit.Chem import rdMolTransforms
from scipy.spatial.transform import Rotation
def random_rotation_translation(translation_distance):
rotation = Rotation.random(num=1)
rotation_matrix = rotat... |
<filename>wlra/tests/test_nmf.py
import numpy as np
import pytest
import scipy.stats as st
import sklearn.decomposition as skd
from fixtures import simulate
from wlra.nmf import nmf
def test_nmf_shape(simulate):
x, eta = simulate
res = nmf(x, 1)
assert res.shape == x.shape
def test_nmf_rank(simulate):
x, eta... |
<filename>code/scripts/2020/02/0_0_finetune_soft_entropy_regularization_sparse_facto_net_constant_perm.py
"""
This script finds a palminized model with given arguments then finetune it.
Usage:
script.py [-h] [-v|-vv] --walltime int [--seed int] --input-dir path [--permutation-threshold float] [--sparsity-factor=in... |
import logging
import pandas
import os
import numpy as np
from scipy.spatial.distance import cdist, squareform
from scipy.sparse import csr_matrix
from numpy import genfromtxt
from progressbar import ProgressBar, Bar, Percentage, Timer
from DataHandler.Postgres import PostgresDataHandler
logger = logging.getLogger()
... |
import numpy as np
import scipy.special as special
from abc import ABCMeta, abstractmethod
class NFA(object):
__metaclass__ = ABCMeta
def __init__(self, epsilon, proba, min_sample_size):
self.epsilon = epsilon
self.proba = proba
self.min_sample_size = min_sample_size
def nfa(self... |
<gh_stars>1-10
from statistics import *
"""
Find the most frequently occurring character in an array.
"""
def most_frequent(arr):
counter = 0
num = arr[0]
for i in arr:
curr_frequency = arr.count(i)
if curr_frequency > counter:
counter = curr_frequency
num = i
... |
import scipy.stats as st
import math
# Confidence Interval
def confIntrv(signLevel, mean, sd, n):
alpha = ((signLevel/100) - 1) * (-1)
alphaOver2 = alpha / 2
print(alphaOver2)
criticalV = round(st.norm.ppf(1-alphaOver2), 2)
marginE = criticalV * sd / math.sqrt(n)
return (mean - marginE, mean + ... |
from typing import List
from .spacing import full_cosine_spacing, equal_spacing
from .spacing import linear_bias_left
from numpy import multiply, power, array, hstack, arctan, sin, cos, zeros, sqrt, pi
from scipy.optimize import root, least_squares
from . import read_dat
class PolyFoil():
name: str = None
a: L... |
<reponame>oie-mines-paristech/lca_algrebraic<gh_stars>0
import functools
import inspect
import re
import types
from copy import deepcopy
from itertools import chain
import pandas as pd
from bw2data.backends.peewee.utils import dict_as_exchangedataset
from bw2data.meta import databases as dbmeta
from sympy import symb... |
<filename>IMUGrabberPython/imugrabber/algorithms/regression_accelero.py
'''
Created on 2010-02-17
@author: malem303
'''
import scipy as sp
import math
from scipy.optimize import leastsq
from imugrabber.algorithms import utils
def residuals(parameters, targets, measures):
misalignmentsAndScales, biases =... |
<reponame>armahmood/repn-learning<filename>rrdr.py
import numpy as np
import pickle
import math
import statistics
import matplotlib.pyplot as plt
import argparse
def read_losses(features, seed_num, search=False, pathstr=''):
if search:
path = pathstr + 'search/' + str(features) + '/'
else:
pa... |
<gh_stars>0
import pygame
import time
import scipy
import numpy as np
import multiprocessing as mp
import datetime
from .world import WHITE, BLACK
try:
from pudb import set_trace as st
except ModuleNotFoundError:
st = lambda: None
import logging
class surface2():
def __init__(self, x, y, name, scale=10... |
import itertools as it
import numpy as np
from scipy.stats.mstats import mquantiles
from scipy import ndimage as nd
from scipy import sparse
from skimage import morphology as skmorph
from skimage import filters as imfilter, measure, util
from sklearn.neighbors import NearestNeighbors
from six.moves import range
import ... |
from fractions import Fraction
import re
from collections import Counter, deque, defaultdict
from itertools import product
with open('../inputs/d12.txt') as f:
inp = f.read().strip()
inp2 = """F10
N3
F7
R90
F11"""
#inp = inp2
print(inp.split()[:10])
def dir_mul(dir, mul):
return (dir[0] * mul, dir[1] * mu... |
<reponame>applied-systems-biology/python2-custom-segment-glomeruli<gh_stars>0
# -*- coding: utf-8 -*-
'''
Counting glomeruli in Light-Sheet microscopy images of kidney.
Full details of the alogrithm can be found in the paper
Klingberg et al. (2017) Fully Automated Evaluation of Total Glomerular Number and
Capillary ... |
<filename>lenskit/metrics/topnFair.py
"""
Fair Top-N evaluation metrics.
Lav measures ud fra : item, score, user, rank, algorithm, protected
"""
from __future__ import division
import random
import numpy as np
import math
from .topn import *
#dataGenerator
from scipy.stats import spearmanr
from scipy.stats import... |
<filename>metric_gen.py
"""
metric_gen.py
-------
PSSR PIPELINE - STEP 5:
Quantification: Generate Peak-signal-to-noise ratio (PSNR) and Structural
Similarity (SSIM) metrics of the test sets.
This script normalizes each slice of the PSSR inference output stack/Bilinear-upsampled
output to its corresponding slice in Gr... |
<reponame>prokolyvakis/deep-align
from scipy.stats import spearmanr
from scipy.stats import pearsonr
from sklearn.metrics import accuracy_score
from sklearn.metrics import confusion_matrix
from sklearn.metrics.pairwise import cosine_distances
from sklearn.metrics.pairwise import linear_kernel
import numpy as np
import ... |
import pandas as pd
from io import StringIO
import pickle
import scipy.signal as signal
import scipy
import pywt # conda install pywavelets
from math import sqrt, log2
from statsmodels.robust import mad
import numpy as np
class TxtFile:
def __init__(self, filepath, verbose=False):
self.filepath = filepat... |
import tensorflow as tf
import numpy as np
from net.ops import random_bbox, bbox2mask, local_patch
from net.ops import priority_loss_mask
from net.ops import gan_wgan_loss, gradients_penalty, random_interpolates
from net.ops import free_form_mask_tf
from net.vgg import Vgg19
from util.util import f2uint
from functools ... |
"""
This is the main file for ParEx, a suite of parallel extrapolation solvers for
initial value problems. It includes explicit, implicit, and semi-implicit (linearly
implicit) solvers. The code is based largely on material from the
following two volumes:
- *Solving Ordinary Differential Equations I: Nonstiff Pr... |
"""
Convolution
===========
This example shows how to use the :py:class:`pylops.signalprocessing.Convolve1D`,
:py:class:`pylops.signalprocessing.Convolve2D` and
:py:class:`pylops.signalprocessing.ConvolveND` operators to perform convolution
between two signals.
Such operators can be used in the forward model of severa... |
import numpy as np
from scipy.sparse import csc_matrix
from pytorch_widedeep.wdtypes import WideDeep
def create_explain_matrix(model: WideDeep) -> csc_matrix:
"""
Returns a sparse matrix used to compute the feature importances after
training
Parameters
----------
model: WideDeep
obje... |
import time
import types
import uuid
import warnings
from functools import wraps
from typing import Tuple, Callable, Dict, Generic, List, TypeVar, Any
import numpy as np
from . import _ops as math
from ._ops import choose_backend_t, zeros_like, all_available, print_, reshaped_native, reshaped_tensor, stack, to_float
... |
import matplotlib.pyplot as plt
import numpy as np
import scipy.signal as signal
import pandas as pd
data = pd.read_csv('dataset.csv')
time = data['time']
velocity = data['velocity']
f = np.linspace(0.1, 10, 1000)
periodogram = signal.lombscargle(time, velocity, f, normalize=True, precenter=True)
plt... |
"""
Origin: QE by <NAME> and <NAME>
Filename: ar1sim.py
"""
import numpy as np
from scipy.stats import norm
def proto1(a, b, sigma, T, num_reps, phi=norm.rvs):
X = np.zeros((num_reps, T+1))
for i in range(num_reps):
W = phi(size=T+1)
for t in range(1, T+1):
X[i, t] = a * X[i,t-1] +... |
<reponame>adigasu/ResCycleGAN
import scipy
from glob import glob
import numpy as np
# from extension import extension
class DataLoader():
def __init__(self, dataset_name, img_res=(128, 128), is_zeroMean = True):
self.dataset_name = dataset_name
self.img_res = img_res
self.is_zeroMean = is_... |
<reponame>Minyus/pipelinex_image_processing
import numpy as np
from scipy.sparse import coo_matrix
def seg_to_roi(img):
peripheral_seg_val_arr = np.unique(
np.concatenate([img[0, :], img[-1, :], img[:, 0], img[:, -1]])
)
peripheral_seg_val_3darr = np.expand_dims(peripheral_seg_val_arr, axis=0)
... |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
# In[1]:
from binance.client import Client
import json
from datetime import datetime
# In[2]:
import plotly.graph_objects as go
from plotly.subplots import make_subplots as splt
import math
import time
import numpy as np
import pandas as pd
import datetime as d... |
from scipy.misc import imresize
import utils
import numpy as np
from scipy import ndimage
from utils import to_int
def get_random_transform_params(input_shape, rotation_range = 0., height_shift_range = 0., width_shift_range = 0.,
shear_range = 0., zoom_range = (1, 1), horizontal_flip... |
from Portfolio import *
from feed import *
from strategy import *
from execution import *
from statistics import *
import tool
from Onepy import *
|
import argparse
import torch
from torch.nn import functional as F
import numpy as np
from scipy.stats import sem
from pandas import read_csv
from torch.utils import data
from Model.model import Model
from Utils.record import record
from DataLoader.dataset import Dataset
from DataLoader.collate import custom_collate
... |
<reponame>Bijay555/innomatics-Apr21-internship
# Enter your code here. Read input from STDIN. Print output to STDOUT
import cmath
n = input()
print(abs(complex(n)))
print(cmath.phase(complex(n)))
|
<filename>silver_irony_detection.py<gh_stars>0
from numpy.random import seed
seed(100)
from tensorflow import set_random_seed
set_random_seed(2)
from sklearn.model_selection import KFold
from sklearn.metrics import confusion_matrix
from sklearn.feature_selection import RFE, RFECV
import seaborn as sns
import matplotli... |
'''hig-order finite difference solver for 2d Burgers equation'''
# spatial diff: 4th order laplacian
# temporal diff: O(dt^5) due to RK4
import scipy.io
import numpy as np
import matplotlib.pyplot as plt
from random_fields import GaussianRF
import torch
torch.manual_seed(66)
np.random.seed(66)
def apply_laplacian(ma... |
# coding=utf-8
# Copyright 2020 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... |
<gh_stars>0
""" Optimization problem to be solved."""
import yaml
import numpy as np
from scipy.optimize import LinearConstraint, Bounds
from PyMEX.utilits import ParallelPyMex
class Simulation:
""" Reservoir parameters for simulation."""
def __init__(self):
""" Reservoir parameters."""
self... |
"""
Module useful if you need some probabilities distributions not implemented yet in other modules or packages
Created on 15 March 2019
@authors:
* <NAME> (FDS), Politecnico di Torino, ITALY
Updates:
dd Mon YYYY:
* ...
"""
import numpy as np
import scipy as sp
import scipy.integrate as sp_int
import warnin... |
<reponame>mirochaj/ares
"""
OpticalDepth.py
Author: <NAME>
Affiliation: University of Colorado at Boulder
Created on: Sat Feb 21 11:26:50 MST 2015
Description:
"""
import inspect
import numpy as np
from ..data import ARES
import os, re, types, sys
from ..util.Pickling import read_pickle_file, write_pickle_file
fro... |
#-*- coding: utf-8 -*-
# 拉格朗日插值代码
import pandas as pd # 导入数据分析库Pandas
from scipy.interpolate import lagrange # 导入拉格朗日插值函数
inputfile = '../data/missing_data.xls' # 输入数据路径,需要使用Excel格式;
outputfile = '../tmp/missing_data_processed.xls' # 输出数据路径,需要使用Excel格式
data = pd.read_excel(inputfile, header=None) # 读入数据
# 自定义列向... |
from typing import Optional, Union
import numpy as np
from anndata import AnnData
from numpy.random.mtrand import RandomState
from scipy.sparse import issparse
import scanpy
def run_diffmap(adata: AnnData, n_comps: int = 15, copy: bool = False):
"""\
Diffusion Maps [Coifman05]_ [Haghverdi15]_ [Wolf18]_.
D... |
<filename>sampler.py
"""
Code for the actor sampler, for generating datasets for the critic.
"""
import os
import time
import enum
import gzip
import pickle
import logging
import traceback
import psutil
import numpy as np
import multiprocessing as mp
import tensorflow as tf
import tensorflow.contrib.eager as tfe
import... |
<filename>detection/model/evaluation.py
import os
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import linear_sum_assignment
from tqdm import tqdm
import tensorflow as tf
from detection.model.models.ssd import SSD
from detection.utils.box_tools import iou, draw_box
from detection import BASE_... |
import matplotlib
matplotlib.use('Agg')
import config
import pylab
import sys
import numpy
from utils import diversity_utils, clade_utils, species_phylogeny_utils
from parsers import parse_HMP_data, parse_midas_data
from plos_bio_scripts import calculate_substitution_rates
import matplotlib as mpl
import matplotli... |
<filename>app/src/main/python/GainOpt_FilterDyn_Class.py
import mat4py as loadmat
import numpy as np
from numpy import random
np.random.seed(1)
import scipy as sci
from scipy import signal
from scipy.fft import fft, ifft
from scipy.special import comb
from os.path import dirname, join
import math as math
import scip... |
import numpy as np
import matplotlib.pyplot as plt
import os
figdir = os.path.join(os.environ["PYPROBML"], "figures")
def save_fig(fname): plt.savefig(os.path.join(figdir, fname))
from scipy.spatial import KDTree, Voronoi, voronoi_plot_2d
np.random.seed(42)
data = np.random.rand(25, 2)
vor = Voronoi(data)
print('Usi... |
<filename>test.py
# To test the model use the following code:
# python run_model.py model=<model> resolution=<resolution> use_gpu=<use_gpu>
# <model> = {iphone, blackberry, sony}
# <resolution> = {orig, high, medium, small, tiny}
# <use_gpu> = {true, false}
# example: python run_model.py model=iphone resolution=o... |
<reponame>zmatlik117/iap<gh_stars>0
import matplotlib.pyplot as plt
from scipy.stats import linregress
import numpy as np
# priprava dat
samples = 10
noise = 2
x = np.linspace(0, 10, samples)
# puvodni primka
y = 3 + 2 * x
# pridame sumiky
noise = np.random.randint(-noise, noise, samples)
test = y + noise
# linregres... |
import string
import sys
from scipy import interpolate
def print_err(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def load_k(file):
f = open(file, 'r')
lines = f.readlines()
f.close()
val = [[], []]
for line in lines:
tokens = line.split(',')
val[0].append(float(... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
################################################################################
#
# CoCoPy - A python toolkit for rotational spectroscopy
#
# Copyright (c) 2016 by <NAME> (<EMAIL>).
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this sof... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import compress
import os
import numpy as np
import scipy as sp
from scipy import stats
import sys
import time
import ctypes
import itertools
import statplot
class SampleInfo(object):
def __init__(self):
#SN Files samplename classid classname
self.samplenum = 0
... |
import scipy.io as sio
import numpy as np
import os
import mne
from mayavi import mlab
sess = 1
sub = 1
dataname = 'sess%02d_subj%02d_EEG_MI.mat' % (sess, sub)
path = 'C:/Data_MI/' + dataname
MI_s1 = sio.loadmat(path,struct_as_record=False,squeeze_me=True)
temp = MI_s1['EEG_MI_train']
sfreq = 1000 # Sampling freque... |
from typing import List
from sympy.matrices.dense import MutableDenseMatrix
class matSolver:
def __init__(self, mat: MutableDenseMatrix) -> None:
self.mat: MutableDenseMatrix = mat
self.course: List = []
self.dim: int = mat.shape[0]
def get_course(self) -> list:
return self.co... |
import caffe
import numpy as np
import argparse, pprint
import scipy.misc as scm
from os import path as osp
from easydict import EasyDict as edict
import time
import glog
import pdb
import pickle
import matplotlib.pyplot as plt
import copy
class GaussRenderLayer(caffe.Layer):
@classmethod
def parse_args(cls, argsStr... |
from collections import defaultdict
from consts import CLUSTERED_SUBSTITUTIONS_MIN_SIZE
from consts import WTS_MIN_PERCENT
import math
from itertools import product
from scipy.special import comb
import numpy as np
def binom(n, k, p):
return comb(n, k, exact = True) * (p ** k) * (1 - p) ** (n - k)
def generate_... |
# This file is part of the pyMOR project (http://www.pymor.org).
# Copyright 2013-2019 pyMOR developers and contributors. All rights reserved.
# License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
"""This module contains algorithms for the empirical interpolation of |Operators|.
The main work ... |
<gh_stars>100-1000
import pytest
import numpy as np
from scipy.special import erf
from pypeit.core import moment
def test_basics():
c = [45,50,55]
img = np.zeros((len(c),100), dtype=float)
x = np.arange(100)
sig = 5.
for i,_c in enumerate(c):
img[i,:] = (erf((x-c[i]+0.5)/np.sqrt(2)/sig) ... |
<gh_stars>1-10
#!/usr/bin/env python3
# Author: <NAME>
import os
import glob
import argparse
import numpy as np
from osgeo import gdal
import isce
import isceobj
from scipy.interpolate import griddata
import shelve
import datetime
import time
from Network import Network
def cmdLineParser(iargs = None):
'''
... |
<reponame>adrn/totoro
import astropy.units as u
import numpy as np
from scipy.optimize import minimize
import gala.integrate as gi
import gala.dynamics as gd
from .potentials import potentials, galpy_potentials
from .config import vcirc
from .actions_o2gf import get_o2gf_aaf
from .actions_staeckel import get_staeckel_... |
<filename>deepspeech_pytorch/gauss.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri May 21 10:29:44 2021
@author: louisbard
"""
from scipy.stats import norm
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
def gaussrep(seq):
# print(seq.size()
lenght... |
<reponame>churchill-lab/alntools<gh_stars>1-10
# -*- coding: utf-8 -*-
from six import iteritems
import csv
import os
import re
import tempfile
import time
import numpy as np
from scipy.sparse import diags
from .matrix.AlignmentPropertyMatrix import AlignmentPropertyMatrix as APM
from . import bam_utils
from . impo... |
import pandas as pd
import numpy as np
from scipy.optimize import minimize
def change_char(x:'String to me modify'):
try:
x = ''.join(ch for ch in x if ch not in ['*'])
except:
pass
return x
def port_emv(Eind:"Vector with returns ", rf: "reference return free risk", Sigma: "Variance Covar... |
# Copyright 2022 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
"""
Scripts reads in sea ice thickness data from CS-2 corrected/uncorrected
and plots a trend analysis over the 2011-2017 period (April)
Notes
-----
Author : <NAME>
Date : 16 January 2018
"""
### Import modules
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as c
import datetime... |
<gh_stars>1000+
# coding: utf-8
import ctypes
from os import environ
from pathlib import Path
from platform import system
import numpy as np
from scipy import sparse
def find_lib_path():
if environ.get('LIGHTGBM_BUILD_DOC', False):
# we don't need lib_lightgbm while building docs
return []
c... |
# Copyright 2018 The TensorFlow Authors All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... |
from typing import List
from scipy.interpolate import griddata
import numpy as np
from subsurface.structs import UnstructuredData, StructuredData
def interpolate_unstructured_data_to_structured_data(ud: UnstructuredData, attr_name: str,
resolution: List[int] = No... |
<gh_stars>0
import numpy as np
import scipy.io as io
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import sys
from args import args, device
dir = './plot/'
dir_1 = './result_data/'
dir_2 = './result_data/'
dir_3 = './result_data/'
ntrain = 64
# img_val = 7
if args.kle == ... |
import numpy as np
import torch
import scipy.sparse as sp
from .normalization import fetch_normalization
def sparse_mx_to_torch_sparse_tensor(sparse_mx):
"""Convert a scipy sparse matrix to a torch sparse tensor."""
sparse_mx = sparse_mx.tocoo().astype(np.float32)
indices = torch.from_numpy(
np.vs... |
#!/usr/bin/env python3
# @Author: *******
# @E-mail: ********
# @Last Modified by: ********
# @Last Modified time: 2021-04-22 08:42:54 23:22:34
# -*- coding: utf-8 -*-
import os
import psutil
import time
import torch
import math
import numpy as np
import pandas as pd
import scanpy as sc
import sc... |
<filename>verification/testD/compute.py<gh_stars>10-100
import math
import numpy as np
from scipy.integrate import trapz, cumtrapz
import matplotlib
matplotlib.use("PDF") # non-interactive plot making
import matplotlib.pyplot as plt
import os
ym=30000.
nu=0.3
alpha=10.0e-06
theta_edge= 0.6*166.667
sig_theta_e = ym *... |
from __future__ import division
import warnings
from pycircstat import CI
from pycircstat.iterators import index_bootstrap
import numpy as np
from scipy import stats
import pandas as pd
class BaseRegressor(object):
"""
Basic regressor object. Mother class to all other regressors.
Regressors support indexi... |
<gh_stars>1-10
# Copyright 2021 The ParallelAccel Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless r... |
<filename>arboretum/gbm.py<gh_stars>1-10
'''
Gradient Boosting models for least-squares and bernoulli models.
author: <NAME>
date: September 2017
'''
import numpy as np
from . import tree
from .base import BaseModel
from scipy.special import expit, logit
class GBM(BaseModel):
'''
GBM is a base class for grad... |
<gh_stars>0
#!/usr/bin/python
# -*- coding:utf-8 -*-
# @author : east
# @time : 2021/4/13 17:24
# @file : rfdist.py
# @project : ML2021
# @software : Jupyter
from scipy.cluster.hierarchy import to_tree, leaves_list
# Functions
# ---------
def get_leaves_num(Z):
return len(leaves_list(Z))
def tree_t... |
<gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 16 13:54:14 2019
@author: mengmi
"""
#%env CUDA_VISIBLE_DEVICES=2
import torch
from torchvision import models, transforms
import numpy as np
import os
import torch.nn as nn
import scipy.io as sio
from PIL import Image
#from matplotlib ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.