text string |
|---|
import numpy as np
import scipy as sp
import logging
import doctest
import shutil
import unittest
import os.path
import time
from pysnptools.distreader.distmemmap import TestDistMemMap
from pysnptools.distreader.bgen import TestBgen
from pysnptools.distreader.distgen import TestDistGen
from pysnptools.distreader impor... |
<filename>numalgsolve/polynomial.py
import numpy as np
import itertools
from numpy.polynomial import chebyshev as cheb
from numpy.polynomial import polynomial as poly
from scipy.signal import fftconvolve, convolve
from numalgsolve.utils import Term, makePolyCoeffMatrix, match_size, slice_top, slice_bottom
import time
... |
<reponame>minjiedeng/NumEcon
from types import SimpleNamespace
import numpy as np
from scipy import optimize
import matplotlib.pyplot as plt
import ipywidgets as widgets
from . import consumer_old as consumer
###########
# figure #
###########
def _figure(par,steps,p1_old,p1_new,e1,e2,alpha,beta):
I_old = p1_o... |
#!/usr/bin/env python3
import subprocess, os, sys
import xml.etree.ElementTree as ET
from collections import defaultdict
from statistics import median, stdev
from datetime import datetime
def get_commit_hash():
res = subprocess.run('git rev-parse HEAD'.split(), check=True, stdout=subprocess.PIPE, universal_newlin... |
<reponame>enricopisoni/SHERPA-training
'''
Created on 25-nov-2016
@author: roncolato
'''
import numpy as np
import matplotlib.pyplot as plt
#from mpl_toolkits.basemap import Basemap
import scipy.io as sio
import platform
import cartopy.crs as ccrs
def CreateMap(bctarget,target,output,flagRegioMat,x,y,iSc,nomeDir,aqi,... |
<reponame>gunnarvoet/pyctdproc<gh_stars>1-10
#!/usr/bin/env python
# coding: utf-8
import gsw
import matplotlib as mpl
import numpy as np
import xarray as xr
from scipy import fft, optimize, signal, stats
from . import calcs, helpers
# We are running into trouble if the default backend is not installed
# in the curre... |
<filename>data_augmentation.py<gh_stars>1-10
# Data augmentation for EMG signals adapted from:
# <NAME> et al., “Data augmentation of wearable sensor data for parkinson’s disease monitoring using convolutional neural networks,” in Proceedings of the 19th ACM International Conference on Multimodal Interaction, ser. IC... |
<reponame>tburnett/pointlike
"""
This module implements the class OffPeak that
can be used to calculate the off-peak region
of a pulsar.
$Header: /nfs/slac/g/glast/ground/cvs/ScienceTools-scons/pointlike/python/uw/pulsar/lc_off_peak.py,v 1.5 2011/10/15 23:02:06 lande Exp $
author: <NAME> <<EMAIL>>
"""
import numbers... |
<reponame>m081429/wsitools
import cv2, openslide
import numpy as np
import math
from scipy.stats import gaussian_kde
from skimage.color import rgb2lab
from sklearn import linear_model
class MatcherParameters:
def __init__(self, layer_patch_num=None, layer_patch_max_try=None, layer_patch_size=None, rescale_rate=0)... |
<reponame>mabergmann/random-forests
import utils
from information_gain import calculate_info_gain_numerical, calculate_info_gain_categorical
from scipy import stats
from random import sample
import math
class DecisionTree:
is_leaf = False
is_trained = False
division = None
n_attr = -1
def train(se... |
<filename>src/justcause/data/generators/ihdp.py
"""Contains a data generating process used in the thesis, based on IHDP covariates.
The helpers begin with an underscore, as they are not exported and should not be
used by themselves. `multi_expo_on_ihdp` makes the entry point to access this DGP.
Basic Usage: ::
>... |
<reponame>tpoisot/nxfa2
#! /usr/bin/python
import networkx as nx
from scipy.sparse import spdiags, coo_matrix
import scipy as sp
import numpy as np
import matplotlib.pyplot as plt
## Now the layout function
def forceatlas2_layout(G, iterations=10, linlog=False, pos=None, nohubs=False,
kr=0.0... |
# -*- coding: utf-8 -*-
from numpy import *
from datetime import datetime, timedelta
from dateutil.relativedelta import *
import os
import re
import codecs
import pandas as pd
import scipy.io.netcdf as spnc
from ecmwfapi import ECMWFDataServer
import time_tools as tt
import geo_tools as gt
import downlo... |
from cymorph.cython_g2 import G2 as g2_cython
import numpy as np
from scipy import signal
import matplotlib.pyplot as plt
class G2:
"""
G2(segmented_image, g2_modular_tolerance=0.01, g2_phase_tolerance=0.01)
Extracts entropy metric from the supplied image.
Parameters
----------
segmented_ima... |
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import scipy.stats as ss
import numpy as np
import seaborn as sns
import pandas as pd
import numpy as np
import math
import argparse
import glob
from figure_gen_utils import convert_bxd_name
from typing import Dict
def mutation_comparison(
sub_0_... |
#!/usr/bin/env python
"""
dynspec.py
----------------------------------
Dynamic spectrum class
"""
from __future__ import (absolute_import, division,
print_function, unicode_literals)
import time
import os
from os.path import split
import numpy as np
import matplotlib.pyplot as plt
import sci... |
<reponame>Aaratrika-Chakraborty/heinz-95729-project-main<filename>ml/src/knn.py
# -*- coding: utf-8 -*-
from pathlib import Path
import argparse
import pandas as pd
import sys
from scipy.sparse import csr_matrix
from sklearn.neighbors import NearestNeighbors
import os
#print(os.getcwd())
owd = os.get... |
<gh_stars>1-10
import numpy as np
from scipy.misc import imsave
config = {}
config["epsilon"] = 1e-7
EPSILON = config["epsilon"]
def min_max_normalization(x, l_range = 0.0, r_range = 1.0, axis = None):
assert (l_range < r_range), "l_range must be less than r_range"
min_x = np.amin(x, axis = axis, keepdims = Tru... |
<reponame>katrinatran/Deeper-into-Biases-with-Personality-in-Recommender-Systems
import os
from scipy import sparse
from torch.utils.data import Dataset
class TwitPers(Dataset):
'''
Twitter Personality Dataset
'''
def __init__(self, scipy_dir_path, pandas_dir_path=None, uids_dic_path=None, which='tr... |
"""
Helper functions for computational geometry in PySAL.
"""
__author__ = "<NAME>, <NAME>, <NAME>, <NAME>"
__credits__ = "Copyright (c) 2005-2009 <NAME>"
import doctest
import math
import copy
import random
from .shapes import *
from itertools import islice
import scipy.spatial
import numpy as np
EPSILON_SCALER = ... |
from inspect import getfullargspec
from typing import (
TYPE_CHECKING,
Callable,
Mapping,
Optional,
Sequence,
Tuple,
Union,
Hashable
)
import numpy as np
import xarray as xr
from scipy.optimize import leastsq, curve_fit
from .utils import da_filter, gen_coord_combo, gen_sim_da
from .... |
<reponame>leal26/pyXFOIL<filename>examples/morphing/flight_conditions/range_expected_etc.py<gh_stars>10-100
import aeropy.xfoil_module as xf
from aeropy.geometry.airfoil import CST, create_x
from aeropy.morphing.camber_2D import *
from aeropy.aero_module import air_properties, Reynolds, LLT_calculator
import numpy as ... |
import sympy as sp
from sympy.interactive.printing import init_printing
import numpy as np
if __name__ == '__main__':
init_printing(use_unicode=False, wrap_line=False)
x, y, z, a, b, c = sp.symbols("x, y, z, a, b, c")
A = sp.Matrix([[x, y, z], [a, b, c], [x+a, y+b, z+c]])
sp.pprint(f"A = {A}")
A_... |
<filename>utils.py
"""
Some codes from https://github.com/Newmu/dcgan_code
"""
from __future__ import division
import math
import json
import random
import pprint
import scipy.misc
import numpy as np
from time import gmtime, strftime
pp = pprint.PrettyPrinter()
get_stddev = lambda x, k_h, k_w: 1/math.sqrt(k_w*k_h*x.g... |
# vim:set encoding=latin1
import numpy as np
import matplotlib.pyplot as plt
import math
import wave
import msvcrt
import sounddevice as sd
import math
import scipy.signal
from queue import Queue
from myLib import *
RATE = 44100
duration = 10 # sec
print ('enregistrement')
samples = ... |
<gh_stars>0
import os
import numpy as np
from scipy.interpolate import interp1d
def create_blank_image(width, height, rgb_color=(0, 0, 0)):
image = np.zeros((height, width, 3), np.uint8)
color = tuple(reversed(rgb_color))
image[:] = color
return image
def get_image_paths(dir_path):
paths = []
... |
<reponame>sukhsung/tomviz
def transform_scalars(dataset, sigma=2.0):
"""Apply a Gaussian filter to volume dataset."""
"""Gaussian Filter blurs the image and reduces the noise and details."""
from tomviz import utils
import scipy.ndimage
import numpy as np
array = utils.get_array(dataset)
... |
<reponame>neuroquery/nqdc<filename>tests/test_vectorization.py
import json
import shutil
from unittest.mock import patch
import numpy as np
import pandas as pd
from scipy import sparse
import pytest
from nqdc import _vectorization
@pytest.mark.parametrize(("with_voc", "n_jobs"), [(True, 3), (False, 1)])
def test_ve... |
<filename>test_scripts/kalman/MPC_observer.py
import numpy as np
import scipy.sparse as sparse
import time
import matplotlib.pyplot as plt
from pyMPC.mpc import MPCController
from kalman import kalman_filter
if __name__ == '__main__':
# Constants #
M = 0.5
m = 0.2
b = 0.1
ftheta = 0.1
l = 0.3
... |
# Copyright 2022 TerraPower, 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 writi... |
#!/usr/bin/env python
import ConfigParser
import json
import logging
import os
import regex
import socket
import sys
import time
import pytz
import arrow
import urlparse
import httplib
import requests
import statistics
import subprocess
import shlex
import traceback
import pymssql
from pymssql import ProgrammingError
... |
import math
import random
import scipy.stats
class _State :
def __init__(self, num, ft_list, trans_probs, means_list, variances):
self.feature_list = ft_list
self.num = num
# TODO: make sure the randomly-initialized means/variances are relatively close to actual values being produced
# TODO: maybe pick specif... |
<reponame>TUM-E21-ThinFilms/skipi
import numpy
import scipy.interpolate
from typing import Callable
from scipy.integrate import trapz
from skipi.util import is_number
from skipi.domain import Domain
FUNCTION_INTERPOLATION_TYPE = 'linear'
class Function(object):
"""
A mathematical function
A function ... |
# -*- coding: utf-8 -*-
"""
Created on Thu May 20 17:52:09 2021
@author: cheritie
"""
import numpy as np
import scipy.ndimage as sp
import sys
import inspect
import time
import matplotlib.pyplot as plt
import multiprocessing
from AO_modules.Detector import Detector
from AO_modules.tools.tools import bi... |
<reponame>LeenJooken/RFMCollaborationMiner
#Class that represents a work session of one resource
#contains a number of events
import statistics
class Worksession:
#@param resource : Resource object
#@param events : list of Event objects
def __init__(self,resource, events):
self.resource = resour... |
# -*- coding: utf-8 -*-
import random
import numpy as np
import matplotlib.pyplot as plt
import scipy.integrate
#set line width
plt.rcParams['lines.linewidth'] = 4
#set font size for titles
plt.rcParams['axes.titlesize'] = 18
#set font size for labels on axes
plt.rcParams['axes.labelsize'] = 18
#set size of numbers ... |
from scipy import linalg
from sympy import *
def Katzmatrix(G, alpha):
A = G.adjacency_matrix()
In = matrix.identity(G.num_verts())
M = In - alpha * A
K = M.inverse()-In
Missing = allonesmatrix(G.num_verts()) - A- In
#print "Missing"
#print Missing
return elemwiseprod(K,Missing)
def... |
import numpy as np
from scipy import signal
import matplotlib.pyplot as plt
from pyvib.forcing import multisine
from pyvib.common import db
def plot(sig):
plt.figure()
for i, u in enumerate(sig):
U = np.fft.fft(u)
plt.subplot(2,2,1+i)
plt.plot(db(U),'+')
plt.xlabel('Frequency l... |
<gh_stars>10-100
import numpy as np
import tensorflow as tf
from tensorflow import gfile
import imageio
import pickle
import scipy.misc
import sys
import imageio
import os
import rllab.misc.logger as logger
slim = tf.contrib.slim
from nets import inception_v3
from gym.envs.mujoco import arm_shaping
def transform(imag... |
<reponame>Computational-Nonlinear-Optics-ORC/Compare-CNLSE
from combined_functions import *
import GNLSE_specific as GN
import BNLSE_specific as BN
from copy import deepcopy
import numpy as np
from scipy.constants import c, pi
from integrands import Integrand_BNLSE, Integrand_GNLSE
from combined_functions import disper... |
import torch
import numpy as np
from scipy import linalg
LAB_WHITE = (0.95047, 1., 1.08883)
XYZ_FROM_RGB = np.array([[0.412453, 0.357580, 0.180423],
[0.212671, 0.715160, 0.072169],
[0.019334, 0.119193, 0.950227]])
RGB_FROM_XYZ = linalg.inv(XYZ_FROM_RGB)
def tv_lab2xy... |
import scipy
import numpy as np
from sklearn import linear_model
from skfeature.utility.construct_W import construct_W
def mcfs(X, n_selected_features, **kwargs):
"""
This function implements unsupervised feature selection for multi-cluster data.
Input
-----
X: {numpy array}, shape (n_samples, n_... |
import numpy as np
import scipy.linalg as la
from rlapy.comps.qb import QBFactorizer
class SVDecomposer:
def __call__(self, A, k, tol, over, rng):
"""
Return U, s, Vh where, for some integer ell <= k,
U is A.shape[0]-by-ell,
s is a vector of length ell,
Vh is e... |
<reponame>mbdevpl/hpctoolkit_dataframe<filename>hpctoolkit_dataframe/hpctoolkit_dataframe.py
"""Operate on HPCtoolkit XML database files as pandas DataFrames."""
from cmath import sqrt # used in formulas for metrics
import collections
import logging
import pathlib
import pprint
import re
import typing as t
import xml... |
import os
from mms import MMS
import numpy as np
import scipy.sparse as sp
import iast
class SysParams:
def __init__(self):
self.spatial_discretization_method = 0
self.u_0 = 0
self.t_end = 0
self.dt = 0
self.nt = 0
self.p_in = 0
self.p_out = 0
self.n... |
<reponame>ameya30/IMaX_pole_data_scripts<gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 22 11:01:02 2017
@author: prabhu
"""
import numpy as np
from astropy.io import fits
from matplotlib import pyplot as plt
from scipy.io import readsav
from scipy.ndimage.morphology import binary_di... |
<filename>Video_Modifier_Core/Video_Modifier_Core.py
#source: https://github.com/federico-terzi/bipcut/blob/master/bipcut.py author <NAME>
#modified by <NAME>
# MIT License
#
# Copyright (c) 2018 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associate... |
import numpy as np
import scipy.ndimage as nd
def shift(x, offset=(0, 0)):
if len(x.shape) == 3:
y = np.zeros_like(x)
for c in xrange(x.shape[2]):
y[:, :, c] = shift(x[:, :, c], offset=offset)
return y
y = nd.interpolation.shift(x, shift=offset, mode='nearest')
return y... |
<filename>align_images/cc2d.py
#!/usr/bin/env python3
''' A set of methods for computing the cross-correlation of 2D images.
Currently, 3 methods are provided for computing the cross-correlation (CC),
each implementing different boundary conditions:
- explicit: multiplication in the real space.
- dft: multiplication... |
# Copyright 2021 <NAME> (<EMAIL>)
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, s... |
<reponame>kamnsv/awpy<filename>awpy/analytics/nav.py
from multiprocessing.sharedctypes import Value
import networkx as nx
import numpy as np
from awpy.data import NAV, NAV_GRAPHS
from scipy.spatial import distance
def point_in_area(map_name, area_id, point):
"""Returns if the point is within a nav area for a map... |
<gh_stars>1-10
from xgboost import DMatrix
from joblib import Parallel, delayed
from random import sample
import numpy as np
import scipy.sparse as sps
from sklearn.feature_extraction import FeatureHasher
#import gensim as gs
from time import time
from .utils import printline, partition
# pair means here (thm features... |
import csv
import numpy as np
# import matplotlib.pyplot as plt
from scipy import stats
from collections import defaultdict
MAX_FILES = 4
def get_data(filename):
csvfile = open(filename)
reader = csv.reader(csvfile)
data = []
for i, row in enumerate(reader):
if i == 0:
headers = ... |
<filename>DeepLearning/RunNN.py<gh_stars>0
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 8 22:05:38 2018
@author: Chandar_S
"""
from cnn import cnn
from fnn import fnn
from rnn import rnn
from nn_utilities_py import nn_utilities
import tensorflow as tf
from scipy.misc import imread
import os
import numpy as np
impo... |
"""Routines for trust-region based local search.
This module contains all functions that are necessary to implement a
trust-region based local search to refine the solution quality. The
local search exploits a linear model of the objective function.
Licensed under Revised BSD license, see LICENSE.
(C) Copyright Inter... |
"""Programme to approximate the optimal bandwidth for the Dagum mixture used in
the simulation. The approximation is based on estimating the mean integrated
squared error when using the kernel density estimator with a Gaussian kernel.
"""
import numpy as np
import json
import pickle
from scipy.stats import burr
from ... |
import numpy as np
import networkx as nx
import pandas as pd
from .Projection import projection
from scipy.stats import t
from time import sleep
import tracemalloc
def getfe(result, epsilon=1e-8, normalize = False, category_input = []):
"""
This function is used to get fixed effect.
:param result: result ... |
'''
Particle filter class
'''
from math import sqrt
import matplotlib.pyplot as plt
import numpy as np
from numba import jit, njit, prange
from numpy import pi
from numpy.linalg import norm
from numpy.random import randn, uniform
from scipy.stats import norm as statsnorm
from .stats import percentile
def _weighted... |
<gh_stars>0
#!/usr/bin/env python
import matplotlib.pyplot as plt
import numpy as np
import scipy.special
from common_pv import *
from nav_msgs.msg import Odometry
from nav_msgs.msg import Path
from geometry_msgs.msg import PoseArray, Pose, Twist, PoseStamped
from ackermann_msgs.msg import AckermannDriveStamped
from a... |
# -*- coding: utf-8 -*-
"""Layout Estimation Func Final.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1rJYpB2EAQ8b0Hosq45WYHOq-FAnQm6qd
### Functions
"""
# Detect Intersection #
import math
from sklearn.preprocessing im... |
<gh_stars>1-10
# /******************************************
# *MIT License
# *
# *Copyright (c) [2021] [<NAME>, <NAME>, <NAME>, <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 the Softwar... |
<reponame>tobsen2code/pyleecan
from .get_boundary_condition import get_boundary_condition
from numpy import pi
from ...Classes.Arc import Arc
from ...Classes.Arc2 import Arc2
import cmath
tol = 1e-6
def draw_surf_line(
surf,
mesh_dict,
boundary_prop,
factory,
gmsh_dict,
nsurf,
mesh_size,
... |
<filename>BarycentricInterpolation.py<gh_stars>1-10
#!/usr/bin/env python
import numpy as np
import pandas as pd
from damask.orientation import Orientation
from scipy import spatial
def calcBarycentricCoords(pt, verts):
"""calculate the Barycentric coordinates"""
verts = np.array(verts) # vertices formed... |
<filename>fbastani-solution/run_test.py
#!/usr/bin/python
import model4u_big as model
from graphextract.discoverlib import graph
import georasters
from multiprocessing import Pool
import numpy
import os
from PIL import Image
import random
import scipy.ndimage
import shutil
import skimage.morphology
import subprocess
... |
from .scVectorField import VectorField
import numpy as np
from scipy.integrate import odeint
def fate(VecFld, init_state, t_end=100, step_size=0.01, direction='both', average=False):
"""Predict the historical and future cell transcriptomic states over arbitrary time scales by integrating vector field
function... |
<reponame>crodriguez1a/inver-synth<gh_stars>10-100
import h5py
import numpy as np
from scipy.io import wavfile
from tensorflow import keras
class SoundDataGenerator(keras.utils.Sequence):
"Generates data for Keras"
def __init__(
self,
data_file=None,
batch_size=32,
n_samps=163... |
from collections import defaultdict
from pathlib import Path
from zipfile import ZipFile
import numpy as np
from d3d.abstraction import (EgoPose, ObjectTag, ObjectTarget3D, Target3DArray,
TransformSet)
from d3d.dataset.base import (TrackingDatasetBase, expand_idx, expand_idx_name,
... |
#!/usr/bin/env python
"""Utility functions and classes for creating mixture models"""
########################################################################
# File: mixture_model.py
#
# Author: <NAME>
# History: 1/7/19 Created
########################################################################
import os
import... |
'''
Evaluation code for the SICK dataset (SemEval 2014 Task 1)
'''
from __future__ import print_function
import numpy as np
import os.path
from sklearn.metrics import mean_squared_error as mse
from scipy.stats import pearsonr
from scipy.stats import spearmanr
from sklearn.utils import shuffle
from keras.models import ... |
"""
prob.py
Some probability functions used for Machine Learning programming in Python.
<NAME> (<EMAIL>)
"""
from __future__ import division
import collections
import operator
import numpy as np
import numpy.linalg as linalg
import numpy.random as random
import scipy.stats as stats
from scipy import constants
from ... |
<reponame>kristianwiklund/AOC2019
1#!/usr/bin/python3
import sys
import scipy, numpy, scipy.spatial
import matplotlib.pyplot as plt
from scipy.spatial.transform import Rotation as R
ipp = {}
for i in sys.stdin:
t = i.split()
j = i.split(",")
if "---" in i:
scanner=int(t[2])
print("Loading... |
import numpy as nu
import scipy
_SCIPY_VERSION= [int(v.split('rc')[0])
for v in scipy.__version__.split('.')]
if _SCIPY_VERSION[0] < 1 and _SCIPY_VERSION[1] < 10:
from scipy.maxentropy import logsumexp
elif _SCIPY_VERSION[0] < 1 and _SCIPY_VERSION[1] < 19:
from scipy.misc import logsumexp
else:... |
import os
from datetime import datetime
from scipy.io import savemat
import numpy as np
import PIL.Image
import torch.optim as optim
import torch
from utils_ME import vid_deprocess, vid_preprocess, normalise_vid, rgb2gray, create_feature_mask_ME, save_video, save_gif, gaussian_blur_ME
def reconstruct_stim(features,... |
<reponame>jarreguit/pymoo
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats
from prettytable import PrettyTable
from pymoo.algorithms.moo.gde3 import GDE3
from pymoo.algorithms.moo.nsga2 import NSGA2
from pymoo.algorithms.soo.nonconvex.cmaes import SimpleCMAES
from pymoo.algorithms.soo.nonconvex.de... |
<reponame>Saujyun/TKP
from __future__ import print_function, absolute_import
import os
import gc
import sys
import time
import math
import h5py
import scipy
import datetime
import argparse
import os.path as osp
import numpy as np
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from torch.aut... |
import warnings
import numpy as np
class KernelPCA:
def __init__(self, n_components, kernel, degree=3, gamma=0.25, coef0=0.0,
random_state=None):
self.n_components = n_components
self.kernel = kernel
self.degree = degree
self.gamma = gamma
self.coef0 = coef... |
<filename>Measures/Negativity_Rabi.py<gh_stars>0
from functools import partial
from scipy import linalg
import numpy as np
import matplotlib.pyplot as plt
import re
def par_trs_1(y): # input is a 4*4 matrix
y_1_1 = y[0:2,0:2] # broken to 2*2 matrix
y_1_2 = y[0:2,2:4]
y_2_1 = y[2:4,0:2]
y_2_2 = y[2:4,2:... |
import os
from argparse import ArgumentParser
import numpy as np
import pandas as pd
from PIL import Image
from matplotlib import pyplot as plt
from scipy.ndimage.measurements import label
import operator
def calc_avg_classif(results_dict: dict, thresholds, output_file):
avg = pd.DataFrame(columns=["Thr", "TP", "... |
import numpy as np
import tensorflow as tf
import scipy.io
vgg_rawnet = scipy.io.loadmat('./imagenet-vgg-verydeep-19.mat')
print("Loaded vgg19 pretrained imagenet")
def build_net(ntype,nin,nwb=None,name=None):
if ntype=='conv':
return tf.nn.relu(tf.nn.conv2d(nin,nwb[0],strides=[1,1,1,1],padding='SAME',nam... |
from collections import namedtuple
from scipy.stats import norm
import numpy as np
import pysubgroup as ps
beta_tuple = namedtuple('beta_tuple',['beta','size'])
class EMM_Likelihood(ps.AbstractInterestingnessMeasure):
tpl=namedtuple('EMM_Likelihood', ['model_params','subgroup_likelihood','inverse_likelihood','siz... |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
#
# This source code is licensed under the BSD license found in the
# LICENSE file in the root directory of this source tree.
"""
Benchmarking utils for timing cuda executions
"""
from collections import defaultdict, deque
from functools import p... |
<filename>dpmm/algorithm_3.py
from numpy import bincount, log, log2, seterr, unique, zeros
from scipy.special import gammaln
from kale.math_utils import log_sample, vi
def iteration(V, D, N_DV, N_D, alpha, beta, z_D, inv_z_T, active_topics, inactive_topics, N_TV, N_T, D_T):
"""
Performs a single iteration of... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from tqdm import tqdm
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from scipy.sparse import hstack
from nltk import word_tokenize
... |
# -*- coding: utf-8 -*-
"""
Module for -- Confusion matrix, contingency, error matrix,
References:
http://en.wikipedia.org/wiki/Confusion_matrix
"""
from __future__ import absolute_import, division, print_function
import utool as ut
import ubelt as ub
import numpy as np
import scipy.interpolate
def testdata_scor... |
'''
Discretize the continuous hybridization function into a discretized model(DiscModel).
checking method is also provided.
'''
from numpy import *
from matplotlib.pyplot import *
from matplotlib import cm
from scipy.interpolate import InterpolatedUnivariateSpline,interp1d
from scipy.integrate import quadrature,cumtra... |
<reponame>chrisfilo/NiMARE<filename>nimare/meta/ibma/base.py
"""
Image-based meta-analysis estimators
"""
from __future__ import division
import numpy as np
from sklearn.preprocessing import normalize
from scipy import stats
from ..base import MetaEstimator
class IBMAEstimator(MetaEstimator):
"""Base class for ... |
import py
import sympy as g
from sympy import *
from sympy.utilities.pytest import XFAIL
from sympy import O
def testseries1():
x = Symbol("x")
e = sin(x)
assert e.series(x,0) != 0
assert e.series(x,0) == O(1, x)
assert e.series(x,1) == O(x, x)
assert e.series(x,2) == x + O(x**2, x)
assert ... |
from anndata import AnnData
import numpy as np
from scanorama import *
import scanpy.api as sc
from sklearn.metrics import silhouette_samples as sil
from scipy.sparse import vstack
from sklearn.preprocessing import normalize, LabelEncoder
import sys
from process import load_names
NAMESPACE = 'shahin'
data_names = [
... |
<gh_stars>10-100
import argparse
import json
import os
import random
import logging
from collections import namedtuple, Counter
from time import time
import h5py
import numpy as np
import faiss
import torch
from tqdm import tqdm
from scipy.sparse import vstack
logging.basicConfig(format='%(asctime)s - %(levelname)s ... |
import sys
import fileinput
import statistics
import math
from parse import parse
if __name__ == '__main__':
SYS_ARGV_LENGTH = 4
assert(len(sys.argv) == SYS_ARGV_LENGTH)
_, nodes, expected_min_cut, measure_full_contraction = sys.argv
expected_min_cut = int(expected_min_cut)
measure_full_contractio... |
import numpy as np
import pickle
from time import time
import pdb
import os
from collections import Counter
import random
import datetime
from scipy import fftpack
def loadSubNormData(mode='all'):
txtFile = '/home/david/Documents/AbnormalProcessing/normEDFfilesB.txt'
f = open(txtFile,'rU')
content = f.rea... |
<gh_stars>10-100
import tensorflow_quantum as tfq
import tensorflow as tf
import cirq
import sympy
import random
import matplotlib.pyplot as plt
import numpy as np
def make_data(n1, n2):
qubit = cirq.GridQubit(0,0)
train, test = [], []
train_label, test_label = [], []
for _ in range(n1):
cir = ... |
import os
import sys
import numpy as np
import ConfigParser
from errno import ENOENT
from numpy import loadtxt
from pandas import read_excel, read_csv
from collections import OrderedDict
from scipy.interpolate import interp1d
from distutils.util import strtobool
from astropy.io import fits as astropyfits
# Function t... |
import json
import numpy as np
import matplotlib.pyplot as plt
import os
from scipy.stats.stats import pearsonr
from scipy.stats.stats import spearmanr
from sklearn.model_selection import train_test_split
from sklearn import ensemble
from sklearn.dummy import DummyClassifier
from sklearn.linear_model import LinearRegr... |
""" The Analytical distribution"""
from equadratures.distributions.recurrence_utils import jacobi_recurrence_coefficients
from equadratures.distributions.template import Distribution
import numpy as np
import scipy.stats as stats
from scipy.special import erf, erfinv, gamma, beta, betainc, gammainc
RECURRENCE_PDF_SAMPL... |
<gh_stars>1-10
from director import robotsystem
from director.consoleapp import ConsoleApp
from director import robotstate
from director import planplayback
from director import lcmUtils
from director import drcargs
from director import roboturdf
from director import simpletimer
from director.timercallback import Timer... |
import numpy as np
from collections import deque
from scipy.spatial.distance import cdist
from cluster._cluster_means import update_cluster_means
def euclidean_distance(x1, x2):
"""Squared distance
We are ignoring the sqrt here to since it
does not affect k-means, and we gain a bit
of speed.
N... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 19 14:55:53 2021
@author: ghiggi
"""
import numpy as np
import xarray as xr
import shapely
import matplotlib as mpl
import matplotlib.patches as mpatches
import cartopy.crs as ccrs
from scipy.interpolate import griddata
from scipy.spatial import ... |
"""
Helper module with function and classes to emulate 1d wave surface and buoy trajectory.
"""
from collections import namedtuple
import numexpr as ne
import numpy as np
from abc import abstractmethod, ABC
from scipy.interpolate import interp1d
from spectrum_processing_1d.processing import calculate_acceleration
Tr... |
<filename>examples/relabel.py<gh_stars>1-10
""" Functions for matching only and creating a csv
with the new global coords and if they are
to be erased ----------------------------------Relabel2 """
import os
# nb2
import sqlite3
import sys
import IPython.display
import matplotlib.pyplot as plt
import numpy as np
impo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.