text string |
|---|
<filename>src/main.py
# 2020.09.07
# finalized 2020.09.26
# @yifan
#
# use DCT/PCA as foreword kernel
# use pinv / Linear Regression find the optimal inverse transformation kernel
# write kerenel to txt file, manually copy the kernels to following array in files:
# fore_K in <jfdctflt.c>
# inv_K in <jidctflt.c>
# ... |
from numpy import linalg, zeros, ones, hstack, asarray, vstack, array, mean, std
import itertools
import matplotlib.pyplot as plt
from datetime import datetime
import pandas as pd
import numpy as np
import scipy
import matplotlib.dates as mdates
from sklearn.metrics import mean_squared_error
from math import sqrt
impor... |
# Copyright (c) 2019, <NAME> (<NAME>)
# Copyright (c) 2019, <NAME> (<NAME>)
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright noti... |
<filename>HAL/sampler.py
from scipy import random, stats
import numpy as np
class GMM():
"""
Simple GMM of n multivariate Gaussians, all with unit variance and equal weights
"""
def __init__(self, means):
"""
Input:
means = (N, d) shaped array of N center points in the d-dimens... |
#!/usr/bin/env python
import math
import os
import pygame
import numpy as np
from scipy.io import wavfile
pygame.mixer.init(44100, -16, 2, 4096)
keyNumbers = [89,90,91,92,93,94,95,96,97,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,4... |
<gh_stars>0
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 11 12:05:02 2016
@author: matthias
"""
import csv
import numpy as np
import scipy as sp
import matplotlib.colors as colors
import matplotlib.pyplot as plt
import os
import shutil
from multiprocessing import Pool
path="/Users/matthias/Documents/popdyn/botero... |
<reponame>ncostar/species-identification-thermal-imaging<filename>temperature_scaling/temperature_scaling.py
import numpy as np
import scipy
import tensorflow as tf
import tensorflow_probability as tfp
def find_scaling_temperature(labels, logits, temp_range=(1e-5, 1e5)):
"""Find max likelihood scaling temperature us... |
"""
Copyright 2019 <NAME>, <NAME>
This file is part of A2DR.
A2DR 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.
A2DR is distributed in t... |
"""
Plotting tool for the neutrino decoupling temperature
To Note:
- Check the data location for the two relevant files TdecAbundances.txt and TdecChisq.txt
- Outputs to pdf "Tdec.pdf"
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
import matplotlib
from utils import ge... |
<reponame>asokraju/sb3-seir
import gym
import numpy as np
import matplotlib.pyplot as plt
from itertools import permutations
import os
from scipy.io import savemat, loadmat
import pandas as pd
import seaborn as sns
import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from mat... |
#!/usr/bin/env python3
"""Particle filter localization example.
Author: <NAME>
Jan 2018
"""
from time import time, sleep
from collections import deque
from math import sqrt
import numpy as np
from scipy.stats import norm as gauss1d
from ssd_robotics import Vehicle, draw, mpi_to_pi, in2pi, sample_x_using_odometry
... |
# -*- coding: utf-8 -*-
import random
import numpy as np
from scipy import integrate
from scipy import special
from nose.tools import assert_almost_equal, assert_warns_regex
from .. import HRG, species_dict
hbarc = 0.1973269788
def test_hrg():
ID, info = random.choice(list(species_dict.items()))
m = inf... |
"""
Adapted from <NAME>:
[1] https://www.mwm.im/lqr-controllers-with-python/
[2] https://github.com/markwmuller/controlpy
"""
import scipy.linalg as LA
def lqr(A, B, Q, R):
"""
Solve for the LQR controller for a continuous time system.
A and B are matrices, describing the system dynami... |
<gh_stars>0
# Note: The codes were originally created by Prof. <NAME> in the MATLAB
import numpy as np
from scipy.stats import norm
from gmpe_bjf97 import gmpe_bjf97
###################
### Description ###
###################
# The probability of exceeding a given PGA level x, using the BJF GMPE.
################... |
# Copyright (c) 2017, CNRS-LAAS
# 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 retain the above copyright notice, this
# list of conditions and the f... |
<gh_stars>1-10
#!/usr/bin/env python3
import time
import math
from datetime import datetime
from time import sleep
import numpy as np
import random
import cv2
import os
import argparse
import torch
from scipy.spatial.transform import Rotation as R
import sys
sys.path.append('./Eval')
sys.path.append('./')
from env_5... |
<filename>src/anmi/T2/funcs_LUD.py
import numpy as np
from ..genericas import print_verbose, matriz_inversa
from sympy import zeros, eye, simplify, sqrt
def permutacion_matriz(U, fila_i, idx_max, verbose=False, P=None, r=None):
"""Efectua una permutación por filas de una matriz
Args:
U (matriz): MAtr... |
import plotly.figure_factory as ff
import plotly.graph_objects as go
import plotly.express as px
import statistics as st
import random as rd
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_te... |
<reponame>BrendenBarbour/necstlab-damage-segmentation
import os
from scipy.optimize import minimize_scalar
import tensorflow as tf
import numpy as np
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.metrics import (Accuracy as AccuracyTfKeras, BinaryAccuracy, CategoricalAccuracy,
... |
<reponame>probcomp/hierarchical-irm
# Copyright 2021 MIT Probabilistic Computing Project
# Apache License, Version 2.0, refer to LICENSE.txt
from scipy.io import loadmat
# Animals as a single binary relation"
# has: Animals x Features -> {0,1}
x = loadmat('50animalbindat.mat')
features = [y[0][0] for y in x['featur... |
<gh_stars>1-10
from numpy.testing import assert_array_almost_equal, TestCase, run_module_suite
import numpy as np
from scipy.optimize import fmin_slsqp
class TestSLSQP(TestCase):
"""Test fmin_slsqp using Example 14.4 from Numerical Methods for
Engineers by <NAME> and <NAME>. This example
maximizes the ... |
# <NAME>, <NAME> finished
#
#
# 2019-11-16
# -----------------------------------------------------------------------------
# This function calcultes the CRPS between an ensemble and one observation.
#
# input:
# calculation: mxn matrix; m = number of simulations
# ... |
<reponame>Xin-Ye-1/HRL-GRG<gh_stars>1-10
#! /usr/bin/env python
import tensorflow as tf
import tensorflow.contrib.slim as slim
import numpy as np
import sys
sys.path.append('..')
from utils.constant import *
flags = tf.app.flags
FLAGS = flags.FLAGS
class Scene_Prior_Network():
def __init__(self,
... |
import sys
sys.path.append("../src/")
import numpy as np
import MaxwellBoltzmann as MB
from numpy import pi
from scipy.integrate import quad, trapz
from matplotlib.ticker import MultipleLocator, FormatStrFormatter
import utils
from scipy.interpolate import interp2d, interp1d
from matplotlib import cm
#Matplotlib ----... |
<gh_stars>1-10
# -
'''_____Standard imports_____'''
import numpy as np
import scipy.signal
'''_____Project imports_____'''
from src.toolbox._arguments import Arguments
def hilbert(spectra: np.array):
return scipy.signal.hilbert(spectra)
def unwrap_phase(spectra: np.array):
temp = hilbert(spectra)
... |
#!/usr/bin/python3
import datetime
import pandas as pd
from scipy import stats
from alpha_vantage.timeseries import TimeSeries
from currency_converter import CurrencyConverter
API_KEY = "<KEY>"
symbols = ["UBER"]
class Data:
def __init__(self, key, symbol):
"""Initialize variables and Alpha Vantage AP... |
<gh_stars>1-10
# -*- coding: utf-8 -*-
import os, sys
import argparse
import numpy as np
import toml
import h5py
import tqdm
import scipy.spatial as spatial
from scipy.optimize import minimize_scalar
from scipy.interpolate import LinearNDInterpolator
from scipy.interpolate import NearestNDInterpolator
from scipy.interp... |
<reponame>neurospin/nipy
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
##############################################################################
# Random Thresholding Procedure (after <NAME> and <NAME>)
import numpy as np
import scipy.stats as st... |
# Hierarchical Clustering
# Import libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Import dataset
dataset = pd.read_ ('')
X = dataset.iloc[:, [3, 4]].values
# Employ dendrogram to find the optimal number of clusters
import scipy.cluster.hierarchy as sch
dendrogram = sch.dendrogram(... |
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import gaussian_kde
def plot_prediction_density(
y_true, scores, figsize=(8,5),
title='Prediction Density Plot',
colors=['red', 'blue']):
class_set = sorted(set(y_true))
x_grid = np.linspace(0, 1, 1000)
fig, ax =... |
"""
Run to generate figures for presentation.
Requires TeX; may need to install texlive-extra-utils on linux
Requires xppy and Py_XPPCall
the main() function at the end calls the preceding individual figure functions.
figures are saved as both png and pdf.
Copyright (c) 2016, <NAME>, <NAME>
All rights rese... |
import torch
from torch.utils.data import DataLoader
import numpy as np
import scipy.io as sio
from .utils import TedataLoader, get_PSNR, get_SSIM, inverse_gat, gat, normalize_after_gat_torch
from .unet import est_UNet
import time
torch.backends.cudnn.benchmark=True
class Test_PGE(object):
def __init__(self,_t... |
''' In this script we do projections of the impact reducing within- and
between-household transmission by doing a 2D parameter sweep'''
from argparse import ArgumentParser
from os.path import isfile
from pickle import load, dump
from copy import deepcopy
from multiprocessing import Pool
from numpy import arange, arra... |
"""
This file is dedicated to the static nonconvex problem taking into consideration the transmission losses B
It concerns the First order solvers
Author: <NAME>
Date : 09/06/2020
"""
import numpy as np
import gurobipy as gp
from gurobipy import GRB
import time
import matplotlib.pyplot as plt
from ... |
<reponame>harry-zuzan/trprimes
"""
Programming problems related to prime numbers. A good source of fodder
for number theory and prime number problems is the youtube channel
https://www.youtube.com/user/numberphile
"""
from collections import namedtuple
from sympy import isprime
# this produces the left truncatable p... |
<reponame>feedbackward/spectral
'''Setup: loss functions used for training and evaluation.'''
## External modules.
from copy import deepcopy
import numpy as np
from scipy.special import erf
## Internal modules.
from mml.losses import Loss
from mml.losses.absolute import Absolute
from mml.losses.classification import ... |
#!/usr/bin/env python
import os
import sys
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.io import loadmat
from skimage import color
from skimage import io
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHotEncoder
import h5py
import tenso... |
<gh_stars>1-10
#!/usr/bin/env python
# Representation and basic operations for array data; more general
# than a Network to allow for testing, applications to bipartite graphs, etc.
# <NAME>, 4/4/2013
import numpy as np
import scipy.sparse as sparse
from Covariate import NodeCovariate, EdgeCovariate
class Array:
... |
<gh_stars>0
import os
import unittest
from tempfile import TemporaryDirectory
import pandas as pd
from scipy.stats import entropy
from hetnetana import *
from hetnetana.generation.generate import *
from hetnetana.generation.generate_toy import convert_simple_to_terminal
from hetnetana.struct import hetnet_examples
fr... |
import numpy as np
import scipy
class FreqResponse(object):
def __init__(self, freq, Hs,cohers = None,trims = None):
self.freq = freq
self.Hs = Hs
self.coherens = cohers
self.trims = trims
pass
|
<filename>deep_models.py
import numpy as np
from os import path
import scipy.io
from pdb import set_trace as bp #################added break point accessor####################
from scipy.signal import lfilter
try: # SciPy >= 0.19
from scipy.special import comb, logsumexp
except ImportError:
from scipy.misc im... |
import numpy as np
from numpy import linalg as la
from scipy.spatial import distance
from sklearn.metrics.pairwise import cosine_similarity
A = np.random.normal(0, 1, size=(300, 300))
B = np.random.normal(0, 1, size=(300, 300))
C = A.dot(B)
A_norm = la.norm(A)
B_norm = la.norm(B)
cos_sim = cosine_similarity(A, B)
prin... |
################################################
## EE559 HW Wk2, Prof. Jenkins, Spring 2018
## Created by <NAME>, TA
## Tested in Python 3.6.3, OSX El Captain
################################################
import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial.distance import cdist
def plotDecBounda... |
import scipy.stats as stats
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
class LexIndEval(object):
"""Class to evaluate Lexicon Induction.
"""
def __init__(self, gt, pred):
"""Initalize the wrapper
Args:
gt: ground truth lexicon [(word1,... |
<filename>SHAPE/model.py
#!/usr/bin/env python3
import numpy as np
import scipy as sp
from scipy.optimize import minimize
import pandas as pd
import matplotlib.pyplot as plt
import math
import emcee
import corner
import pickle
import tkinter as tk
import matplotlib.font_manager
from tkinter import simpledialog
from tki... |
#!/usr/bin/env python3
import os
import time
import scipy
import mnist
import pickle
import matplotlib
import numpy as np
import itertools as it
from numpy import random
matplotlib.use("agg")
from matplotlib import pyplot as plt
from scipy.special import softmax
mnist_data_directory = os.path.join(os.path.dirname(__f... |
<reponame>wilsonchingg/dnn-speech-enhancement
import sys, os, json, math, random, numpy as np
from scipy.io.wavfile import read, write
with open(os.path.join(os.path.dirname(__file__), '../config.json')) as f:
SAMPLING_RATE = json.load(f)["sampling_rate"]
SNR = None
def set_snr(_snr):
global SNR
SNR = _snr
# Con... |
<filename>src/models/users/bouncer/bouncer.py
"""
Bouncers / Security Guards Module
module inherits from user and add bouncer specific functionality
"""
__developer__ = "mobius-crypt"
__email__ = "<EMAIL>"
__twitter__ = "@blueitserver"
__github_profile__ = "https://github.com/freelancing-solutions/"
__lice... |
<filename>dist_pd/optimal_paramset.py
import tensorflow as tf
import numpy as np
from scipy.optimize import minimize
eps = 0.001
cons_unbdd = ({'type': 'ineq', 'fun': lambda x: x[0]-eps},
{'type': 'ineq', 'fun': lambda x: 1-eps-x[0]},
{'type': 'ineq', 'fun': lambda x: x[1]-eps},
{'type': 'ine... |
import tkinter as tk
import numpy as np
import winsound
from scipy import signal
from scipy.io import wavfile
from PIL import Image, ImageTk
from os import getcwd, path
from spectrograph.plots import WavePlot, SpectrumPlot
class Menubar(tk.Menu):
"""Create a functional menubar in application."""
INFO = (
... |
import os.path as osp
import numpy as np
import scipy.sparse as sp
import networkx as nx
import pandas as pd
import os
import torch
import torch_geometric.transforms as T
from torch_geometric.data import Data
from torch_geometric.utils import to_undirected, is_undirected, to_networkx
from networkx.algorithms.component... |
import glob
from matplotlib import pyplot as plt
import numpy as np
import os
import readline
from scipy.misc import imread
import tensorflow as tf
import time
import model
from inputs.detection.inputs import resize_image_maintain_aspect_ratio
def test(bbox_priors, checkpoint_dir, specific_model_path, cfg):
gr... |
<filename>matmodlab2/core/database.py
import os
import re
import datetime
import numpy as np
from scipy.io.netcdf import NetCDFFile
COMPONENT_SEP = '.'
def read_exodb(filename):
db = DatabaseFileReader(filename)
return db.df
def read_npzdb(filename):
from pandas import DataFrame
f = np.load(filename,... |
"""
Transcritical flow over a bump with a shock.
Ref1: Houghton & Kasahara, Nonlinear shallow fluid flow over an isolated ridge.
Comm. Pure and Applied Math. DOI:10.1002/cpa.3160210103
Ref2: Delestre et al, 2012, SWASHES: a compilation of shallow water
analytic solutions..., Int J Numer Meth Fluids, DOI:10.1002/... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on July 10, 2019
@author: <NAME> <<EMAIL>>
@author: <NAME> <<EMAIL>>
"""
from typing import Optional
import numpy as np
from scipy import sparse
def membership_matrix(labels: np.ndarray, dtype=bool, n_labels: Optional[int] = None) -> sparse.csr_matrix:
"... |
# -*- coding: utf-8 -*-
from Batch_MRF_Helpers import inf_label_latent_helper
from MrfTypes import BatchExamplesParser, Options
from Utils.IOhelpers import _load_grabcut_unary_pairwise_cliques
import pickle
import matplotlib.pyplot as plt
import numpy as np
import scipy as sp
__author__ = 'spacegoing'
path = './expDa... |
import re
import sys
import os.path as op
import numpy as np
import neuroseries as nts
SIZE_HEADER = 1024 # size of header in B
NUM_SAMPLES = 1024 # number of samples per record
SIZE_RECORD = 2070 # total size of record (2x1024 B samples + record header)
REC_MARKER = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 255], dtype... |
import numpy as np
from numpy import newaxis as nax
from numpy import atleast_3d
from scipy.fftpack import idst, dst
# from ase.data import atomic_masses
class Projector:
"""
Coordinate transformation using projector function
projecting force requires to return forces and coordinate
because of double... |
<gh_stars>1-10
import numpy as np
from scipy.io import loadmat
from scipy.sparse import csc_matrix
from scipy.sparse.linalg import factorized
## reading post-fault initial condition from the mat-file
temp = loadmat('./data/init_ne.mat', struct_as_record=True)
X0 = temp['X']
Vbus0 = temp['Vbus']
nobus = len(Vbus... |
<filename>LLC_Membranes/timeseries/msd.py
#! /usr/bin/env python
import os
import sys
import argparse
import numpy as np
import mdtraj as md
import matplotlib.pyplot as plt
from LLC_Membranes.analysis import Poly_fit, top
from LLC_Membranes.llclib import physical, topology, timeseries, fitting_functions, atom_props, f... |
######
#imports
######
# general
import statistics
import datetime
from sklearn.externals import joblib # save and load models
import random
# data manipulation and exploration
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
## machine learning stuff
# preprocessing
from sklear... |
import autograd.numpy as np
import scipy.sparse as sparse # for testing
import sys, time
try:
from . import csc, ltvsystem
except:
import csc, ltvsystem
class LTVMPC:
'''Interface that the provided "model" must provide:
- getLinearDynamics(y, u)
- dynamics(y, u) - if ITERATE_TRAJ is selected
'... |
<reponame>valmel/smashpy
#!/usr/bin/env python
# cython: profile = True
from smash.models import MF
import scipy.io as io
#import cProfile
##################
# make a choice
##################
#dataset = 'movielens'
dataset = 'chembl'
#normalizeGradients = False
normalizeGradients = True
#sideInfo = False
sideInfo =... |
# -*- coding: utf-8 -*-
"""
This module contains auxiliary code which might be useful in interactive sessions
"""
import sympy as sp
def multi_str_replace(s, tup_list):
"""
performs mutltiple consecutive replacements on one string
tup_list: list of 2-tuples [(old1, new1), (old2, new2), ...]
return... |
<filename>03_autoencoding_and_tsne.py<gh_stars>10-100
'''
This script trains an autoencoder on every csv file containing the Mel
spectrogram data for a list of songs. The learned latent features are then
used to cluster the songs with t-SNE
Artist information will be used to color the clusters to see how accurate
clu... |
import os
import numpy as np
from matplotlib import pyplot as plt
from scipy import stats as st
import sys
res_kb = int(sys.argv[1])
if os.path.isfile("polycomb_enrichment.txt"):
os.system("rm polycomb_enrichment.txt")
if os.path.isfile("enhancer_enrichment.txt"):
os.system("rm enhancer_enrichment.txt")
chroms = ... |
<filename>partial_dependency.py
from __future__ import print_function
import sklearn
import pandas as pd
import numpy as np
#from sklearn.ensemble.partial_dependence import plot_partial_dependence
#from sklearn.ensemble.partial_dependence import partial_dependence
from scipy.stats.mstats import mquantiles
from sklea... |
import numpy as np
from foolbox2.criteria import TargetClass
from foolbox2.attacks.boundary_attack import BoundaryAttack
# from adversarial_vision_challenge import load_model
# from adversarial_vision_challenge import read_images
# from adversarial_vision_challenge import store_adversarial
# from adversarial_vision_cha... |
import os
import scipy.io.wavfile as wav
# install lame
# install bleeding edge scipy (needs new cython)
def mp3_to_np(file_name):
fname = file_name
temp = 'temp.wav'
cmd = 'lame --decode {0} {1}'.format(fname, temp)
os.system(cmd)
data = wav.read(temp)
return data
clean_cmd = 'rm -rf tem... |
import numpy as np
import math
import matplotlib.pyplot as plt
import matplotlib.pylab as pylab
from scipy.stats import multivariate_normal
def state_space_display_predict(y,y_dot,mu_0,sigma_0,mu_bar,sigma_bar):
y_axis = np.array([y_dot-1,y_dot+1])
x_axis = np.array([y-2,y+2])
delta= 0.05
x_coor, y... |
<filename>code/deconvolution.py
'''
Deconvolution
=============
This file contains the routine to perform Wiener deconvolution in the Fourier domain.
Author: 2018 (c) <NAME>
License: MIT License
'''
from __future__ import division, print_function
import numpy as np
from scipy import linalg as la
from scipy.interpola... |
<filename>mxnetseg/data/cocostuff.py
# coding=utf-8
import os
import scipy.io
import numpy as np
import mxnet as mx
from PIL import Image
from gluoncv.data.segbase import SegmentationDataset
from mxnetseg.utils import DATASETS, dataset_dir
@DATASETS.add_component
class COCOStuff(SegmentationDataset):
... |
# filters
import numpy as np
from scipy.signal import butter, filtfilt, sosfiltfilt
def butter_lowpass_filter(data, lowcut, fs, order):
nyq = fs/2
low = lowcut/nyq
b, a = butter(order, low, btype='low')
# demean before filtering
meandat = np.mean(data, axis=1)
data = data - meandat[:, np.newaxi... |
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 08 11:30:52 2015
@author: <NAME>
"""
import numpy as np
from matplotlib.collections import PatchCollection
from matplotlib.patches import Polygon
try:
import sympy
except ImportError, e:
print "NeedleMaster requires sympy."
print "Try to install it with:"
print "... |
import importlib
import itertools
from itertools import product, count
import json
import os
import os.path as op
from copy import deepcopy
from dataclasses import dataclass
# from dpcontracts import invariant
from math import floor, ceil
import more_itertools
from pathlib import Path
import toolz as tz
from typing imp... |
<filename>utils.py
import numpy as np
from os import walk
import os, shutil
from os.path import splitext
import pandas as pd
from scipy.io import loadmat
def load_file(file_path):
if splitext(file_path)[1] == '.mat':
# print(' Loading ', file_path)
x = loadmat(file_path)
return x
... |
<reponame>jayson-garrison/ML-RandomForests-SVM<filename>project/SupportVectorMachine/SVM.py
from cmath import inf
from Utils.Model import Model
import numpy as np
from numpy.linalg import norm
import pandas as pd
import sys
np.set_printoptions(threshold=sys.maxsize)
class SVM(Model):
def __init__(self, C, tol, max... |
from potentials.DiscreteCondPot import *
from nodes.BayesNode import *
import math
import cmath
class PhaseShifter(BayesNode):
"""
The Constructor of this class builds a BayesNode that has a transition
matrix appropriate for a phase shifter.
The following is expected:
* the focus node has precis... |
<filename>src/spatial_quantities.py<gh_stars>1-10
'''
This code is used to calculate spatial information, sparsity and other spatial quantities
'''
from __future__ import division
from multiprocessing import Pool
from scipy import signal
import numpy as np
from misc import *
def triweight_kernel(N_bins=50, sigma=... |
import networkx as nx
import osmnx as ox
import matplotlib.pyplot as plt
from scipy.optimize import minimize_scalar, differential_evolution
import time
import copy
import googlemaps
from EleNa.src.config import Config
def find_path_edges(graph, path, weight, mode):
"""
used to alter the path edges in case mu... |
<filename>finetune/tvqa/prep_data.py
"""
Convert TVQA into tfrecords
"""
import sys
sys.path.append('../../')
import argparse
import hashlib
import io
import json
import os
import random
import numpy as np
from tempfile import TemporaryDirectory
from copy import deepcopy
from PIL import Image, ImageDraw, ImageFont
im... |
"""RDP analysis of the Sampled Gaussian Mechanism.
Functionality for computing Renyi differential privacy (RDP) of an additive
Sampled Gaussian Mechanism (SGM). Its public interface consists of two methods:
compute_rdp(q, noise_multiplier, T, orders) computes RDP for SGM iterated
T... |
<gh_stars>1-10
'''
Modules for Numerical Relativity Simulation Catalog:
* catalog: builds catalog given a cinfiguration file, or directory containing many configuration files.
* scentry: class for simulation catalog entry (should include io)
'''
#
from nrutils.core import global_settings
from nrutils.core.basics i... |
"""
Module: LMR_verify_proxy_plot.py
Purpose: Plotting of summary statistics from proxy-based verification. Both proxy
chronologies that were assimilated to create reconstructions and those witheld for
independent verification are considered.
Input: Reads .pckl files containing verification data ... |
<reponame>zdai257/pyroomacoustics
import numpy as np
import matplotlib.pyplot as plt
from scipy.io import wavfile
from scipy.signal import fftconvolve
import IPython
import pyroomacoustics as pra
import os
from os.path import join
import librosa
import random
import pandas as pd
import argparse
import json
from math im... |
<reponame>chiffa/BioFlow
import numpy as np
from scipy.stats import gumbel_r
from typing import List
from bioflow.utils.log_behavior import get_logger
log = get_logger(__name__)
def get_neighboring_degrees(degree: int,
max_array: np.array,
nearest_degrees: in... |
#!/usr/bin/env python
"""
Generate an image where the x-axis is the seed, the y-axis is the random number.
"""
# core modules
import random
# 3rd party
import numpy as np
def generate_image(size=1000):
arr = np.zeros((size, size))
for i in range(size):
random.seed(i)
for j in range(size):
... |
# -*- coding: utf-8 -*-
"""
cov_model
~~~~~~~~~
"""
import numpy as np
from scipy.linalg import block_diag
from slime.core import MRData
import slime.core.utils as utils
class CovModel:
"""Single covariate model.
"""
def __init__(self, col_cov,
use_re=False,
boun... |
<reponame>Jdudre/peri
from builtins import range, zip
import numpy as np
import scipy.ndimage as nd
import peri
from peri import initializers
from peri.util import Tile
import peri.opt.optimize as opt
from peri.logger import log
CLOG = log.getChild('addsub')
def feature_guess(st, rad, invert='guess', minmass=None, ... |
#! /usr/bin/python3
import numpy as np
import lightgbm as lgb
import pandas as pd
from setting import *
import scipy
from sklearn.model_selection import train_test_split
import gc
cnt = 1
root_path = '/home/zyoohv/Documents/tencent_dataset/preliminary_contest_data/upsample/'
def main():
cv_numiterations = para... |
from __future__ import print_function
from numbers import Number
import mdtraj as md
import numpy as np
from scipy.optimize import leastsq
def calc_contact_angle(traj, guess_R=1.0, guess_z0=0.0, guess_rho_n=1.0,
n_fit=10, left_tol=0.1, z_range=None, surface_normal='z', n_bins=50,
fit_range=None, drop... |
# ------------------- Imports for BNN PYMC3 ---------------------------------
import numpy as np
import pymc3 as pm
import theano
import arviz as az
from arviz.utils import Numba
from scipy.stats import mode
import theano.tensor as tt
Numba.disable_numba()
Numba.numba_flag
floatX = theano.config.floatX
# For creati... |
<filename>theano/misc/tests/test_may_share_memory.py<gh_stars>10-100
"""
test the tensor and sparse type. The CudaNdarray type is tested in sandbox/cuda/tests/test_tensor_op.py.test_may_share_memory_cuda
"""
import numpy
import theano
try:
import scipy.sparse
scipy_imported = True
except ImportError:
sci... |
<reponame>westlake-cairi/MarLip<filename>utils.py
import os
import time
import math
import torch
import signal
import imageio
import subprocess
import numpy as np
from itertools import product
import matplotlib.pyplot as plt
from scipy.spatial import Delaunay
from sklearn.decomposition import PCA
from mpl_toolkits.mplo... |
<gh_stars>0
"""
This will draw an overall flux daigram
"""
# load a bunch of stuff
import cantera as ct
import numpy as np
import scipy
import pylab
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from matplotlib.pyplot import cm
from matplotlib.ticker import NullFormatter, Max... |
import numpy as np
from scipy import stats
from river.base import DriftDetector
class KSWIN(DriftDetector):
""" Kolmogorov-Smirnov Windowing method for concept drift detection.
Parameters
----------
alpha
Probability for the test statistic of the Kolmogorov-Smirnov-Test. The alpha parameter ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Base Class for Item Finders
"""
from __future__ import (
print_function,
division,
absolute_import,
unicode_literals)
from six.moves import xrange
# =============================================================================
# Imports
# =============... |
<filename>vasppy/optics.py
"""
functions for working with optical properties from vasprun.xml
"""
from math import pi, sqrt
import numpy as np # type: ignore
from scipy.constants import physical_constants, speed_of_light # type: ignore
eV_to_recip_cm = 1.0/(physical_constants['Planck constant in eV s'][0]*speed_of_... |
from uncertainties_tools import *
from sgld import *
import sgld_tools
from tqdm import tqdm
import argparse
import torch
import torch.nn as nn
import torch.functional as F
from torch.distributions.normal import Normal
import matplotlib.pyplot as plt
import numpy as np
import sklearn.datasets
from sklearn.model_select... |
"""Symbolic filter-error method estimation models."""
import numpy as np
import scipy.special
import sympy
from ceacoest.modelling import symoptim
class InnovationDTModel(symoptim.Model):
def __init__(self, nx, nu, ny):
super().__init__()
self.nx = nx
"""Number of states."""
s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.