text string |
|---|
#!/usr/bin/env python
#python 3 compatibility
from __future__ import print_function
#stdlib imports
import sys
import collections
import datetime
import time
import os.path
#third party imports
import h5py
from scipy.io import netcdf
import numpy as np
from .multiple import MultiGrid
from .shake import ShakeGrid
fr... |
import enum
import logging
import numpy as np
import sympy as sp
class TrajectoryType(enum.Enum):
VELOCITY = 2
ACCELERATION = 4
JERK = 6
SNAP = 8
class MininumTrajectory:
def __init__(self, trajtype: TrajectoryType):
numcoeffs = trajtype.value
logging.info(f'Creating minimum {tr... |
"""Exhastuve grid search for parameters for TSNE and UMAP"""
import argparse
import itertools
import hdbscan
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.gridspec as gridspec
import numpy as np
import pandas as pd
import seaborn as sns
from scipy.spatial.distance import pdist, squareform
f... |
import pytest
from typing import Tuple, List
from abc import ABCMeta, abstractmethod
import numpy as np
from scipy.special import comb
from scipy.sparse import find
from tqdm import tqdm
from itertools import combinations
from panqec.codes import StabilizerCode
from panqec.bsparse import is_sparse, vstack, to_array
fro... |
import numpy as np
from scipy import integrate
from scipy import interpolate
# Cosmological parameters
Om0 = 0.272
Ol0 = 1.0 - Om0
h = 0.704
ns = 0.961
sigma80 = 0.807
SPEEDOFLIGHT_KMS = 2.99792458e5
def nhat(alpha, delta):
nhat = np.zeros(3)
nhat[0] = np.cos(delta) * np.cos(alpha)
nhat[1] = np.cos(delta) * np.... |
# -*- coding: utf-8 -*-
import numpy as np
import glob
import os
import sys
import scipy.io.wavfile as wavf
import scipy.signal
import h5py
import json
import librosa
import multiprocessing
import argparse
def preprocess_data(src, dst, src_meta, n_processes=15):
"""
Calls for distibuted preprocessing of the... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 22 16:48:57 2021
This script clean data from FastTrack analysis to crate an Xarray object that is saved inside an twin folder, in a .nc file
@author: baptistelafoux
"""
#### WARNING : TO DO - Slide light signal time basis to account for differen... |
<filename>tests/test_kernels/test_kernel.py
"""Test cases for kernels."""
import numpy as np
import pytest
import scipy.spatial
import probnum.kernels as kernels
import probnum.utils as _utils
def test_1d_data(kernel: kernels.Kernel, x0_1d: np.ndarray, input_dim: int):
"""Test handling of 1d data."""
kernma... |
<gh_stars>1-10
import numpy as np
from scipy import fftpack
def get_2d_dct(x):
return fftpack.dct(fftpack.dct(x.T, norm='ortho').T, norm='ortho')
def get_2d_idct(x):
return fftpack.idct(fftpack.idct(x.T, norm='ortho').T, norm='ortho')
def RGB_img_dct(img):
assert len(img.shape) == 3 and img.shape[0] == ... |
<filename>practice/tf_practice.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 28 22:55:09 2019
@author: ali
"""
import control as ct
import numpy as np
# start with a transfer function and omega vector
tf_s = ct.tf([1], [1, 2, 2])
omega_rad_s = np.logspace(-1, 2, 10)
ct.bode_plot(tf_s)
PS... |
import numpy
from scipy.misc import imread
from matplotlib import pyplot as plt
from PIL import Image
from PIL import ImageDraw
def rotate(image, angle, color, filter=Image.NEAREST):
if image.mode == "P" or filter == Image.NEAREST:
matte = Image.new("1", image.size, 1) # mask
else:
matte = Im... |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.rcParams.update({'font.size': 15})
import pandas as pd
from scipy.stats.stats import pearsonr
gids = [6000]
# Decide which systems we are doing analysis for.
sys_dict = {}
#sys_dict['ll1'] = { 'cells_file': '../build/ll1.csv', 'f_1': ... |
<filename>Groups/Group_ID_45/2DSPCCA/spcca2d.py
import pandas as pd
import numpy as np
import math
from sklearn.neighbors import NearestNeighbors
from scipy.spatial.distance import pdist, squareform
from numpy import linalg
from scipy.linalg import eigh
from scipy import sparse
from numpy import linalg as LA
class SPC... |
import numpy as np
import scipy.constants as const
from scipy.optimize import minimize
from physunits import *
pe = 1. # photo electrons
hbar = const.hbar
c = const.c
pi = np.pi
def absorption_SNR(probe_pulse, sample, detector, technical_noise=True):
""" Calculates the signal-to-noise ratio for the target optica... |
# coding=utf-8
# Copyright 2018 The Google AI Language Team 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 ... |
"""
Copyright (c) Facebook, Inc. and its affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
import argparse
import pathlib
from argparse import ArgumentParser
import h5py
import scipy
import numpy as np
from runstats import Statisti... |
<gh_stars>0
#Standard python libraries
import os
import warnings
import copy
import time
import itertools
import functools
#Dependencies - numpy, scipy, matplotlib, pyfftw
import numpy as np
import matplotlib.pyplot as plt
import pyfftw
from pyfftw.interfaces.numpy_fft import fft, fftshift, ifft, ifftshift, fftfreq
fr... |
<gh_stars>0
import math
from scipy.spatial import distance
def gauss_bell(x_vector, t_vector, std):
return math.exp(-((distance.euclidean(x_vector, t_vector) / std) ** 2))
def calculate_cell_std(t_image, images):
return min(list(map(lambda x: distance.euclidean(x, t_image), images)))
|
import numpy as np
import scipy.constants as spc
from pyresponse.utils import fix_mocoeffs_shape, repack_matrix_to_vector
class Operator:
"""Handle property integrals, taking them from the AO basis to a
representation of a right-hand side perturbation for CPHF or
transition properties."""
def __init... |
<filename>game/levels/cellular_automata_level.py
from collections import Counter
from queue import Queue
from random import random
import numpy as np
from scipy.signal import convolve2d
from config.constants import CELL
from .level import Level
class CellularAutomataLevel(Level):
def _flood_fill(self, level_ma... |
<reponame>weepiess/PRnet-train
import numpy as np
import os
import argparse
import cv2
import random
import math
from datetime import datetime
from skimage.io import imread, imsave
import scipy.io as sio
class TrainData(object):
def __init__(self, train_data_file):
self.train_data_file = ... |
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
import numpy as np
from scipy.cluster.hierarchy import dendrogram, linkage, fcluster
from scipy.ndimage.filters import gaussian_filter1d
import pylab as pl
import matplotlib.gridspec as gridspec
import seaborn as sns
import matplotlib.font_manager as... |
from __future__ import print_function
import sys
import os
import argparse
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import torchvision.transforms as transforms
from torch.autograd import Variable
from data import VOC_ROOT, VOC_CLASSES as labelmap
from PIL import Image
from data import VOC... |
<reponame>kreimanlab/WhenPigsFlyContext
import json
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import scipy.io
# intialize dicts
total, results = {}, {}
for sz in range(1, 5):
for contx in range(0, 4):
cond = (sz, contx)
results[cond], total[cond] = 0, 0
#python3 test_exp_I.py --unc... |
<filename>seimore/Main.py
### Eigen-Reconstruction of Scaler Perturbations
### Script Created on November 27th, 2019
### Libraries
from scipy.integrate import quad as qd
import time as t
from BasicFuncs import *
### Main Part of Code
def pwr(number, root):
return np.log(number)/np.log(root)
### Smooth Function
def ... |
"""Test user-provided initial values for parameters."""
import random
import statistics
import aiohttp
import pytest
import helpers
program_code = """
data {
real x;
}
parameters {
real mu;
}
model {
x ~ normal(mu,1);
}
"""
data = {"x": 2}
@pytest.mark.asyncio
async def te... |
<reponame>thunder-project/thunder-register
from numpy import arange
from scipy.ndimage.interpolation import shift
from registration import CrossCorr
reference = arange(9).reshape(3, 3)
deltas = [[1, 0], [0, 1]]
shifted = [shift(reference, delta, mode='wrap', order=0) for delta in deltas]
register = CrossCorr()
model... |
from sympy.matrices import Matrix, eye, zeros
from sympy import sin, pi, cos, abc
from sympy.solvers import solve
class TriangleGroup:
def __init__(self,p,q,r):
[sp,sq,sr] = (cos(pi/n) for n in [p,q,r])
self.pqr = [p,q,r]
m = Matrix([[-1,sp,sr],
[sp,-1,sq],
... |
<reponame>chebykinn/university
import sys
import math
from scipy.sparse import lil_matrix
import operator
# sorting map
import numpy as np
# local imports
from sklearn.metrics.pairwise import cosine_similarity
from src.utils import get_open_files, get_lemma_tokens
WINDOW_SIZE = 5
LOG_BASE = 2
TOP_WORD_OCCUR = 3000
T... |
import numpy as np
def from_data_file(data_dir):
""" This function reads the data that we use in this demo."""
data=dict()
import scipy.io as sio
data_file = sio.loadmat(data_dir+'/data_train.mat')
data['train']=dict()
data['train']['inputs'] = data_file['inputs']
data['train']['target... |
#!/usr/bin/env python3
import sys
import cmath
#Find the permuations of a string (By using recursion helper)
def main():
str_word = input("Enter a string: ").strip()
if not (type(str_word) == str and str_word):
sys.stderr.write("Please input a valid string!")
exit(1)
# Find the permuations ... |
"""
tybalt/data_models.py
2018 <NAME>
Methods for loading, transforming, and compressing input gene expression data
Usage:
from tybalt.data_models import DataModel
dm = DataModel(filename='example_data.tsv')
# Transform if necessary
dm.transform(how='zscore')
# Compress input data with various... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 8 10:13:01 2017
+
; NAME:
;
; izi_mcmc
;
; PURPOSE:
;
; Compute the posterior PDF of the gas-phase metallicity, ionization
; parameter and dust EBV given a set of observed emission line fluxes
; and errors, and a photo-ionization model grid... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
__author__ = '<NAME>'
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import sklearn.metrics as metrics
import numpy as np
from sklearn.neighbors import NearestNeighbors
from scipy.spatial.distance import correlation, cosine
import ipywidgets as widg... |
"""
with the name of ALLAH:
SUDIO (https://github.com/MrZahaki/sudio)
audio processing platform
Author: <NAME> (<EMAIL>)
Software license: "Apache License 2.0". See https://choosealicense.com/licenses/apache-2.0/
"""
import io
from ._register import Members as Mem
from ._register import static_vars
from ._tools... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Roulette - Klasse von zufall
#
#
# This file is part of zufall
#
#
# Copyright (c) 2019 <NAME> <EMAIL>
#
#
# Licensed under the Apa... |
<gh_stars>1-10
#!/usr/bin/env python
import pandas as pd
import cv2
import math
import numpy as np
import random
import math
import tensorflow as tf
from scipy.stats import norm
import numpy as np
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten,Lambda
... |
import abc
from collections import OrderedDict
from time import time
import numpy as np
from sympy import cos, sin
from devito.equation import Eq
from devito.ir import (DataSpace, IterationSpace, Interval, IntervalGroup, Cluster,
ClusterGroup, detect_accesses, build_intervals, groupby)
from dev... |
import numpy as np
import mne
RAW_DATA_DIR = '/home/alex/SwannLab/EMU_data'
BIDS_ROOT = '/home/alex/SwannLab/EMU_data_BIDS'
DATA_DIR = '/home/alex/SwannLab/EMU_analysis'
SUBJECTS = [1, 2, 5, 6, 9, 10, 11, 12]
TASK = 'SlowFast'
TEMPLATE = 'cvs_avg35_inMNI152'
N_COMPONENTS = 50
EVENTS = dict(baseline=('Fixation', -1.5, ... |
<filename>Human_intention/src/Train_model/concatinate_contour.py
"""Contours with overlap control.
This script generates widely spaced black contours, with a gray patch in a
subregion where more finely-spaced colored contours are visible. The gray
patch covers the black contours.
"""
from __future__ import division
i... |
"""
Implementation of window function estimation, following https://github.com/cosmodesi/GC_derivations,
and https://fr.overleaf.com/read/hpgbwqzmtcxn.
"""
import time
import numpy as np
from scipy import special
from pmesh.pm import ParticleMesh, RealField, ComplexField
from . import mpi
from .fftlog import PowerToC... |
from functools import reduce
import numpy as np
import pytest
from cpsplines.utils.fast_kron import (
fast_kronecker_product,
kronecker_matrix_by_identity,
)
from cpsplines.utils.timer import timer
from scipy.linalg import block_diag
# Take the Kronecker product of a list of random matrices with ... |
<reponame>likojack/bnv_fusion
import numpy as np
from scipy.spatial.transform import Rotation
def read_pose(img):
""" see render_depths.py for translation and intrinsic
"""
img = img[:-1]
x_rot, y_rot = [float(f) for f in img.split("_")]
T_wo = np.eye(4)
T_wo[2, 3] = -1
rot_mat_0 = Rotatio... |
import numpy as np
import random
import os
import librosa
import soundfile
from scipy.io.wavfile import read
import matplotlib.pyplot as plt
def packlossf(PackLoss, theo_pack_loss_maxlen, speech):#, speech
theo_pack_loss_rate = PackLoss /100
total_packs = len(speech)
if theo_pack_loss_maxlen == 0:
q = 1 - th... |
from __future__ import annotations
from dataclasses import dataclass, field
from fractions import Fraction
from typing import List, Union, Iterable
import numpy as np
import pandas as pd
from reamber.base.RAConst import RAConst
MAX_DENOMINATOR = 100
@dataclass
class BpmChangeSnap:
bpm: float
measure: int
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 23 14:55:18 2020
@author: daiwei
"""
"""
This file writes the raw data in forms of arrays to different txt files
"""
#%%
#######################################
# This part generates the output file #
#######################################
... |
<gh_stars>0
from scipy.io import loadmat
import numpy as np
from math import radians, log
from random import random
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
OFFSET_DISTANCE = 0.5
ALPHA = 1
BETA = radians(5)
Z_MAX = 150
def L0():
return log(1.0)
def L_OCC():
p = random()*0.... |
# Thanks to https://www.kaggle.com/wcukierski/example-metric-implementation
import csv
import numpy as np
from scipy import ndimage as ndi
from tqdm import tqdm
def masks2labels(masks, roll=False):
num_mask = masks.shape[2 if roll else 0]
rolled = np.rollaxis(masks, 2) if roll else masks
mask_list = list... |
<filename>sound4python/sound4python.py
try: import tempfile, wave, subprocess, os, signal, struct
except:
print("E: sound4python is unable to import a combination of %s"%
("tempfile, wave, subprocess, os, signal, struct"))
import threading
import scipy.io.wavfile
import numpy as np
impor... |
import os
from optparse import OptionParser
def getOptions():
usage = "python pg-plot.py <data>"
parser = OptionParser( usage=usage )
(options, args) = parser.parse_args()
if len(args) != 1:
print usage
exit()
return (options, args)
options, args = getOptions()
import numpy as np... |
import numpy as np
from scipy.special import softmax
import argparse
parser = argparse.ArgumentParser(description="Measure Cost_average defined in NIST LRE2017 ", add_help=True)
parser.add_argument("--label", type=str, default="data/test_segments/utt2lang_sorted",help="label filename")
parser.add_argument("--score", t... |
import numpy as np
from numpy import random
import cupy as cp
from unyt import nm
from unyt import ps
from unyt import m
from unyt import s
from unyt import J
from unyt import kJ
from unyt import kg
from unyt import amu
import openmm as mm
from scipy import special
import csv
from scipy import integrate
from scipy.inte... |
# In order to understand how the code works, it is a good idea to check the
# final section of the file that starts with
# if __name__ == '__main__'
#
# Your task is essentially to replace all the parts marked as TODO or as
# instructed through comments in the functions, as well as the filenames
# and labels in the m... |
<gh_stars>1-10
import numpy
from .. import rqa
from .. import dsp
from .. import utilities
import os
import scipy.io.wavfile
from . import experiments
def test_dsp(kind="small"):
if kind=="small":
N = 1
data_file_name = os.path.join(os.path.dirname(__file__), 'test_dsp_profile_'+str(N)+'ms.npz')... |
# standard library
from functools import lru_cache
# third-party libraries
from scipy.stats import norm as normal_distribution, binom as binomial_distribution # type: ignore # mistakenly, pylance doesn't recognize scipy.stats.norm and scipy.stats.binom
@lru_cache(10000)
def normal_z_score(p: float = 0.95) -> float:
... |
import gym
from pyroomacoustics import MicrophoneArray, ShoeBox, Room, linear_2D_array, Constants
import numpy as np
import matplotlib.pyplot as plt
from gym import spaces
from scipy.spatial.distance import euclidean
from sklearn.metrics.pairwise import euclidean_distances
from copy import deepcopy
import nussl
import ... |
<reponame>aredder/distributed_policy_gradient
import numpy as np
from scipy.integrate import odeint
class Filter:
def __init__(self, flow_init, water_init, k_1, k_2, delta):
self.state_1 = flow_init
self.state_2 = water_init
self.delta = delta
self.a_1 = None
self.a_2 = Non... |
import torch
import numpy as np
import scipy.optimize as opt
from tqdm import tqdm
from clean_data import dist
from functools import partial
from neural_network import ffn
from method import ls, phi_meta, grad_phi_meta
if __name__ == '__main__':
''' read data '''
fname = 'task3'
mat, anchors= list(), lis... |
import numpy as np
import tensorflow as tf
import time
import os
import matplotlib.pyplot as plt
import matplotlib as mpt
import colorsys as cls
import statistics as stat
from sklearn.model_selection import train_test_split
import csv
import pickle
from mmd import rbf_mmd2, median_pairwise_distance, mix_rbf_... |
<gh_stars>1-10
# import os.path
# import torchvision.transforms as transforms
# from data.base_dataset import BaseDataset, get_transform
from data.base_dataset import BaseDataset
# from data.image_folder import make_dataset
# from PIL import Image
# import PIL
import h5py
import random
import torch
import numpy
import ... |
<reponame>Anthony102899/Lego-ImageGenerator
# %%
import sys
sys.path.append("../../..")
from tqdm import tqdm
import torch
from torch.optim import Adam
import numpy as np
from scipy.linalg import null_space
from solvers.rigidity_solver import (
algo_core as core,
gradient,
extra_constraint
)
from solvers.... |
<filename>3rd_party_libs/transnetv1/transnetv1_handler.py
import ffmpeg
import numpy as np
import tensorflow as tf
import cv2
transnet_verbose = False
class ShotTransNetParams:
F = 16
L = 3
S = 2
D = 256
INPUT_WIDTH = 48
INPUT_HEIGHT = 27
CHECKPOINT_PATH = None
class ShotTransNet:
def __in... |
<reponame>xueyuelei/tracklib<gh_stars>1-10
# -*- coding: utf-8 -*-
'''
Linear Kalman filter
REFERENCE:
[1]. <NAME>, "Optimal State Estimation: Kalman, H Infinity, and Nonlinear Approaches," John Wiley and Sons, Inc., 2006.
'''
from __future__ import division, absolute_import, print_function
__all__ = ['KFilter']
im... |
<reponame>thejerrytan/CarND-Behavioural-Cloning-P3
import csv
import cv2
import numpy as np
import os
import sklearn
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
# Use this to train track2
TRAINING_DIR = "harder_data"
# Use this to train track1
# TRAINING_DIR = "data"
# Model f... |
<filename>xesmf/smm.py<gh_stars>1-10
"""
Sparse matrix multiplication (SMM) using scipy.sparse library.
"""
import xarray as xr
import scipy.sparse as sps
import warnings
def read_weights(filename, N_in, N_out):
'''
Read regridding weights into a scipy sparse COO matrix.
Parameters
----------
fi... |
<reponame>HaroonRafique/CERN_NewPTC_PyORBIT<filename>lib/save_bunch_as_matfile.py
import orbit_mpi
from orbit_mpi import mpi_datatype
from orbit_mpi import mpi_op
import numpy as np
import scipy.io as sio
from bunch import Bunch
# 12.03.2017: works now also for lostbunch attributes
# 03.06.2017: now a bunch object can... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import mne
import numpy as np
from . import download as dl
from scipy.io import loadmat
HEADMOUNTED_URL = 'https://zenodo.org/record/2617085/files/'
class HeadMountedDisplay():
'''
We describe the experimental procedures for a dataset that we have made publicly a... |
<gh_stars>1-10
import os
import cv2
import glob
import json
import tqdm
import numpy as np
from scipy.spatial.transform import Slerp, Rotation
import trimesh
import torch
from torch.utils.data import DataLoader
from .utils import get_rays
# ref: https://github.com/NVlabs/instant-ngp/blob/b76004c8cf478880227401ae76... |
#!/usr/bin/env python3
import os
import io
import numpy
import random
import re
import hashlib
import math
import array
import wget
import shutil
import statistics
import subprocess
import requests
from functools import reduce
from shutil import copyfile
from os.path import expanduser
from pathlib import Path
from pyd... |
<reponame>feliposz/project-euler-solutions
"""Problem 57
21 November 2003
It is possible to show that the square root of two can be expressed as
an infinite continued fraction.
2 = 1 + 1/(2 + 1/(2 + 1/(2 + ... ))) = 1.414213...
By expanding this for the first four iterations, we get:
1 + 1/2 = 3/2 = 1.5
1 + 1/(2 +... |
"""python embed_fbanks.py pascal1k_crossnet_adadelta_emb_200.pickle"""
from __future__ import division
import cPickle as pickle
import sys
import os.path as path
import glob
import operator
import os
from collections import defaultdict
import joblib
from scipy.spatial.distance import pdist, cdist
from scipy.io impor... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Proof of concept of a minimalist, 3 layers (1 hidden) Neural Network. Code
based on the lectures from the Machine Learning coursework (Stanford -
Coursera) by Prof. Dr. <NAME> and the code implementation of andr0idsensei
(https://gist.github.com/andr0idsensei/92dd7e54a... |
<reponame>tuwiendsg/ADVISE
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 18 10:53:11 2013
@author: Georgiana
"""
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
import scipy.cluster.hierarchy as hcluster
from pandas import *
import collections
import matplotlib.pyplot as plt
import scipy.spatial... |
from __future__ import print_function
#!/usr/bin/python
"""
Simple adjunct routine to plot LSPS/CRACM maps with traces, over cell image if possible.
Reuqires acq4read.
Takes advantage of acq4read code to access all data and attributes.
"""
import os
import re
import itertools
import argparse
from collections impor... |
<reponame>vlivashkin/pygraphs
from abc import ABC
import numpy as np
from scipy.sparse.csgraph import shortest_path
from sklearn.utils import deprecated
from . import shortcuts as h
from . import scaler
class Distance(ABC):
name, _default_scaler, power = None, None, None
_parent_kernel_class = None
def... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 10 12:23:27 2015
@author: Eric
Takes 512x512 pixel images as input, spits out 16x16 patches.
"""
import numpy as np
import scipy.io
import matplotlib.pyplot as plt
filename = "IMAGES.mat"
dataname = "IMAGES"
newlength = 16
images = scipy.io.loadmat(filename)[dataname]... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#Created on Sat Nov 18 21:15:20 2017
#@author: rday
#MIT License
#Copyright (c) 2018 <NAME>
#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in th... |
<reponame>Draeius/loopwalk_kernel
from typing import List, Dict
from grakel import Graph
from scipy.sparse import lil_matrix
from sklearn import preprocessing
class AbstractConverter:
_k = 1
def getK(self) -> int:
return self._k
def setK(self, k: int):
if k < 1:
self._k = 1
... |
from .encoding import *
from random import randint
import scipy.stats
import numpy as np
import math
import sys
import tensorflow as tf
from copy import deepcopy
from .apply_mutations import topology_mutations, parameter_mutations, learning_mutations
from .saving_handler import *
# TODO -> por safety measures caso l... |
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 6 21:41:38 2015
@author: <NAME>
"""
import numpy as np
from scipy import misc
import matplotlib.pyplot as plt
from scipy import ndimage
from PIL import Image
def gauss(shape,sigma):
m,n = [(ss-1.)/2. for ss in shape]
y,x = np.ogrid[-m:m+1,-n:n+1]
h = np.e... |
<reponame>automl/learning_environments
import statistics
import torch
import torch.nn.functional as F
import yaml
from agents.base_agent import BaseAgent
from envs.env_factory import EnvFactory
from models.actor_critic import Actor_PPO, Critic_V
from models.icm_baseline import ICM
from utils import AverageMeter, Repl... |
import statistics
def cal_median(data_array):
output = statistics.median(data_array)
return output
data1 = [2, -1, 3, 6, 9, 4, 5, -1] # 3.5
data2 = [-1, 6, 5, 8, 1.1, 0]
non_negative = []
for num in data2:
if num >= 0:
non_negative.append(num)
print(cal_median(non_negative))
|
<reponame>yngvem/sparse_tensors<gh_stars>0
from scipy import optimize
def minimize(fun, x0, jac=None, obj_to_array=None, array_to_obj=None, **kwargs):
if obj_to_array is None and array_to_obj is None:
def obj_to_array(x): return x
def array_to_obj(x): return x
elif obj_to_array is None or arra... |
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
from scipy import io
import numpy as np
import pylab as pl
from scipy.signal import savgol_filter as sg
def smooth(x, fillen=27, polyord=3, axis=-1):
y = sg(np.flip(sg(x, fillen, polyord, axis=axis), axis),
fillen, polyord... |
# -*- coding: utf-8 -*-
# Copyright 2019 the HERA Project
# Licensed under the MIT License
"""Module for predicting noise on visibilties using autocorrelations and for producing noise standard deviation data files."""
import numpy as np
import argparse
import scipy
from . import io
from . import version
from .utils ... |
# -*- coding: utf-8
import numpy as np
from scipy.signal import freqz
import wx
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
from matplotlib.figure import Figure
from ihna.kozhukhov.imageanalysis.gui.mapfilterdlg import filters
class FilterDlg(wx.Dialog):
__sample_rate = None
... |
<reponame>thejeffreyli/pySimpleMask<gh_stars>0
import numpy as np
from scipy.sparse import csr_matrix
import matplotlib.pyplot as plt
import matplotlib.colors as colors
class RigakuReader():
def __init__(self, file):
self.file = file
def load(self):
with open(self.file, 'r') as f:
... |
<reponame>AarhusCosmology/concept1.0-data<filename>script/helper.py
import collections, os, pickle, re, shutil, sys
from glob import glob
import numpy as np
import matplotlib.pyplot as plt
import scipy.interpolate
"""
This script provide common functionality to the other Python scripts.
Do not wory about the variou... |
<filename>forces.py
import numpy as np
from scipy.spatial.transform import Rotation
from copy import copy
class Gravity:
def __init__(self, rod, gravity=np.array([0, 0, -9.8])):
self._gravity = gravity
self._rod = rod
def get_force(self):
return np.array([0.0, 0.0, 0.0]), self._gr... |
<gh_stars>1-10
from .base import BaseEvaluator
import re
import os
import argparse
import tqdm
from typing import Dict, List, Set
from sklearn.metrics import average_precision_score, ndcg_score
from scipy.stats import pearsonr, spearmanr
import logging
import numpy as np
import pickle
import json
import torch
import ma... |
# coding=utf-8
# Copyright 2022 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... |
# -*- coding: utf-8 -*-
import numpy as np
from scipy import special
from sklearn.base import ClassifierMixin, BaseEstimator
from sklearn.datasets import make_classification
def lossf(w, X, y, l1, l2):
"""
Вычисление функции потерь.
:param w: numpy.array размера (M,) dtype = np.float
:param X: nump... |
# -*- coding: utf-8 -*-
"""
Create Pharmacophore models from set of molecules.
Created on Mon Mar 16 10:11:53 2015
@author: <NAME>
"""
from pybel import readfile
from decaf.toolkits.ob import phar_from_mol
from decaf.utils import similarity, combine_pharmacophores
import numpy as np
from multiprocessing import Pool, ... |
from statistics import mean
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
import random
style.use('ggplot')
# XS = np.array([1, 2, 3, 4, 5, 6, 1, 4], dtype=np.float64)
# YS = np.array([5, 4, 6, 5, 6, 7, 1, 4], dtype=np.float64)
# noinspection PyPep8Naming,PyShadowingNames
def best_... |
import sympy as sp
import numpy as np
from kaa.model import Model
from kaa.reach import ReachSet
from kaa.plotutil import Plot
from settings import KaaSettings, PlotSettings
from kaa.timer import Timer
KaaSettings.SupressOutput = False
PlotSettings.save_fig = False
class HarOscRotate(Model):
def __init__(self,... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 11 09:33:07 2020
@author: HI
"""
import xlwings as xw
import math
from scipy.stats import norm
@xw.func
def GBlackScholesNGreeek(S,X,T,r,q,sigam,corp):
data=[S,X,T,r,q,sigam,corp]
d1=(math.log(data[0]/data[1])+(data[4]+data[5]**2/2)*data[2]/365)/((data[5])*math... |
# absolute minimum implementations of the basic spaghetti plot designs
#
# written quickly by Gleicher on 10/17/2017
#
# this was meant to see how quickly I could get the basic designs in place
# I am not a matplotlib expert, so I did the simplest and first thing I could
# figure out. The plots are ugly - and the code ... |
import os
import cv2
from scipy import misc
data_path = os.path.join('datasets', 'yourData')
both_path = os.path.join(data_path, 'val_test')
test_path = os.path.join(data_path, 'test')
gt_path = os.path.join(data_path, 'gt')
if not os.path.isdir(test_path):
os.mkdir(test_path)
if not os.path.isdir(gt_path):
o... |
#here comes all the external libraries imports of opytics
from scipy.optimize import fsolve
import numpy as np
import matplotlib.pyplot as plt
from math import *
##low-level functions
def straight(x0,y0,i): #parametric straight line with an angle i with the axis Ox
return parametric(lambda t: x0 + cos(i)*t, lambda... |
<filename>discharge_time_series.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Plots averaged and smoothed time series of rainfall and runoff for the
gauged basins.
Written by <NAME> for
"Low variability runoff inhibits coupling of climate, tectonics, and
topography in the Greater Caucasus"
If you use this... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.