text string |
|---|
<filename>simulation/sim_utils/policy.py
from abc import abstractmethod
from scipy.special import softmax
import numpy as np
import statsmodels.api as sm
import torch.nn as nn
import torch.nn.functional as F
import torch
from torch import optim
from torch.distributions import Normal
from tqdm.auto import tqdm
def ve... |
<filename>common/image_utils.py
"""Image utils."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import cv2
import io
import matplotlib.pyplot as plt
import numpy as np
import PIL
import PIL.ExifTags
import scipy.ndimage as ndimage
import tensorflow as tf... |
<reponame>Jianyang-Hu/numpypractice<filename>images_0430.py
# -*- coding: utf-8 -*-
# @version : Python3.6
# @Time : 2017/4/30 15:58
# @Author : Jianyang-Hu
# @contact : <EMAIL>
# @File : images_0430.py
# @Software: PyCharm
#scipy.ndimage图像处理
from scipy import misc
import numpy as np
import matplotlib.pyplot as... |
import statistics
import string
import umpy_utils as utl
def is_temp_extreme(max_min_temps, max=70, min=50):
"""Return list of daily temperatures that falls between the specified
< min > and < max > temperature range (inclusive).
Parameters:
max_min_temps (list): daily max and min temperatures
... |
from pathlib import Path
import numpy as np
from scipy import ndimage
from self_supervised_3d_tasks.data.generator_base import DataGeneratorBase
import os
class SegmentationGenerator3D(DataGeneratorBase):
def __init__(
self,
data_path,
file_list,
batch_size=8,
... |
import tensorflow as tf
import tensorflow_quantum as tfq
import cirq
import sympy
import numpy as np
import matplotlib.pyplot as plt
import networkx as nx
from itertools import combinations
def to_dec(x):
return int("".join(str(i) for i in x), 2)
nodes = 14
regularity = 6
maxcut_graph = nx.random_regular_graph(n... |
<reponame>yaoqi-zd/SGAN
from __future__ import print_function
from __future__ import division
import json
import time
import pickle
from scipy.ndimage import zoom
import cv2
# import caffe
import math
from ipdb import set_trace
import numpy as np
import os.path as osp
from random import shuffle
import random
# clas... |
#Simple script for poking around CovCountyHospitalTimeSeries.csv
#<NAME>
import sys
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy import stats
sys.path.append('..')
import lib
CCH = lib.loadCCHTimeSeries()
beds = CCH['beds'].to_numpy()
population = CCH['popul... |
#!/usr/bin/env python
from snpy import *
from numpy import *
import sys,os,string
from snpy.filters import standards
from snpy.filters import standard_mags
import scipy
# Filters to process
fs = ['rk','ik']
# dictionary of natural magnitudes
sm = {}
sloan_mags = standard_mags['Smith']
BD17 = standards['Smith']['bd1... |
from scipy import ndimage
import tensorflow as tf
from spatial_transformer import AffineVolumeTransformer
import numpy as np
import scipy.misc
import binvox_rw
import sys
def read_binvox(f):
class Model:
pass
model = Model()
line = f.readline().strip()
if not line.startswith(b'#binvox'):
... |
from phik import phik_matrix
import scipy.stats as ss
from sklearn import preprocessing
import numpy as np
import pandas as pd
# Returns an overview stats of the dataset
def get_data_stat(data):
"""
Parameter
data: a dataframe containing
Returns
dict_stats: dictionary containing all data statisti... |
<filename>code/dtw.py
import numpy as np
import pylab as pl
import scipy.interpolate as it
# Auxiliary functions
def get_mirror(s, ws):
"""
Performs a signal windowing based on a double inversion from the start and end segments.
:param s: (array-like)
the input-signal.
:param ws: (integer)... |
# -*- coding: utf-8 -*-
from datetime import datetime, timedelta
from statistics import mean
from chaoslib.exceptions import FailedActivity
from chaoslib.types import Configuration, Secrets
from logzero import logger
from chaosaws import aws_client
__all__ = ["get_alarm_state_value", "get_metric_statistics", "get_me... |
import unittest.mock
from ConfigSpace import EqualsCondition
import scipy.optimize
import numpy as np
import sklearn.datasets
import sklearn.model_selection
from smac.configspace import (
ConfigurationSpace,
UniformFloatHyperparameter,
CategoricalHyperparameter,
convert_configurations_to_array,
)
from... |
# -*- coding: utf-8 -*-
"""
@Time : 2020/3/27 下午1:03
@File : test_RSRS.py
@author : pchaos
@license : Copyright(C), pchaos
@Contact : <EMAIL>
"""
import unittest
from unittest import TestCase
import pandas as pd
import os
import datetime
import numpy as np
import statsmodels.formula.api as sml
import matplotli... |
<filename>my_submissions/metaTuSOT/optimizer.py
import warnings
from copy import copy, deepcopy
import numpy as np
from poap.strategy import EvalRecord
from pySOT.experimental_design import SymmetricLatinHypercube
from pySOT.optimization_problems import OptimizationProblem
from pySOT.strategy import SRBFStrategy
from ... |
from absl import app, flags, logging
import pandas as pd
import numpy as np
import scipy.io
import networkx
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch_geometric
from torch_geometric.data import DataLoader
from sklearn.model_selection import train_test_split, RepeatedStratifiedKFol... |
from __future__ import print_function
import torch
import math
from torch.utils.data import Dataset
from scipy.special import expit, erf
import numpy as np
import pickle
import argparse
# teacher forward call with gaussian noise
def teacher_predict(inp, w1, w2, ep, sig_w):
# print(ep)
h = np.dot(w1.data.numpy(), i... |
<filename>spectrum_helper/__init__.py<gh_stars>10-100
import numpy as np
from scipy import signal
from scipy.io import wavfile
import json
from os import path, makedirs
from time import time
fs = 44100
nperseg = 2**9
window = 'hann'
# noverlap = 512
sampleLen = 20
sampleDelta = 60
def transform_signal(x):
f, t,... |
import numpy as np
from typing import List, Callable, Union, Optional, Any
from scipy.special import digamma
import lmfit as lm
import pandas as pd
from scipy.signal import savgol_filter
import logging
from ... import core_util as CU
from . import dat_attribute as DA
logger = logging.getLogger(__name__)
FIT_NUM_BINS ... |
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 14 11:55:08 2018
@author: <NAME>
"""
import pytest
import itertools
import numpy as np
import pandas as pd
import scipy.sparse as sps
from sklearn.datasets import make_blobs
from sklearn.linear_model import Ridge
from sklearn.base import is_classifier, is_regressor
fro... |
""" Use iDR3 zero points and field corrections to calibrate stamps. """
import os
import numpy as np
from astropy.io import fits
from astropy.table import Table, vstack
from scipy.interpolate import RectBivariateSpline
from tqdm import tqdm
import context
def get_zps():
""" Load all tables with zero points for i... |
import csv
from statistics import mean
from collections import OrderedDict
with open('/home/naeim/Desktop/task2.csv') as f:
lst1=list()
dic1=dict()
lst2=list()
for line in f:
lst1.append(line.split())
for item in lst1:
dic1[float(item[1])]=item[0]
for key in dic1.keys()... |
<filename>src/sctools/count.py<gh_stars>10-100
"""
Construct Count Matrices
========================
This module defines methods that enable (optionally) distributed construction of count matrices.
This module outputs coordinate sparse matrices that are converted to CSR matrices prior to delivery
for compact storage, ... |
# -*- coding: utf-8 -*-
from Voicelab.pipeline.Node import Node
from parselmouth.praat import call
from Voicelab.toolkits.Voicelab.VoicelabNode import VoicelabNode
import numpy as np
from scipy.fftpack import fft
from scipy.interpolate import interp1d
from scipy.io import wavfile
from scipy.io.wavfile import read as wa... |
#-*- encoding:utf-8 -*-
'''
Created on 2014年12月16日
@author: GongYu
'''
from utils.feature_select import select_feature
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_extraction.text import CountVectorizer
from sklearn import cross_validation
from sklearn.linear_model impor... |
<filename>lstm_pca.py
from os.path import join
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.stats import zscore
from sklearn.decomposition import PCA
import pandas as pd
from itertools import combinations
from statistical_tests import bootstrap_test, fisher_mean
from statsmodels.s... |
<gh_stars>1-10
# Prim's maximal spanning tree algorithm
# Prim's alg idea:
# start at any node, find closest neighbor and mark edges
# for all remaining nodes, find closest to previous cluster, mark edge
# continue until no nodes remain
#
# INPUTS: graph defined by adjacency matrix, nxn
# OUTPUTS: matrix specifying ... |
<reponame>louis-she/ignite
import os
import re
from unittest.mock import patch
import pytest
import pytorch_fid.fid_score as pytorch_fid_score
import scipy
import torch
from numpy import cov
import ignite.distributed as idist
from ignite.metrics.gan.fid import FID, fid_score
@pytest.fixture()
def mock_no_scipy():
... |
from __future__ import print_function
import glob
import os, sys
os.environ["CUDA_VISIBLE_DEVICES"] = ""
from tqdm import tqdm
import numpy as np
from random import shuffle, random
from os.path import expanduser
from pathos.multiprocessing import ProcessPool as Pool
from scipy.io import loadmat
from scipy.misc import i... |
# Author: <NAME>, <NAME>
# Summer 2015
from __future__ import division,absolute_import,print_function,unicode_literals #for Python 2.7
#from pylab import *
from scipy.special import wofz,jn,ive
from scipy.optimize import fsolve,root,newton
from numpy import amin,matrix,tile,linspace,repeat,empty,log10,sqrt,... |
from scipy.spatial import KDTree
from collections import Counter
class SimpleKnn:
def __init__(self, n_neighbors=5):
self.n_neighbors = n_neighbors
self.pred_neighbors = None
def fit(self, X, y):
self.X = X
self.y = y
self.tree = KDTree(X, 30)
# [5.1 3.5]
... |
import unittest
from fractions import Fraction
from rdflib import ConjunctiveGraph, Graph, Literal, URIRef
class TestIssue953(unittest.TestCase):
def test_issue_939(self):
lit = Literal(Fraction("2/3"))
assert lit.datatype == URIRef("http://www.w3.org/2002/07/owl#rational")
assert lit.n3(... |
# -*- coding: utf-8 -*-
import scipy.optimize
from numpy import *
import mab.gd.logging as logging
logger = logging.getLogger("gd.simplefit")
import emcee
from kaplot import *
#fitter = None
def lnprob(x, fitter):
print x, fitter
return fitter.logL(x)
class MCMCExplore(object):
def __init__(self, simplefit):
se... |
#--------------------------------------------------
#Create image script
#--------------------------------------------------
import scipy
from os import listdir
import numpy as np
import csv
from scipy.misc import imsave
import matplotlib.pyplot as plt
from scipy import interpolate
from scipy import stats
from scipy.... |
<reponame>ArkiWang/LeetcodePy
import copy
from cmath import inf, log
import numpy as np
class Solution:
suffix_list = None
tree_list = None
shuffle_list = None
op_list = None
num_list = None
flag = False
post_tree = None
post_trees = None
gen_combine_peer_layer = None
def which... |
"""Parse Tecan files, group lists and fit titrations.
(Titrations are described in list.pH or list.cl file.
Builds 96 titrations and export them in txt files. In the case of 2 labelblocks
performs a global fit saving a png and printing the fitting results.)
:ref:`prtecan parse`:
* Labelblock
* Tecanfile
:ref:`prte... |
import math
import datetime
import collections
import statistics
import itertools
def is_prime(num):
for i in range(2, int(math.sqrt(num)) + 1):
if num % i == 0:
return False
return True
def input_list():
ll = list(map(int, input().split(" ")))
return ll
tc = int(input())
for ... |
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/06_score.ipynb (unless otherwise specified).
__all__ = ['filter_score', 'filter_precursor', 'get_q_values', 'cut_fdr', 'cut_global_fdr', 'get_x_tandem_score',
'score_x_tandem', 'filter_with_x_tandem', 'filter_with_score', 'score_psms', 'get_ML_features', 'trai... |
<gh_stars>1-10
import numpy as np
from scipy.spatial.distance import euclidean
import heapq
def do_the_search(orchestra, sources_list, search_source, search_method, search_iterations, include_inst, include_tech, include_dyn, include_notes, overlap):
min_peaks_to_find=15
smallest = 10000
match = ''
rem... |
"""Series of checks to be performed on dataframes used as inputs of methods fit() and
transform().
"""
from typing import List, Union
import numpy as np
import pandas as pd
from scipy.sparse import issparse
def check_X(X: Union[np.generic, np.ndarray, pd.DataFrame]) -> pd.DataFrame:
"""
Checks if the input ... |
<gh_stars>1-10
'''
enet computes the elastic net estimator using the cyclic co-ordinate
descent (CCD) algorithm.
INPUT:
y : (numeric) 1darray of size N ( (output, respones)
if the intercept is in the model, then y needs to be centered.
X : (numeric) ndarray of size N x p (input, features)... |
<gh_stars>1-10
# Copyright 2015, Yahoo Inc.
# Licensed under the terms of the Apache License, Version 2.0. See the LICENSE file associated with the project for terms.
import os
import caffe
import numpy as np
from PIL import Image
import scipy
###################################
# Feature Extraction
#################... |
<reponame>horta/iseq
from math import log
from typing import Any, Dict, List, Sequence, Tuple
from hmmer_reader import HMMERProfile
from nmm import (
Alphabet,
Base,
BaseTable,
CodonTable,
GeneticCode,
LPROB_ZERO,
FrameState,
MuteState,
AlphabetTable,
lprob_normalize,
)
from .r... |
import numpy as np
import sympy as sp
from functools import singledispatch
import FIAT
from FIAT.polynomial_set import mis, form_matrix_product
import gem
from finat.finiteelementbase import FiniteElementBase
from finat.sympy2gem import sympy2gem
class FiatElement(FiniteElementBase):
"""Base class for finite e... |
<reponame>n-yoshikawa/automatic-differentiation-SCF
import time
import numpy
import matplotlib.pyplot as plt
from pyscf import gto, scf, ao2mo
import scipy
from scipy.optimize import minimize
import jax.numpy as jnp
from jax import grad, jit, random
from jax.config import config
config.update("jax_enable_x64", True)... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 24 18:28:16 2019
@author: hejme
"""
from os.path import join as join
import numpy as np
import scipy.misc as m
from tqdm import tqdm
import collections
import os
exists = os.path.isfile('/path/to/file')
files = collections.defaultdict(list)
for split in ["train", "val"]:... |
<filename>stex.py
import math
import re
import string
import gc
from itertools import repeat
from random import choice
from statistics import mean, stdev
from time import perf_counter
from publicize import public
from reindent import Indenter
RANDOMIZE_IDS = True
TEMPLATE = '''
from itertools import r... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 2 08:54:27 2021
@author: <NAME>
"""
"""
A class to manage a Gaussian basis for the Jolanta potential with l=1
Lots of helper functions not in the class to keep the legacy notebooks working.
"""
import numpy as np
import scipy.special
from scipy.... |
# simple model with gain method for separating 2 people speech
import numpy as np
import librosa
from sklearn.model_selection import train_test_split
import os
import scipy.io.wavfile as wavfile
# OPTION
TRAIN = 1
TEST = 0
INVERSE_CHECK = 0
# read the data in time domain and its sample rate
# path1 = '../../data/aud... |
from backport_collections import Counter
import imread
import numpy as np
import mahotas as mh
import random
from scipy.optimize import curve_fit
from scipy.spatial import distance
import skimage.measure
import tifffile as tif
import time
from matplotlib.pyplot import imshow
import matplotlib.pyplot as plt
from... |
#!/usr/bin/env python
# vim: set fileencoding=utf-8 ts=4 sts=4 sw=4 et tw=80 :
#
# First crack at a wavelength solution system.
#
# <NAME>
# Created: 2019-02-12
# Last modified: 2019-03-06
#--------------------------------------------------------------------------
#************************************************... |
<gh_stars>1000+
"""Newton-CG trust-region optimization."""
from __future__ import division, print_function, absolute_import
import math
import numpy as np
import scipy.linalg
from ._trustregion import (_minimize_trust_region, BaseQuadraticSubproblem)
__all__ = []
def _minimize_trust_ncg(fun, x0, args=(), jac=None,... |
<filename>synthetic_moments_ridge.py
import os
import torch
import torch.nn as nn
from torch.utils.data import Dataset
from sklearn.datasets import make_spd_matrix
from sklearn.covariance import empirical_covariance
from sklearn.metrics import mean_squared_error
from torch.utils.data import DataLoader
import numpy as n... |
# coding: utf-8
"""
.. _l-example-onnxruntime-logreg:
Benchmark of onnxruntime on LogisticRegression
==============================================
The example uses what :epkg:`pymlbenchmark` implements, in particular
class :class:`OnnxRuntimeBenchPerfTestBinaryClassification
<pymlbenchmark.external.onnxruntime_perf_... |
import functools
import logging
import pickle
import sys
import time
from collections import Counter
from datetime import datetime
from pathlib import Path
from typing import Dict
from typing import Set
from typing import Union, Tuple, List
import igraph as ig
import matplotlib.pyplot as plt
import networkx as nx
impo... |
from __future__ import division
import numpy as np
from glob import glob
import os, sys
import scipy.misc
CURDIR = os.path.dirname(__file__)
sys.path.append(os.path.abspath(os.path.join(CURDIR, '..')))
sys.path.append(os.path.abspath(os.path.join(CURDIR, '...')))
from geo_utils import scale_intrinsics
from common_util... |
<reponame>andreped/mri_brain_tumor_segmentation
import torch
from tensorflow.python.keras.models import load_model
import matplotlib.pyplot as plt
from scipy.ndimage import zoom
import os
from os.path import join
import numpy as np
import sys
from shutil import copy
from math import ceil, floor
from copy import deepcop... |
import autograd.numpy as np
from scipy.stats import uniform
from scipy.special import ndtri as z
from autograd.scipy.stats import norm
from scipy.stats import norm as scipy_norm
from surpyval import nonparametric as nonp
from surpyval import parametric as para
from surpyval.parametric.parametric_fitter import Parametri... |
#!/usr/bin/env python
# Licensed as BSD by <NAME> of the ESRF on 2014-08-06
################################################################################
# Copyright (c) 2014, the European Synchrotron Radiation Facility #
# All rights reserved. #
#... |
import numpy as np
import scipy.interpolate
from netCDF4 import Dataset
import pdb
class Data3d:
"""basic data element that contains a 3D (plevs/lat/lon) data field"""
def __init__(self,array3d=[],lon=[],lat=[],plevs=[],time=[],minv=-9e9):
"""Data3d(array[time,plevs,lat,lon], lon, lat, plevs, time,minv): 3D data ... |
import os
from library.temperature import c_to_f
def get_command_input():
print("Indoor Air Quality Monitoring Command Console\n")
print("Please select from the following options:")
print("(A) Add reading")
print("(B) List readings")
print("(C) Calculate")
print("(D) Exit\n")
command = input("Input... |
<filename>imate/trace/_eigenvalue_method.py
# SPDX-FileCopyrightText: Copyright 2021, <NAME> <<EMAIL>>
# SPDX-License-Identifier: BSD-3-Clause
# SPDX-FileType: SOURCE
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the license found in the LICENSE.txt file in the root
# ... |
import pandas as pd
import scipy.stats as ss
import numpy as np
import json
import seaborn as sns
from dython.nominal import theils_u, cramers_v
from AnalysisModule.routines.util import MDefined, read_jsonfile
import ast
indf = pd.read_csv("../../DataGeneration/5_SimpleInput/input.csv")
smiles2cluster = re... |
<reponame>kidist-amde/image-search-engine<gh_stars>0
import sys
sys.path.append('..')
from base import BaseSolution
import cv2
from tqdm import tqdm
import argparse
import numpy as np
from scipy import spatial
class Histogram:
def __init__(self, bins):
self.bins = bins
def detectAndCompute(self, image... |
"""
A Python interface to the simpler Lock Plume model.
"""
from numpy import zeros, ones, meshgrid, linspace, any, array, dot, arange, \
pi, sin, cos, arccos
from scipy import optimize as opt
from datetime import date, timedelta
from glob import glob
from MAPL.constants import *
from LockPlum... |
<filename>main.py
from scipy.ndimage import geometric_transform
from math import pi
from cmath import exp
import png
from base64 import b64decode
import requests
from struct import iter_unpack
def hi_c(z, x, y):
tile_id = 'CQMd6V_cRw6iCI_-Unl3PQ.{}.{}.{}'.format(z, x, y)
params = {
'd': tile_id,
... |
<reponame>pllim/halotools
"""
This module contains the template class `~halotools.empirical_models.OccupationComponent`,
which standardizes the form of the classes responsible for governing galaxy abundance
in all HOD-style models of the galaxy-halo connection.
"""
import numpy as np
from scipy.special import pdtrik
i... |
import numpy as np
from numpy import genfromtxt
import scipy
import Image
import matplotlib.pyplot as plt
class VhdlAPI:
source_bin_file = 'image_0_200x200_pad.min'
source_bin_path='binaries/'
def __init__(self, source_bin_path = source_bin_path, source_bin_file = source_bin_file):
self.source_bi... |
<filename>DSP_Task3/finalyarab.py
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'Task3GUIFINAL.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are... |
<gh_stars>100-1000
"""
Name : c6_26_beta_good.py
Book : Python for Finance (2nd ed.)
Publisher: Packt Publishing Ltd.
Author : <NAME>
Date : 6/6/2017
email : <EMAIL>
<EMAIL>
"""
from scipy import stats
from matplotlib.finance import quotes_historical_yahoo_ochl as getData
be... |
<gh_stars>1-10
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Approximates the cluster STIM relationships with power laws to estimate a
of n (i.e., the slope exponent in the stream power incision model)
Written by <NAME> for
"Low variability runoff inhibits coupling of climate, tectonics, and
topography in the G... |
import torch
import torch
import scipy as sp
import numpy as np
import argparse
from graphsaint.kgraphsaint import loader
from graphsaint.graph_samplers import edge_sampling
import time
print(torch.cuda.is_available())
|
<reponame>NewCPM/MCPM
import numpy as np
from scipy.optimize import minimize
from scipy.stats import sigmaclip
from os import path
import matplotlib.pyplot as plt
import sys
from MCPM import utils
from MCPM.cpmfitsource import CpmFitSource
def fun_2(inputs, cpm_source, t_E, f_s):
"""2-parameter function for opti... |
import sys
usrid = sys.argv[1]
import numpy as np
import MySQLdb as mdb
from scipy import sparse
from scipy.sparse.linalg import svds
from collections import defaultdict
from operator import itemgetter
def sparse_mean(mat, row = -1, column = -1):
# function to take means on a sparse matrix
if row != -1:
mat = ma... |
import os
import json
import numpy as np
import scipy
from scipy import io
class MPIIMeta:
def __init__(self,image_path,annos_list):
#print(f"test get meta with img_path:{image_path} annos_list:{annos_list}\n\n")
image_name=os.path.basename(image_path)
self.image_id=int(image_name[:image_na... |
<gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
from scipy import signal
import matplotlib.pyplot as plt
from scipy.special import expit
import json
import pandas as pd
import toml
import os
import sys
path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
sys.path.insert(1, ... |
<reponame>kozzion/tensealstat<gh_stars>1-10
import sys
import os
from scipy import stats
import tenseal as ts
import numpy as np
from scipy.stats import f
sys.path.append(os.path.abspath('../../tensealstat'))
from tensealstat.tools_context import ToolsContext as tc
from tensealstat.algebra.algebra_numpy import Algebr... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: © 2021 Massachusetts Institute of Technology.
# SPDX-FileCopyrightText: © 2021 <NAME> <<EMAIL>>
# NOTICE: authors should document their contributions in concisely in NOTICE
# with details inline in source files... |
<filename>Flower/utils.py
import numpy as np
import tensorflow as tf
import random
from skimage import feature, transform
import _pickle as pkl
import matplotlib.pyplot as plt
from pylab import rcParams
import scipy
import scipy.stats as stats
from tensorflow.python.ops import gen_nn_ops
from tensorflow.python.ops impo... |
<filename>sematch/evaluation.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright 2017 <NAME>- Grupo de Sistemas Inteligentes
# gzhu[at]dit.upm.es
# DIT, UPM
#
# 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... |
"""
This script performs Sparse PCA on the test datasets passed as parameter to
`sparse_pca()` function. The code is based on thunder-extraction NMF algorithm.
References:
-----------
1) www.github.com/thunder-project/thunder-extraction/blob/master/extraction/algorithms/nmf.py
2) https://github.com/thunder-pr... |
<reponame>aasensio/pyAndres
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 10 10:18:41 2014
@author: aasensio
"""
__all__ = ["AppForm"]
from PyQt4.QtGui import QMainWindow, QWidget, QApplication, QGridLayout
import sys
import os.path
import matplotlib.cm as cm
import numpy as np
import pyfits as pf
import scipy.io
... |
#coding:utf-8
#
# a class of gammatone (gammachirp) FIR filter
# filtering uses scipy overlap add convolution
import sys
import numpy as np
from matplotlib import pyplot as plt
from scipy import signal # scipy > 1.14.1
# Check version
# Python 3.6.4 on win32 (Windows 10)
# numpy 1.14.0
# matplo... |
<reponame>jonlwowski012/UGV-Wheel-Slip-Detection-Using-LSTM-and-DNN
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.layers import Embedding
from keras.layers import LSTM
from keras.optimizers import Adam
from keras import losses
from os import listdir
from os.path import join
from... |
<gh_stars>0
import time
import sympy
import platform
from fractions import Fraction as R
from scipy.special import comb
import signal
# https://stackoverflow.com/a/22348885/538379
if platform.system() == 'Windows':
class timeout:
def __init__(self, seconds=1, error_message='Timeout'):
self.secon... |
#!/usr/bin/env python3
import numpy as np
import os
import random
from time import time
import logging
import pickle
from scipy.spatial import cKDTree
from person import Person
from fleet import Fleet
from utils import get_random_els_with_reposition, MAX, copy_list_to_boolindexing
from utils import get_multiprocessin... |
<gh_stars>1-10
import helpermethods as helper
import numpy as np
import sys
import edgeml_pytorch.utils as utils
from edgeml_pytorch.graph.protoNN import ProtoNN
import torch
import time
import scipy
from antropy.antropy import entropy
from scipy.signal import periodogram, welch
import pandas as pd
# HyperParams
hyp... |
<reponame>jpmieville/sir
#!/usr/bin/env python
####################################################################
### This is the PYTHON version of program 7.2 from page 242 of #
### "Modeling Infectious Disease in humans and animals" #
### by Keeling & Rohani. #
### #
##... |
# -*- coding: utf-8 -*-
"""Helpful routine using the underlying Python functions
in 'statistics' and 'statsmodels' to handle common needs
in molecular modeling
"""
import logging
import random
import statistics
import statsmodels.tsa.stattools as stattools
logger = logging.getLogger(__name__)
def analyze_autocorre... |
<reponame>JudithVerstegen/scarabs-abm
import os
import numpy as np
from scipy.stats import chisquare
import json
import pyNetLogo
def run_simulation(experiment, default=False):
'''run a netlogo model
Parameters
----------
experiments : dict
'''
print('Experiment', experiment)
netlogo.c... |
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 2 17:49:51 2016
Author: <NAME>, University of Washington School of Oceanography, Seattle WA
Module for building age-depth profile from biostratigraphy or
magnetostratigraphy data of an ocean drilling site.
Boundaries between different sedimentation rate regimes are manua... |
import numpy as np
import scipy.io.wavfile as wav
import scikits.audiolab
import sys, glob
def padsig(sig, delay):
'''
Pad the signal at the end with a delay
'''
return np.append(sig[delay:], np.zeros(delay) )
def revsig(sig, delay):
'''
Reverse the delay given a single.
'''
if delay ... |
<reponame>AsimKhan2019/OpenAI-Lab
import numpy as np
import scipy as sp
from rl.preprocessor.base_preprocessor import PreProcessor
# Util functions for state preprocessing
def resize_image(im):
return sp.misc.imresize(im, (110, 84))
def crop_image(im):
return im[-84:, :]
def process_image_atari(im):
... |
""" Copyright (c) 2017-2020 ABBYY Production LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in wr... |
import unittest
import pysal
import scipy
import numpy as np
from pysal.spreg.ml_lag import ML_Lag
from pysal.spreg import utils
from pysal.common import RTOL
from skip import SKIP
@unittest.skipIf(SKIP,
"Skipping MLLag Tests")
class TestMLError(unittest.TestCase):
def setUp(self):
db = pysal.ope... |
import torch
import torch.nn as nn
from scipy.spatial.distance import cdist
import numpy as np
def train_target(args):
dset_loaders = digit_load(args)
## set base network
if args.dset == 'u2m':
netF = network.LeNetBase().cuda()
elif args.dset == 'm2u':
netF = network.LeNetBase().cuda() ... |
<reponame>Breadstwin/grblas<filename>grblas/tests/test_io.py
from io import BytesIO, StringIO
import numpy as np
import pytest
import grblas as gb
from grblas import Matrix
try:
import networkx as nx
except ImportError: # pragma: no cover
nx = None
try:
import scipy.sparse as ss
except ImportError: # p... |
# Code adapted from "upfirdn" python library with permission:
#
# Copyright (c) 2009, Motorola, Inc
#
# All Rights Reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must re... |
<reponame>DougBurke/naima<gh_stars>1-10
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import numpy as np
from astropy.tests.helper import pytest
from astropy.utils.data import get_pkg_data_filename
import astropy.units as u
from astropy.io import ascii
from ..core import (run_sampler, get_sampler, un... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.