text string |
|---|
from CQS.methods import *
import matplotlib.pyplot as plt
from CQS.util.IO import tuplesToMatrix
from CQS.util.PauliOps import X, Y, I
from CQS.util.verification import KHK, exactU
from numpy.fft import fft, fftfreq
from numpy import kron
import numpy as np
import scipy as sci
from scipy.signal import find_peaks
#Gre... |
<gh_stars>0
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 26 19:53:49 2016
@author: YPC
"""
import numpy as np
from scipy.sparse import csr_matrix
import csv
row = np.array([0, 0, 1, 2, 2, 2])
col = np.array([0, 2, 2, 0, 1, 2])
data = np.array([1, 2, 3, 4, 5, 6])
csr_matrix((data, (row, col)), shape=(3, 3... |
"""
:synopsis: Plotting persistence and barcode diagrams and calculating clusters.
"""
# standard library imports
import collections
# third party imports
from matplotlib import pyplot
import numpy
import scipy
import ripser
import persim
def product_metric(nd_array_1, nd_array_2):
"""Calculate a product metric... |
# Copyright 2016-present CERN – European Organization for Nuclear Research
#
# 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... |
<reponame>sigeisler/robustness_of_gnns_at_scale
from typing import Any, Dict, Union, List
from torchtyping import TensorType, patch_typeguard
from typeguard import typechecked
import logging
from abc import ABC, abstractmethod
import torch
import torch.nn.functional as F
import numpy as np
import scipy.sparse as sp
f... |
import itertools
import operator
import numbers
import scipy.sparse as sparse
from findiff.coefs import coefficients, coefficients_non_uni
from .stencils import Stencil
from .utils import *
from .grids import Grid
DEFAULT_ACC = 2
class Operator(object):
""" Base class for all operator classes """
pass
clas... |
<filename>consistency_test/VoxelTest/rsHRF_python.py
import os
import time
import numpy as np
import nibabel as nib
from scipy import stats
from rsHRF import spm_dep, processing, utils, basis_functions
import warnings
warnings.filterwarnings("ignore")
# Create outputfolder
output_folder = os.getcwd() + '/Data'
if n... |
"""
The bpm module contain the Bpm class used to simulate the light propagation -
within low refractive index variation
and small angle (paraxial approximation) -
using the Beam Propagation Method.
This module was done by <NAME> during a master
university course from the PAIP master of the université de Lorraine,
unde... |
<reponame>Joshuaalbert/bayes_tec<filename>src/bayes_tec/utils/stat_utils.py
import numpy as np
from scipy.optimize import fmin,minimize
def log_normal_solve(mean,std):
mu = np.log(mean) - 0.5*np.log((std/mean)**2 + 1)
sigma = np.sqrt(np.log((std/mean)**2 + 1))
return mu, sigma
def log_normal_solve_fw... |
import numpy as np
import scanpy as sc
import math
from statsmodels.stats.proportion import proportions_ztest
from cluster.cli.cli import centroids
from scipy.stats import ttest_ind
"""
import pandas as pd
def kitchen_sink(ad, cluster_name="louvain"):
X = ad.X.toarray()
#X = (X / X.sum()) * 10000
cluster_... |
#! python3
# -*- coding: utf-8 -*-
"""mwxlib graph for image
Author: <NAME> <<EMAIL>>
"""
from __future__ import division, print_function
from __future__ import unicode_literals
from __future__ import absolute_import
import traceback
import sys
import wx
try:
import framework as mwx
from matplot2 import Matplo... |
<gh_stars>1-10
"""manual:
https://gist.github.com/taruma/60725ffca91dc6e741daee9a738a978b"""
import numpy as np
import pandas as pd
from scipy import stats, interpolate
# tabel dari Soewarno, hal. 219
# lampiran tabel III-3, Nilai k Distribusi Pearson tipe III
# dan Log Pearson ti
# kode: SW
_DATA_SW = np.array([
... |
<gh_stars>1-10
#!/usr/bin/env python
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
import numpy as np
from astropy import cosmology
from scipy import stats
import ReadScripts as rs
import PlotScripts as ps
import CollectiveStats as collective
import Observa... |
import math, random, statistics
from dataclasses import dataclass
from collections import Counter, defaultdict
class CounterWithMode(Counter):
def mode(self):
try:
return self.most_common(1)[0][0]
except IndexError:
return None
@dataclass(frozen=True)
class Observation:
classification: str
f... |
<gh_stars>0
import numpy as np
from scipy import signal
from models.utils import sqrt_gain_db, design_high_shelving_filter
class PresenceModel:
def __init__(self, configuration):
self._configuration = configuration
self._sos = np.array([[1, 0, 0, 1, 0, 0],
[1, 0, 0, ... |
<filename>pydatatool/citypersons/utils.py<gh_stars>10-100
import argparse
import os
from scipy import io as scio
from pydatatool.utils import save_json
"""
{
"categories":[{"id":1,"name":"pedestrian"},
{"id":2,"name":"rider"},
{"id":3,"name":"sitting person"},
{... |
# emacs: -*- mode: python-mode; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the NiBabel package for the
# copyright and license terms.
#
### ### ### #... |
<reponame>Tjorriemorrie/trading
import pandas as pd
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
from matplotlib.dates import YearLocator, MonthLocator, DateFormatter
from sklearn.ensemble import RandomForestRegressor
from sklearn.cross_validation import cross_val_score
import sklearn as sk
imp... |
#! /usr/bin/env python3
"""
"""
# MIT License
#
# Copyright (c) 2016 <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 Software without restriction, including without limitation the ... |
from gimpfu import *
import gimpcolor
import time
import sys
import shortuuid
import completion_pb2
import numpy as np
import cv2
from PIL import Image
from scipy.ndimage.morphology import binary_dilation, binary_erosion
def drawable_of_file(filename):
'''
Load a file and return the the drawable.
A call... |
# ###########################################################################
#
# CLOUDERA APPLIED MACHINE LEARNING PROTOTYPE (AMP)
# (C) Cloudera, Inc. 2020
# All rights reserved.
#
# Applicable Open Source License: Apache 2.0
#
# NOTE: Cloudera open source products are modular software products
# made up of hu... |
<filename>refnx/reflect/reflect_model.py
"""
*Calculates the specular (Neutron or X-ray) reflectivity from a stratified
series of layers.
The refnx code is distributed under the following license:
Copyright (c) 2015 <NAME>, ANSTO
Permission to use and redistribute the source code or binary forms of this
software and... |
import pickle, pandas as pd
import numpy as np
import glob
import os.path as osp
import re
from scipy.stats import rankdata as rd
def identity(x): return x
def load_pickle(fp):
with open(fp, 'rb') as f: return pickle.load(f)
def get_df(fp):
pp = rd if RANKDATA else identity
x = load_pickle(fp)
if n... |
<reponame>jllanfranchi/pygeneric<filename>mystats.py<gh_stars>0
import scipy.stats as stat
import scipy.optimize as opt
import numpy as np
import lmfit
def var_ci(var, n, ci):
df = n - 1
tail_prob = (1.-ci)/2.
chi2_left = stat.chi2.ppf(q=tail_prob, df=df)
chi2_right = stat.chi2.ppf(q=1-tail_prob, df=df... |
<reponame>jiadonglee/laspec
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os, sys, io
import warnings
import numpy as np
import pandas as pd
from astropy.io import fits, ascii
from astropy.table import Table
import scipy.signal
import urllib.request
import urllib.parse
import requests
'''
Pipeline by Created by <N... |
<gh_stars>10-100
# Original source here: https://www.kaggle.com/tunguz/logistic-regression-with-words-and-char-n-grams
import argparse
import pickle
import time
import pandas as pd
import scipy.sparse
from sklearn.model_selection import train_test_split
from tqdm import tqdm
from toxic_utils import *
from willump.eva... |
from imagepy import IPy
import numpy as np
from imagepy.core.engine import Filter
from imagepy.ui.panelconfig import ParaDialog
from imagepy.ui.widgets import CurvePanel
from scipy import interpolate
class ThresholdDialog(ParaDialog):
def init_view(self, items, para, hist):
self.curvep = CurvePanel(self)
... |
# Copyright(c) 2014, The LIMIX developers (<NAME>, <NAME>, <NAME>)
#
# 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 app... |
#!/usr/bin/env python
"""
Condense a raw sample file generated by USPR, removing idle periods.
"""
import os
import argparse
import scipy
import itertools
import struct
WINDOW = 80
def main():
parser = argparse.ArgumentParser()
parser.add_argument('file', help="Raw sample file")
parser.add_argument('--... |
#!/usr/bin/env python3
"""
Wrappers for scipy.io.wavfile
"""
import numpy as np
import scipy.io.wavfile
import os.path
from typing import Tuple
def _sum_to_mono(filename:str, data: np.ndarray, warn_if_mono_sum=True) -> np.ndarray:
if len(data.shape) == 1:
return data
n_channels = data.shape[1]
if n_channe... |
<filename>quantiphyse/processes/feat_pca.py<gh_stars>1-10
"""
Quantiphyse - PCA implementation
Copyright (c) 2013-2020 University of Oxford
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... |
from __future__ import division
# Copyright (c) 2015 <NAME>
# Licensed under the BSD 3-clause license (see LICENSE.txt)
import numpy as np
from scipy import stats,special
import scipy as sp
from ..core.parameterization import Param
from ..core.parameterization.transformations import Logexp
from . import link_functions... |
import os
import sys
import subprocess
from typing import Literal
from tqdm import tqdm
import numpy as np
from scipy.io import loadmat
import cv2
import torch
from torch.nn import functional as F
from torch.utils.data import Dataset
from torchvision import datasets, transforms
from vaetc.utils.debug import debug_pr... |
<reponame>ExoWorldsSpies/hops-2.6.8
import warnings
warnings.filterwarnings(
'ignore', message='Matplotlib is building the font cache using fc-list. This may take a moment.')
warnings.filterwarnings(
'ignore', message='The installed version of numexpr 2.4.4 is not supported in pandas and will be not be used... |
from pymongo import MongoClient
import pprint
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas as pd
import numpy as np
import statsmodels.api as sm
import statsmodels.stats.api as sms
from scipy import stats
import pylab as py
from statsmodels.graphics import tsaplots
from sklearn.compos... |
<reponame>brightghost/panawave-umbrella<filename>radialstructs.py
import logging as log
from math import degrees, radians
from cmath import exp
from random import random, randint
from time import sleep
import json
import os
class RotatingPoly:
'''test class for animating and rotating methods'''
def __init__(... |
#Ref: <NAME>
"""
All cell images resized to 128 x 128
Images used for test are completely different that the ones used for training.
136 images for testing, each parasitized and uninfected (136 x 2)
104 images for training, each parasitized and uninfected (104 x 2)
"""
import cv2
import numpy as np
import os
import... |
# License: BSD 3 clause
import numpy as np
from scipy.sparse import csr_matrix
import unittest
from tick.preprocessing import LongitudinalFeaturesLagger
class Test(unittest.TestCase):
def setUp(self):
self.features = [
np.array([[0, 1, 0], [0, 0, 0], [0, 1, 1]], dtype="float64"),
... |
"""Tests for piece.py"""
from fractions import Fraction
import pandas as pd
import numpy as np
from harmonic_inference.data.data_types import KeyMode, PitchType
from harmonic_inference.data.piece import Note, Key, Chord, ScorePiece, get_reduction_mask
import harmonic_inference.utils.harmonic_constants as hc
import ha... |
"""
Wrapper for Segmentation Evaluation.
Author: <NAME>
License: MIT
Copyright: 2018-2019
"""
import sys
sys.path.insert(0, "./..")
import torch
import os.path
import argparse
from scipy import misc
from models import create_model
from data.png_dataset import PngDataset
from options.train_options import TrainOptions
f... |
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.patches import FancyArrowPatch
from mpl_toolkits.mplot3d import proj3d
import numpy as np
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import scipy as sp
import matplotlib.colors as colors
import cv2
from draw import *
fr... |
# AUTOGENERATED! DO NOT EDIT! File to edit: notebooks_dev/dist.ipynb (unless otherwise specified).
__all__ = ['get_distribution_var_factor_jaccard', 'pointwise_variance',
'estimate_mean_and_variance_from_neighbors_mixture', 'sample_from_neighbors_continuous', 'PointwiseMixture',
'JaccardPointwise... |
<reponame>rekords-uw/Profiler-public<gh_stars>0
from __future__ import division
from profiler.globalvar import *
from concurrent.futures import ThreadPoolExecutor
from tqdm import tqdm
import pandas as pd
import numpy as np
import logging
from sklearn import preprocessing
from scipy.cluster.vq import vq, kmeans, whiten... |
<gh_stars>1-10
import cv2
from scipy import ndimage
import numpy as np
def warp_image(image, width, height):
#defining target rectangle
tl = [272,225]
tr = [439,226]
br = [773,419]
bl = [6,401]
target_rectangle = np.float32([tl,tr,br,bl])
# defining image parameters
imgtl = [0,0]
... |
import numpy as np
from scipy.interpolate import CubicSpline, interp1d
from scipy.signal import correlate
from scipy.optimize import least_squares
import matplotlib.pyplot as plt
def find_rv0(shft, lambd, flat_obj, flat_std, pixscale, oversamp):
"""
Function for finding the wavelength shift between the... |
import glob
import ntpath
import matplotlib.pyplot as plt
import statistics
def read_folder(folder):
data = []
folder = folder + "/*"
all_files = glob.glob(folder)
for file in all_files:
basename = ntpath.basename(file)
if basename.startswith("out"):
f = open(file, "r")
... |
'''
MinibatchIteratorFromDisk.py
Extension of MinibatchIterator
reads in data that has been pre-split into batches on disk.
Usage:
construct by providing a list of valid filepaths to .mat files (see XData for format)
then call has_next_batch()
get_next_batch()
Traversal order of the files ... |
#!/usr/bin/python
#
# The MIT License (MIT)
#
# Copyright (c) 2015 <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 Software without restriction, including without limitation the rights
# to u... |
<gh_stars>1-10
""" Class to read the result data """
import os
import pickle
import numpy as np
from scipy.signal import find_peaks
class DataReader(object):
""" Class to read the result data """
def __init__(self, spatial_conv=False, path='', n_draws=200, readout_time=3950):
# shall we use dirac s... |
<gh_stars>0
"""
Main script for future simulations. Separated from main script for calibrations to be cleaner for development, but
should consider merging back in future.
"""
import pandas as pd
import numpy as np
from datetime import datetime
import os
import xarray as xr
import netCDF4 as nc
from time import strfti... |
<reponame>DavidStirling/CellProfiler-Analyst<filename>cpa/dirichletintegrate.py<gh_stars>10-100
# CellProfiler is distributed under the GNU General Public License,
# but this file is licensed under the more permissive BSD license.
# See the accompanying file LICENSE for details.
from numpy import *
from scipy.integra... |
<reponame>WesleyClode/MBIMC-GAE
'''
Created on Aug 8, 2016
Processing datasets.
@author: <NAME> (<EMAIL>)
'''
import scipy.sparse as sp
import numpy as np
from time import time
class Dataset(object):
'''
Loading the data file
trainMatrix: load rating records as sparse matrix for class Da... |
import time
import numpy as np
import scipy.stats as st
class EM:
def __init__(self, K):
self.K = K # number of clustering / Gaussian mixture
self.D = None # dimension, depend on the input point when training
self.mu_set = None # mean of each mixture, [ K * D ]
self.co... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 14 15:32:09 2019
@author: nico
"""
import numpy as np
import scipy.signal as scsg
#%% senoidal
"""
brief: Generador de señales senoidal, con argumentos
fs: frecuencia de muestreo de la señal [Hz]
N: cantidad de muestra... |
"""pca.py: Contains a class for Principal Component Analysis."""
__author__ = "<NAME>, <NAME>"
__email__ = "<EMAIL>, <EMAIL>"
__status__ = 'Development'
import numpy as np
from scipy.linalg import eig, norm
class PCA(object):
"""Class that handles dimensionality reduction via princinpal
component anlysis.""... |
import unittest, view_stats, os, statistics, numpy
class TestStats(unittest.TestCase):
def setUp(self):
self.score_file_path = "/home/vagrant/adapt/ad/test/scores/unittest.csv"
self.feature_file_path = "/home/vagrant/adapt/ad/test/features/unittest.csv"
self.view_name = "unittest"
s... |
<filename>driver.py<gh_stars>0
#!/usr/bin/env python3
from argparse import Namespace
from gc import collect
from os import makedirs, dup, dup2, open as osopen, close, devnull, O_WRONLY
from os.path import join, abspath, dirname, isabs, basename, curdir
from typing import Tuple
import matplotlib.pyplot as plt
import n... |
<reponame>CS540-Testers-SP22/hw4-tester
'''
These tests were inspired by and use code from the tests made by
cs540-testers-SP21 for the Spring 2021 semester.
Their version (1.0) can be found here:
https://github.com/cs540-testers-SP21/hw4-tester/
Subsequently, their version was also inspired by and use code ... |
from __future__ import print_function, division
import sys
sys.path.insert(0, 'lib')
import numpy as np
import random
import pydicom
import os
import matplotlib.pyplot as plt
import pickle
import math
import pydicom
from shutil import copyfile
import nibabel as nib
import scipy.ndimage as ndimage
from scipy.stats impor... |
<gh_stars>0
import numpy as np
from scipy.integrate import odeint
from lmfit import minimize, Parameters, Parameter, report_fit
from src.d00_utils.conf_utils import *
from src.d02_extraction.extract_least_sq_fit import *
def g(t, y0, coefs, f):
"""
Solution to the ODE y'(t) = f(t,y,k) with initial condition ... |
# LICENSE: Simplified BSD https://github.com/mmp2/megaman/blob/master/LICENSE
from __future__ import division ## removes integer division
import numpy as np
from nose import SkipTest
from numpy.testing import assert_array_almost_equal, assert_allclose
from scipy.spatial.distance import pdist, squareform
from megaman.... |
######
# this script containing matrix generators is solely developed and written by <NAME>
######
import random
from matrixOperations import*
from sympy import*
#####################################################################################################
# from 15-112 course notes
def callWithLargeStack(f,*arg... |
<filename>torch_mlc.py
import numpy as np
from scipy.signal import get_window
import torch
import torch.nn as nn
import torch.nn.functional as F
def _peak_picking(x):
mask = (x[:, 1:-1] > x[:, :-2]) & (x[:, 1:-1] > x[:, 2:])
return F.pad(mask, (1, 1))
def _pitch_profile(x, *args):
filterbank = torch.spa... |
import argparse
import numpy as np
from numpy.linalg import svd, norm
from scipy.spatial.transform import Rotation as R
import matplotlib.path as mpltPath
def read_pdb(file_path):
"""
Function to read in pdb file and output as list of atoms and positions
ARGS:
file_path (str): path to pdb file
R... |
<gh_stars>10-100
#!/usr/bin/env python3
''' general eigenvalue decomposition'''
import numpy as np
from scipy import linalg
__author__ = "<NAME> and <NAME>"
__email__ = "<EMAIL>,<EMAIL>"
def gevd(x1,x2,no_pairs):
'''Solve generalized eigenvalue decomposition
Keyword arguments:
x1 -- numpy array of size [NO_chan... |
"""
Calculate various stats regarding how associated a context token is with contentiousness.
Output: stats/stats_{depth}.csv
Process:
* load the annotation set (controls already removed):
* remove 'Weet ik niet' and 'Onleesbare...' annotations
* case-fold target words
* With respect to the t... |
<reponame>anuj-harisinghani/canary-nlp
import copy
from classes.handlers.ParamsHandler import ParamsHandler
import pandas as pd
from scipy import stats
import numpy as np
'''
to be called inside trainers
'''
class FeatureSelector:
def __init__(self):
params = ParamsHandler.load_parameters('settings')
... |
# pylint: disable=no-member
"""Widget to convert SMILES to nanoribbons."""
import numpy as np
from scipy.stats import mode
import re
from IPython.display import clear_output
import ipywidgets as ipw
import nglview
from traitlets import Instance
from ase import Atoms
from ase.data import covalent_radii,chemical_symb... |
# encoding: utf-8
import pywt
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from scipy import signal
#--读取数据--
def ReadFile(filename):
#filename = 'data.txt'
data = []
with open(filename, 'r') as file_to_read:
while True:
lines = file_to_... |
"""
Fifth Attempt at making the emission spectra simulator
"""
import os
import sys
import itertools
import numpy as np
import pandas as pd
from scipy import stats
import scipy.integrate
import scipy.optimize
from scipy.interpolate import interp1d
from scipy.interpolate import RegularGridInterpolator
import matpl... |
#!/usr/bin/env python
""" Utility module. All auxiliary functions go here.
This module provides internal functionalities for everything else, aside from
handling the internal details of running the simulation itself. There is a
plethora of varied functions, so it's best left alone unless strictly necessary.
Do not mo... |
<reponame>stephensekula/OLeAA<gh_stars>0
import sys
import pandas as pd
import numpy as np
import uproot3 as uproot
import scipy
import math
import glob
from uproot_methods import *
from concurrent.futures import ThreadPoolExecutor
# Define useful variables
## Units
global u_fb,u_mb,u_pb
u_fb = 1
u_mb = 1e12*u_fb
... |
<gh_stars>1-10
"""
Modified from:
Animation of Elastic collisions with Gravity
author: <NAME>
email: <EMAIL>
website: http://jakevdp.github.com
license: BSD
Please feel free to use and modify this, but keep the above information. Thanks!
Modified by: <NAME>, <NAME>
2020
"""
import numpy as np
from scipy.spatial.dis... |
<reponame>isabelline/QualityEstimation_fairseq
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the LICENSE file in
# the root directory of this source tree. An additional grant of patent rights
# can be found in the PATENTS file in the same... |
import numpy as np
import pandas as pd
import scipy.optimize
# Import own modules
import lbfcs.varfuncs as varfuncs
import lbfcs.multitau as multitau
#%%
def trace_ac(df,NoFrames,field = 'photons',compute_ac=True):
'''
Get fluorescence trace for single pick and normalized multitau autocorrelation function (AC... |
<reponame>muradtuk/ProjectiveClusteringCoresets
"""*****************************************************************************************
MIT License
Copyright (c) 2022 <NAME>, <NAME>, <NAME>, <NAME>, <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associa... |
<gh_stars>1-10
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Run Monte Carlo simulation on resistance mismatch to obtain a distribution for VCCS output resistance"""
import matplotlib as mpl
import matplotlib.font_manager as fm
# mpl.rc('font', **{'family': 'serif', 'serif': ['Computer Modern']})
mpl.rcParams['fon... |
import pytest
import numpy as np
import scipy.sparse as sp
from lightfm.datasets import fetch_movielens, fetch_stackexchange
def test_basic_fetching_movielens():
data = fetch_movielens()
assert isinstance(data['train'], sp.coo_matrix)
assert isinstance(data['test'], sp.coo_matrix)
assert data['t... |
"""A little extension to the python3 math library.
B.t.w. when called as a standalone script, it solves Problem #5 of Project Euler
(https://projecteuler.net): 2520 is the smallest number that can be divided by each of
the numbers from 1 to 10 without any remainder. What is the smallest positive
number that is evenly ... |
"""
This module defines the method to obtain the watershed labels for the given dataset.
"""
import numpy as np
import pdb
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader, Subset
import higra as hg
from mlpack import emst
import scipy as sp
def _euclid_distance(X, u, v):
""... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 26 14:22:27 2021
@author: suraj
"""
import pyvista as pv
import numpy as np
import matplotlib.pyplot as plt
from pyvista import examples
from scipy.integrate import odeint
filename = f'../../../Similarity_Solution/su2.csv'
data_blasisus = np.genfr... |
<gh_stars>1-10
import cwb.templates
import numpy as np
import yaml
import os
import scipy.linalg
import pickle
import argparse
import subprocess
try:
import importlib.resources as pkg_resources
except ImportError:
# Try backported to PY<37 `importlib_resources`.
import importlib_resources as pkg_resources... |
import numpy as np
from numexpr import evaluate
from math import pi
from scipy.linalg import solve
from scipy.special import jv
# basic periodic scatter information
from novice_stakes.periodic_scatter import Bragg
# complete reflection coefficent calculation modules to check results
from novice_stakes.periodic_scatte... |
import torch
import torch.optim as optim
from torch.utils.data import DataLoader
import numpy as np
from tqdm import tqdm
import pandas as pd
from sklearn.metrics.pairwise import cosine_similarity
from nltk.metrics.spearman import spearman_correlation
from scipy.stats import spearmanr
import os
import sys
from data_re... |
from __future__ import division
from sympy import Rational, oo
from sympy import Line, Point, Point2D, Parabola
from sympy.utilities.pytest import raises
def test_parabola_geom():
p1 = Point(0, 0)
p2 = Point(3, 7)
p3 = Point(0, 4)
p4 = Point(6, 0)
d1 = Line(Point(4, 0), Point(4, 9))
d2 = Line... |
<filename>src/binomial.py
from scipy.stats import binom
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(1, 1)
# Calculate a few first moments:
n, p = 5, 0.4
mean, var, skew, kurt = binom.stats(n, p, moments='mvsk')
# Display the probability mass function (``pmf``):
x = np.arange(binom.ppf... |
import pytest
import scipy.stats as stats
from numpy import array, asarray, eye, hstack, ones, sqrt, stack, tile, zeros
from numpy.random import RandomState
from numpy.testing import assert_allclose
from struct_lmm2 import StructLMM2
from struct_lmm2._simulate import (
column_normalize,
create_environment_matr... |
import math
from fractions import Fraction
from aigerbv import atom, ite
# Python is deprecating fractions.gcd....
# https://stackoverflow.com/questions/147515/least-common-multiple-for-3-or-more-numbers/147539#147539 # noqa: E501
def lcm(a, b):
"""Return lowest common multiple."""
return a * b // math.gcd(... |
"""
<NAME>
Training and validation of EENet
"""
from __future__ import print_function
import time
import csv
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
from scipy import stats
from init import initializer
from eenet import EENet
from custom_eenet import CustomEENe... |
import functools
import numpy as np
from PIL import Image
from . import tag
from .exif import ExifReader
def getcoordinates(w, h, r):
uu, vv = np.meshgrid(np.arange(w), np.arange(h))
t = (uu - w / 2) * 2 * np.pi / w
p = (vv - h / 2) * np.pi / h
st, ct = np.sin(t), np.cos(t)
sp, cp = np.sin(p), n... |
# coding: utf-8
# # Reading Data
# In[1]:
import numpy as np
import scipy as sp
import pandas as pd
get_ipython().run_line_magic('matplotlib', 'inline')
import matplotlib.pyplot as plt
from collections import defaultdict
# In[2]:
# open docs file and read its lines
with open("../data/raw/train.dat", "r") as f... |
# uncompyle6 version 3.7.4
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]
# Embedded file name: T:\InGame\Gameplay\Scripts\Server\objects\components\object_relationship_component.py
# Compiled at: 2020-09-03 20:55:24
# Size of sou... |
<filename>foolbox/attacks/pgd.py
from __future__ import division
import numpy as np
from .base import Attack
class ProjectedGradientAttack(Attack):
"""L infinity Projected gradient descent attack from Madry et al. 2017.
https://arxiv.org/abs/1706.06083
Only implements xentropy loss for now. Foolbox does... |
<gh_stars>1-10
import numpy as np
from scipy.stats import chi2
from scipy.special import gammaln
def fminESS(p, alpha=.05, eps=.05, ess=None):
"""
Minimum effective sample size
"""
crit = chi2.ppf(1 - alpha, p)
foo = 2. / p
if ess is None:
logminESS = foo * np.log(2.) + np.log(np.pi)... |
#!/usr/bin/env python
#
"""
Adjust a template by multiplying it by a set of scale parametrs
"""
import numpy as np
from fermipy import utils
from gammapy.maps import Map
from scipy.interpolate import interp1d
def make_interpolator(yamlfile):
scale = utils.load_yaml(yamlfile)
emids = (np.array(scale['E_min'... |
#!/usr/bin/env python3
# From https://github.com/AtsushiSakai/PythonRobotics/blob/master/Localization/extended_kalman_filter/extended_kalman_filter.py
import math
from math import sin, cos, pi
import rospy
import tf
from std_msgs.msg import Header
from geometry_msgs.msg import Point, Pose, Quaternion, Twist, Vector3... |
<reponame>sands-lab/rethinking-sparsification<filename>logistic-regression/functions.py
import numpy as np
import random
import time
from numpy.linalg import norm
from scipy.sparse import csr_matrix
from scipy.optimize import minimize
from scipy.special import expit
from copy import deepcopy
from scipy.stats import be... |
import netCDF4
import numpy as np
import pandas as pd
import scipy as sci
# from scipy.spatial import *
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from matplotlib.widgets import Widget
from matplotlib.colors import LogNorm, Normalize
from lmatools.coordinateSystems import Geo... |
"""
Created on Fri Sept 4 11:40:33 2020
@author: <NAME>
"""
import numpy as np
import skimage as sk
import scipy as sp
#import matplotlib.pyplot as mplp
import cv2
#from skimage import color,morphology
#from skimage import segmentation
#from skimage.measure import find_contours
def get_boundary(image):
... |
<filename>plugins/xafs/xafsutils.py
"""
Utility functions used for xafs analysis
"""
import numpy as np
from larch import Group, ValidateLarchPlugin
import scipy.constants as consts
KTOE = 1.e20*consts.hbar**2 / (2*consts.m_e * consts.e) # 3.8099819442818976
ETOK = 1.0/KTOE
MODDOC = '''
XAFS Functions for Larch, esse... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.