text string |
|---|
<reponame>ningeen/cv-validator
from typing import Any, Tuple
from scipy.stats import wasserstein_distance
from cv_validator.utils.constants import ThresholdPSI, ThresholdWasserstein
from cv_validator.utils.psi import calculate_psi
DIFF_METRICS = {
"psi": calculate_psi,
"wasserstein_distance": wasserstein_dis... |
<reponame>sckangz/overlapping-community-detection<gh_stars>10-100
import numpy as np
import scipy.sparse as sp
import torch
import torch.nn as nn
import torch.nn.functional as F
from nocd.nn.gcn import sparse_or_dense_dropout
from nocd.utils import to_sparse_tensor
__all__ = [
'ImprovedGCN',
'ImpGraphConvolut... |
import matplotlib
matplotlib.use('Agg')
import pyart
from matplotlib import pyplot as plt
import numpy as np
import glob
import os
from copy import deepcopy
from distributed import Client
import dask.bag as db
from time import sleep
from datetime import timedelta, datetime
from scipy.optimize import fmin_l_bfgs_b
impo... |
<filename>pybragg/functions.py
#########################################################
#
# author of this file: <NAME>
# email: <EMAIL>
# written: 20.03.2021
#
#########################################################
# needed for spline
from scipy.interpolate import interp1d
# parabolic cylinder function ... |
<reponame>HWPengSYSU1993/DSVNs-model<gh_stars>1-10
"""Training a face recognizer with TensorFlow based on the FaceNet paper
FaceNet: A Unified Embedding for Face Recognition and Clustering: http://arxiv.org/abs/1503.03832
"""
# MIT License
#
# Copyright (c) 2016 <NAME>
#
# Permission is hereby granted, free of charge... |
<reponame>ysoftman/test_code<gh_stars>1-10
# coding: utf-8
# ysoftman
# 참고
# tensorflow vs scikit-learn
# tensorflow 가 deep learning 의 low level 수준의 기능을 제공하는 반면
# scikit-learn 은 이미 정립된 머신러닝 분류(결증트리,svm, p), 회귀, 클러스터링등의 알고리즘을 제공한다.
# scikit-learn 으로 딥러닝, 강화학스등을 구현하기에는 적절하지 않다.
# Machine Learning Recipes with <NAME>
# pi... |
"""Plot the quantile /inverse CDF function"""
import numpy as np
from scipy.stats import norm
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib.patches as mpatches
grid = np.linspace(0,1, 1000).tolist()
num_zero = 0.00001
grid[0] = num_zero / 1000000
grid[999] = 1- num_zero/1000000
x = [num... |
from lxml import etree
import soundfile as sf
import numpy as np
from scipy.signal import find_peaks
import matplotlib.pyplot as plt
RL = {
1: "Right Outer Main Beam",
2: 'Right Inner Main Beam',
3: 'Right Signature',
4: 'Right Channel 4',
5: 'Right Channel 5',
6: 'Right Channel 6',
7: '... |
'''
Function:
Implementation of HungarianMatcher
Author:
<NAME>
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
from scipy.optimize import linear_sum_assignment
'''HungarianMatcher'''
class HungarianMatcher(nn.Module):
def __init__(self, cost_class=1.0, cost_mask=1.0, cost_dice=1.0)... |
<reponame>Kazutaka333/behavioral_cloning<gh_stars>0
import csv
lines = []
folder_names = ['center2',
'center3',
'reverse',
'curve2',
'recovery',
'flipped_center2',
'flipped_center3',
'flipped_reverse',
... |
<reponame>bhi-kimlab/neticspy<filename>src/neticspy/util.py
import os
import numpy as np
from scipy.special import gammainc
def row_normalize(adj):
normalized_adj = adj / adj.sum(axis=1).reshape(-1, 1)
np.nan_to_num(normalized_adj, copy=False, nan=0)
return normalized_adj
def mkdir(output):
if '/' in output:
... |
from os import listdir
import numpy as np
import scipy.stats as st
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import rcParams
def identify(in_dir, out_dir):
outlier_threshold = st.norm.ppf(0.99) # threshold for events - 99% significance
fs = listdir(in_dir) # directory containing files... |
<gh_stars>1-10
from scipy.io.wavfile import read
import RPi.GPIO as GPIO
import random, os, fnmatch, pygame, sys, time
# Clears console
def clear():
os.system('clear')
def reset_lights():
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(18, GPIO.OUT)
GPIO.setup(15, GPIO.OUT)
... |
<reponame>elsuizo/abr_control
import numpy as np
import sympy as sp
from ..base_config import BaseConfig
class Config(BaseConfig):
""" Robot config file for the three joint MapleSim arm
Attributes
----------
REST_ANGLES : numpy.array
the joint angles the arm tries to push towards with the
... |
<reponame>LukasErlenbach/active_learning_bnn
"""
base_model.py
This module implements the BaseModel class from which the other network models
are derived. The class holds a tensorflow session and a net_config.
The class implements training, evaluation and prediction functions.
"""
from tensorflow_probability import... |
import copy
import os
from functools import partial
from pathlib import Path
from typing import List, Tuple
import hydra
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pytorch_lightning as pl
import scipy
import torch
from hydra.utils import get_original_cwd
from omegaconf import DictCon... |
<gh_stars>0
from skimage import io, filters
import numpy as np
from matplotlib import pyplot as plt
from scipy import ndimage
im = io.imread('me.jpeg')
im = im[:,:,0]
im = im.astype('float')
lin, col = im.shape
im2 = np.zeros((lin,col))
filtro = np.array([[1, 0, -1],
[1, 0, -1],
... |
#!/usr/bin/env python
from load import ROOT as R
from matplotlib import pyplot as P
import numpy as N
from gna.env import env
from gna.labelfmt import formatter as L
from mpl_tools.helpers import savefig, plot_hist, add_colorbar
from scipy.stats import norm
from gna.converters import convert
from argparse import Argum... |
"""
A demonstration intended to illustrate possible problems with the Gaussian
fitting approach to measuring the cross-correlation peak.
If the cross-correlation peak is well-represented by a single Gaussian
component, the errors acquired from the normal least-squares fit should be
representative of the true error in ... |
from typing import Tuple
import numpy as np
from skimage import filters, morphology, measure
import pandas as pd
from scipy import ndimage
from brainlit.utils.util import check_type, check_iterable_type
def find_somas(volume: np.ndarray, res: list) -> Tuple[int, np.ndarray, np.ndarray]:
r"""Find bright neuron s... |
import numpy as np
from sklearn.decomposition import PCA
import os
import time
import pickle as pickle
import pyhsmm
from pyhsmm.util.text import progprint_xrange
from pyhsmm.util.stats import whiten, cov
import autoregressive.models as ARmodel
import autoregressive.distributions as ARdist
import matplotlib.pyplot as p... |
import numpy as np
import scipy as sp
import kernels
import scipy.integrate as integrate
import scipy.interpolate as interpolate
import scipy.sparse.csgraph as csgraph
from numpy import matlib
def mean_error_2d_contour(gt,pred):
return np.mean(np.sqrt(np.square(gt[0::2,:]-pred[0::2,:])+np.square(gt[1::2,:]-pred[1:... |
<filename>Task_2/Dataset/gradient_descent.py
from sklearn.metrics import mean_squared_error as MSE
import numpy as np
import numpy as np
from scipy.sparse import diags
from sklearn.metrics import mean_squared_error as MSE
class GradientDescent:
def __init__(self,
learning_rate=1e-4, epochs=1e4,... |
<filename>main.py
#!/usr/bin/python2
#import numpy as np # don't need this with scipy
import scipy
import scipy.io
import mGLanim
#from sys import exit # pychecker: (exit) shadows builtin
# If you want to debug this, in a Python console, type:
# from load_from_matlab_scipy import *
# nordTank = matlabLoader() # load... |
<gh_stars>0
"""
StellarSource.py
Author: <NAME>
Affiliation: University of Colorado at Boulder
Created on: Mon Jul 8 09:56:35 MDT 2013
Description:
"""
import numpy as np
from scipy.integrate import quad
from ..physics.Constants import *
def _Planck(E, T):
""" Returns specific intensity of blackbody at T.""... |
<filename>evaluate_tradeoffs.py
#!/usr/bin/python3
import json
import seaborn as sns
from matplotlib import cm
from matplotlib.colors import ListedColormap, LinearSegmentedColormap
import matplotlib.colors as colors
from scipy.stats import spearmanr
import pylab
import scipy.cluster.hierarchy as sch
import cv2
from P... |
"""
Pipeline to reduce LRIS redside spectra.
Inputs:
prefix - Filename prefix, usually 'lred'
dir - Directory with input files, ie "raw/" (backslash is important!)
science - Numbers of the science files, ie "0023,0024,0029,0030"
arc - Number of arc file, ie "0025"
flats - ... |
# used by the PREPROCESS class and specified by the MISFIT parameter
import sys
import numpy as _np
import cmath
from scipy.signal import hilbert as _analytic
from scipy.fftpack import fft, ifft, fftfreq
from seisflows.tools.array import loadnpy
from seisflows.plugins import misfit
from seisflows.tools.math import... |
<gh_stars>0
import argparse
import numpy as np
from scipy import ndimage
import h5py
class Clefts:
def __init__(self, test, truth):
test_clefts = test
truth_clefts = truth
self.resolution=(40.0, 8.0, 8.0)
#self.truth_clefts_invalid = (truth_clefts == 0)
self.test_clefts_... |
<filename>source/hsicbt/utils/plot.py
import matplotlib
# matplotlib.rcParams['pdf.fonttype'] = 42
# matplotlib.rcParams['ps.fonttype'] = 42
matplotlib.rcParams['text.usetex'] = True
#matplotlib.rcParams['text.latex.unicode']=True
import matplotlib.pyplot as plt
import numpy as np
from .color import *
from .const imp... |
# --------------------------------------------------------
# Written by <NAME> and modified by <NAME> (https://github.com/JudyYe)
# Convert from MATLAB code https://inst.eecs.berkeley.edu/~cs194-26/fa18/hw/proj3/gradient_starter.zip
# --------------------------------------------------------
from __future__ import print... |
<gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from datetime import datetime
import numpy as np
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import ShuffleSplit
from sklearn... |
import numpy as np
import pandas as pd
from scipy import stats
import statsmodels.api as sms
import seaborn as sns
import matplotlib.pyplot as plt
def find_top_n_growth_zips(paramdict, n):
sorted_dict = dict(sorted(paramdict.items(), key=lambda price: price[1], reverse = True))
return list(sorted_dict.keys())[... |
import numpy as np
from velocity_transformations import compute_pmra, compute_pmdec, compute_distance_pmra, compute_distance_pmdec
from scipy.stats import norm
from multiprocessing import Pool
# from joblib import Parallel, delayed
# from functools import partial
def MC_values(parallax, parallax_error, n_MC):
m... |
# compute alpha using 'get_t' function,
# which ignores input vector x, and considers it to have consecutive numbers
import numpy as np
def get_t(t: float, x: np.ndarray, y: np.ndarray):
m1 = (len(x) * np.sum(y * t ** x) - np.sum(y) * np.sum(t ** x)) * np.sum(x * t ** (2*x))
m2 = (np.sum(y) * np.sum(t ** (2 ... |
"""Utilities for evaluating the fairness of die"""
from typing import List, Union, Tuple
from scipy.linalg import solve
from scipy.optimize import minimize
from pydantic import BaseModel, Field
import numpy as np
def _pretty_multiplier(x: float) -> str:
"""Make a prettier version of a multiplier value
Args:... |
"""
LICENSE TYPE: MIT
Received: from [192.168.2.2] (adsl-76-254-50-95.dsl.pltn13.sbcglobal.net [76.254.50.95])
(Authenticated sender: <EMAIL>)
by relay6-d.mail.gandi.net (Postfix) with ESMTPSA id D9F06FB883
for <<EMAIL>>; Sun, 2 Nov 2014 08:05:18 +0100 (CET)
From: <NAME> <<EMAIL>>
Content-Type: multipart/alternat... |
from __future__ import print_function, division
# ML utils
from sklearn.pipeline import make_pipeline
from sklearn import preprocessing
from sklearn.model_selection import KFold, cross_validate
from sklearn.metrics import confusion_matrix
# classifiers
from sklearn.discriminant_analysis import LinearDiscriminantAnalysi... |
<filename>code/morsecode.py
# -*-coding:utf-8-*-
from numpy import zeros, append, sin, pi, arange, hstack
from scipy.io.wavfile import write
from pynput.keyboard import Events, Key
from sounddevice import play
freq = 700 # 摩尔斯电码的音调频率
rate = 96000 # 生成、播放摩尔斯电码音频的采样率
duration = 0.06 # 摩尔斯电码中“点”的长度(秒),用来控制发报速度
o = ze... |
from django.shortcuts import render, redirect, reverse
from django.db.models import Avg
from django.contrib import messages
from django.contrib.auth import login, authenticate
from django.contrib.auth.decorators import login_required
from showcase.models import Player, Team, PlayerScorecard, Club, Coach
from .forms im... |
<filename>twodspec/thar.py<gh_stars>0
# -*- coding: utf-8 -*-
"""
Created on Tue May 30 13:27:58 2017
@author: cham
@SONG: RMS = 0.00270124312246
delta_rv = 299792458/5500*0.00270124312246 = 147.23860278870518 m/s
LAMOST: R~1800, 299792.458/6000*3A = 150km/s WCALIB: 10km/s delta_rv = 5km/s
MMT: R~2500, 299792.458... |
<gh_stars>1-10
# Copyright (c) Microsoft Corporation
# All rights reserved.
#
# MIT License
#
# 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... |
<gh_stars>1-10
from skdesign.power import (PowerBase,
is_in_0_1,
is_integer,
is_numeric,
is_positive)
import math
import scipy.stats as stats
class CarryOverEffect(PowerBase):
""" Test for presence of a... |
<filename>doc/.src/book/src/varform1D.py<gh_stars>10-100
"""
Solution of 1D differential equation by linear combination of
basis functions in function spaces and a variational formulation
of the differential equation problem.
"""
import sympy as sym
import numpy as np
import mpmath
import matplotlib.pyplot as plt
def... |
import numpy as np
import pint
import scipy as sp
import scipy.stats
from uncertainties import unumpy, ufloat, UFloat
def linregress(x, y):
r = sp.stats.linregress(x.m, y.m)
return (
ufloat(r.slope, r.stderr) * (y.units / x.units),
ufloat(r.intercept, r.intercept_stderr) * y.units
)
def c... |
<reponame>braycarlson/warbler.py
import librosa
import numpy as np
from scipy.signal import lfilter
class Spectrogram:
def __init__(self, signal, parameters):
self._signal = signal
self._parameters = parameters
@property
def data(self):
spectrogram = self.spectrogram_nn()
... |
from time import perf_counter
import numpy as np
from sklearn import clone
from sklearn.cluster import KMeans
from sklearn.model_selection import RepeatedStratifiedKFold, StratifiedKFold
from sklearn.metrics import *
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.ensemble i... |
from __future__ import annotations
from typing import Iterable, Optional
import collections
import contextlib
import copy
import functools
import itertools
import networkx as nx
import numpy as np
import os
import pathlib
import tempfile
import rdkit
import rdkit.Chem
import rdkit.Chem.AllChem
import scipy.interpolate... |
<reponame>Computational-Plant-Science/DIRT<gh_stars>10-100
#! /nv/hp10/adas30/bin/python
'''
----------------------------------------------------------------------------------------------------
DIRT 1.1 - An automatic high throughput root phenotyping platform
Web interface by <NAME> - <EMAIL>
http://dirt.iplantcollabo... |
<reponame>sysbio-curie/pyExaStoLog
# BSD 3-Clause License
# Copyright (c) 2020, <NAME>
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above co... |
<reponame>aydindemircioglu/radInt<filename>featureScoring.py
import numpy as np
import pandas as pd
from pymrmre import mrmr
import cv2
from sklearn.svm import SVC, LinearSVC
from sklearn.feature_selection import RFE, RFECV
from ITMO_FS.filters.multivariate.FCBF import FCBFDiscreteFilter
from ITMO_FS.filters.univariat... |
<filename>synthetic_sbm.py
#!/usr/bin/env python
import sys, os
import argparse
import numpy as np
from numpy.linalg import svd,eigh
import pandas as pd
import matplotlib.pyplot as plt
import mcmc_sampler_sbm
from estimate_cluster import estimate_clustering
from sklearn.cluster import KMeans
from scipy.stats import mod... |
from sys import *
from sympy import *
import numpy as np
#from sympy import Symbol, solve
from sympy import init_printing
from sympy.solvers.solveset import linsolve
from sympy.polys.polyfuncs import horner
def symbolCIP(nOrder):
# Simple check
if nOrder % 2 == 0:
sys.exit("Order might be od... |
from functools import lru_cache
import pandas as pd
from scipy import stats
import statsmodels.api as sm
from sklearn.preprocessing import scale
import conf
from entity import Gene
class GLSPhenoplier(object):
"""
Runs a generalized least squares (GLS) model with a latent variable (gene
module) weights ... |
<gh_stars>10-100
import os
import pickle
from nltk.classify import ClassifierI
from statistics import mode
from nltk.tokenize import word_tokenize
from log import log_config
logger = log_config.getLogger('analyze_mod.py')
#Service paths
current_path = os.path.dirname(os.path.realpath(__file__))
parent_path = os.path.... |
import numpy as np
from scipy.special import factorial2 as fc2
from scipy.special import factorial as fc
from scipy.special import erf
from fmm_source import q_particle, gs_q_dist
from contracted_basis import shell_pair
from basic_operations import Vlm, operation
def fmm(q_source, btm_level, p, scale_factor, WS_index... |
<gh_stars>0
import sys
sys.path.append('..')
import os
from copy import deepcopy
from braindecode.datasets.bbci import BBCIDataset
from braindecode.datasets.bcic_iv_2a import BCICompetition4Set2A
from braindecode.datautil.signal_target import SignalAndTarget
from sklearn.preprocessing import MinMaxScaler, LabelEncoder... |
<reponame>leouieda/inversion-again
from __future__ import division
from future.builtins import object, super, range
import warnings
import numpy as np
import scipy.sparse as sp
from fatiando.utils import safe_solve, safe_diagonal, safe_dot
class LinearOptimizer(object):
def __init__(self, precondition=True):
... |
# -*- coding: utf-8 -*-
"""Demo160_Distributions.ipynb
## Variable distributions and their effects on Models
Reference
[https://www.statisticssolutions.com/homoscedasticity/]
### Linear Regression Assumptions
- Linear relationship with the outcome Y
- Homoscedasticity
- Normality
- No Multicollinearity
## Linea... |
import collections
import itertools
import logging
from pathlib import Path
import cmws
import numpy as np
import pyro
import scipy
import torch
from cmws.examples.csg.models import (
heartangles,
hearts,
hearts_pyro,
ldif_representation,
ldif_representation_pyro,
neural_boundary,
neural_bo... |
import copy as cp
import numpy as np
from scipy.linalg import pinv, eigh
from sklearn.base import TransformerMixin
def shrink(cov, alpha):
n = len(cov)
shrink_cov = (1 - alpha) * cov + alpha * np.trace(cov) * np.eye(n) / n
return shrink_cov
def fstd(y):
y = y.astype(np.float32)
y -= y.mean(axis... |
<gh_stars>100-1000
'''
Functions for working with quaternions. Note that all the functions also
work on arrays, and can deal with full quaternions as well as with
quaternion vectors.
A "Quaternion" class is defined, with
- operator overloading for mult, div, and inv.
- indexing
'''
'''
author: <NAME>
date: Feb-20... |
<gh_stars>10-100
import warnings
import jax
import numpy as onp
import jax.numpy as np
from scipy.sparse.linalg import LinearOperator, eigs
from utils import flat_t_op_fun, hs_dot
def build_t_op(core_tensor, direction, jitted=True):
"""
Get the transfer operator for a TI-MPS, which acts on an input matrix
... |
<reponame>qiaozhijian/vLPD-Net
# Author: <NAME>
# Shanghai Jiao Tong University
# Code adapted from PointNetVlad code: https://github.com/jac99/MinkLoc3D.git
import numpy as np
import torch
from pytorch_metric_learning import losses
from pytorch_metric_learning.distances import LpDistance
from scipy.spatial.transform... |
<filename>process/honda-label/preprocess.py<gh_stars>1-10
import numpy as np
import os
import glob
import struct
import sys
from scipy.ndimage.filters import gaussian_filter, convolve
from scipy.misc import toimage, imresize
def load_images(img_files):
"""
Given a list of image file names, this loads and retur... |
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 27 23:12:56 2019
@author: david
"""
"""
USE HESTON
"""
import numpy as np
import tensorflow as tf
from scipy.stats import multivariate_normal as normal
import math
"""
z_vals = [[[1, 2], [3, 4], [9, 10]], [[3, 4], [5, 6], [0, 0]], [[7, 8], [9, 10], [0, 0]]]
z_vals_tf = ... |
import numpy as np
from scipy.constants import mu_0
# TODO: make this to take a vector rather than a single frequency
def rTEfunfwd(n_layer, f, lamda, sig, chi, depth, HalfSwitch):
"""
Compute reflection coefficients for Transverse Electric (TE) mode.
Only one for loop for multiple layers.
... |
<reponame>Nadogan/Instagram_Poetry_Processing
#this script generates 20 instapoems based on a sample
#run from command line, and specify the path of the sample in the command
#the sample has to be a csv file
import numpy as np
import random
import statistics
#gets averages from the sample poems so that our poems are ... |
import numpy as np
import tensorflow as tf
from tensorflow import keras
import scipy.stats as ss
from tensorflow.keras.utils import to_categorical
#import keras
#from keras.utils import to_categorical
class DataLoader(keras.utils.Sequence):
'Loads data for Keras'
def __init__(self, S, path, train_ix, batch_size, n_a... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import sys
import warnings
from math import sqrt, pi, exp, log, floor
from abc import ABCMeta, abstractmethod
import numpy as np
from .. import constants as const
from ..config import ConfigurationItem
from ..utils.misc import isiterable
from ..utils.exc... |
<filename>src/algo/math/solve.py<gh_stars>0
"""
Numerical methods for solving equations f(x) = 0.
"""
def newton1D(f, x_0, df=None, delta=0.00001):
"""
Find solution to f(x) = 0 with newton's method
:param f: function f
:param x_0: starting point for x
:param df: first order derivative of f
:p... |
import numpy as N
from os.path import dirname
from supreme.lib import klt
import scipy as S
imread = S.misc.pilutil.imread
imsave = S.misc.pilutil.imsave
img1 = imread(dirname(__file__) + '/img0.pgm')
img2 = imread(dirname(__file__) + '/img1.pgm')
tc = klt.TrackingContext()
print tc
fl = klt.FeatureList(100)
klt.s... |
""" 6 DOF equation of motion"""
import numpy as np
from . import math_function as mf
from scipy.integrate import ode
class SixDOF(object):
"""# 6 dimensional equation of motion of the rigid body.
## Instances
### x: state variables
x[0:3]: position, inertial coordinate [m]
x[3:6]: velocity, i... |
# -*- coding: utf-8 -*-
"""
-----------------------------------------------------------------------------
Ejercicio 1: Integración - Fórmulas de cuadratura simples.
-----------------------------------------------------------------------------
"""
import numpy as np
import sympy as sym
# Cálculo de la integr... |
<reponame>wagnew3/Amodal-3D-Reconstruction-for-Robotic-Manipulationvia-Stability-and-Connectivity--Release<filename>trajopt/sandbox/examples/reconstruct_scene.py
import os
from optparse import OptionParser
import scipy
import time
import glob
dir_name=os.path.dirname(__file__)
parser = OptionParser()
parser.add_option... |
from statistics import mean
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
xs = np.array([1, 2, 3, 4, 5, 6], dtype = np.float64)
ys = np.array([5, 4, 6, 5, 6, 7], dtype = np.float64)
'''
Formula for Linear regression's slope is
Y = Mx + B
Where M is the slope and B is the y-intercept
... |
import fire
import ray
import os
import csv
from copy import deepcopy
import numpy as np
from functools import partial
from multiprocessing import Pool
from tqdm import tqdm
from scipy.stats import loguniform
from infomercial import exp
from infomercial.utils import save_checkpoint
from infomercial.utils import load_... |
<filename>visnav/calibration/calibrate.py
import configparser
import pickle
import os
import glob
import sys
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import leastsq, fmin_bfgs, minimize
import cv2
from visnav.algo import tools
from visnav.algo.image import ImageProc
from vis... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pandas as pd
from datetime import datetime, timedelta
import numpy as np
from scipy.stats import pearsonr
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.ticker as tck
import matplotlib.cm as cm
import matplotlib.font_manager... |
<reponame>lgbouma/rudolf
import os
import numpy as np, pandas as pd
from astropy.timeseries import BoxLeastSquares
from scipy.signal import savgol_filter
import matplotlib as mpl
import matplotlib.pyplot as plt
from aesthetic.plot import savefig
from copy import deepcopy
from astrobase.lcmath import sigclip_magseries
... |
<filename>code/figures/si/figS0X_ppc.py<gh_stars>0
#%%
import pickle
from git import Repo #for directory convenience
import numpy as np
import scipy.stats as st
import pandas as pd
import arviz as az
import matplotlib.pyplot as plt
import matplotlib
import matplotlib.patheffects as path_effects
import seaborn as sns
... |
import sys
import logging
import string
import sympy as sp
from sympy.codegen.rewriting import optims_c99, optimize, ReplaceOptim
from sympy.core.mul import Mul
from sympy.core.expr import UnevaluatedExpr
def ccode(eq) -> str:
"""Transforms a sympy expression into C99 code.
Applies C99 optimizations (`sympy... |
<reponame>ZilongJi/HippocampalSWRDynamics
"""
This module contains helper functions used in multiple files throughout the codebase.
"""
import numpy as np
import scipy.stats as sp
from scipy.special import factorial
from scipy.special import gamma
from typing import Optional, Tuple
def calc_poisson_emission_probabil... |
<gh_stars>0
#NUM = 0; nums = [0,5,10,15,20] ; bins = 150 ; minv = 140 ; maxv =170
NUM = 6; nums = [1,6,11,16,21] ; bins = 150 ; minv = 300 ; maxv = 330
#nums = [2,7,12,17,22] ; bins = 200 ; minv = 445 ; maxv = 485
#nums = [3,8,13,18,23] ; bins = 200 ; minv = 600 ; maxv = 650
#nums = [4,9,14,19,24] ; bins = 200 ; minv =... |
<gh_stars>0
import sklearn.model_selection as ms
from sklearn.model_selection import RandomizedSearchCV, GridSearchCV
from skopt import BayesSearchCV
from skopt.space import Real, Categorical, Integer
import scipy.stats
import pandas as pd
import numpy as np
import os
from mastml import utils
import logging
log = logg... |
<filename>examples/plot_sax.py
"""
================================
Symbolic Aggregate approXimation
================================
This example shows how you can quantize a time series (i.e. transform a
sequence of real numbers into a sequence of letters) using
:class:`pyts.quantization.SAX`.
"""
import numpy as n... |
#! /usr/bin/python
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import matplotlib
import argparse
from scipy.interpolate import griddata
from vapory import *
import mcubes
def spin(center, vec):
top = center + 0.5*vec
bottom = center - 0.5*vec
r = 255.0
g = 0... |
""" Fitting a moving Gaussian to fireball data. """
from __future__ import print_function, division, absolute_import
import numpy as np
import matplotlib.pyplot as plt
import scipy.optimize
from FRbin import read as readFR
from MovingGaussian import movingGaussian2D
def centroidImage(img):
""" Find the centro... |
<filename>MultiQubit_PulseGenerator/NQB/nqb_tomo_functions.py
'''
-------------------------------------------------
- Suite of functions for tomography -
-------------------------------------------------
Generalized MLE code written by <NAME> (<EMAIL>),
based on 1-2QB code written by <NAME> (<EMAIL>)
wi... |
#!/usr/bin/env python
#=======================================================
#File: d1_TopicModeling
#Cleaning Data and generating topics using NMF
#using Dr Gene's Code (as given in dropbox), modified by <NAME>
#=======================================================
import numpy as np
import glob
import os
im... |
import numpy as np
from scipy.misc import imsave
from math import sqrt, floor, ceil
def displayNetwork(A, cols = None, file_name = 'network.jpg', opt_normalize = True):
"""This function visualizes filters in matrix A. Each column of A is a
filter. We will reshape each column into a square image and visualizes
o... |
"""
Analyzes filaments to membrane distances on list of tomograms
Input: - A STAR file with a set of ListTomoFilaments pickles (SetListFilaments object input)
- Settings for the measurements
Output: - Plots by tomograms
- Global plots
"""
################# Package import
impor... |
<reponame>kekraft/contamination_stack<filename>people_tracking/scripts/people_tracker.py
#!/usr/bin/env python
import rospy
import numpy as np
from std_msgs.msg import *
from geometry_msgs.msg import Point, Quaternion, Pose, Vector3
from visualization_msgs.msg import Marker, MarkerArray
from sensor_msgs.msg import Las... |
<reponame>jamesharrison0799/QDot-Constant-Interaction-Model<filename>ConstantInteractionSimulation.py
import numpy as np
import matplotlib.pyplot as plt
from scipy.ndimage import gaussian_filter
from random import seed # generates seed for random number generator
from random import random # random generates a random n... |
<reponame>LarsChrWiik/CE903-group6<filename>GUI/API/Preprocessing/Phase.py
import numpy as np
from scipy.signal import hilbert as hilbert_analytic
from scipy.fftpack import hilbert as hilbert
"""
Phase difference between channels.
"""
class Phase:
"""
***** INPUT 1 *****
2-dm = chunks.
3-dm = sensors... |
"""Lens classes."""
# stdlib
import logging
import math
# external
import numpy as np
import scipy.constants as sc
# project
from payload_designer.libs import physlib, utillib
LOG = logging.getLogger(__name__)
class ThinLens:
"""Thin singlet lens component.
Args:
D (float, optional): diameter of ... |
<reponame>ElsevierSoftwareX/SOFTX-D-20-00016
from scipy.spatial import distance
import pandas
import time
import numpy
import math
def load_from(filename):
"""Load the data from the specified filename."""
# Set the columns
columns = [
'timestamp',
'playerID',
'xPosition',
... |
import heisenberg.self_similar.kh
import itertools
import matplotlib.pyplot as plt
import numpy as np
import pathlib
import scipy.interpolate
import typing
import vorpy
import vorpy.realfunction.bezier
import vorpy.realfunction.piecewiselinear
def plot_J_equal_zero_extrapolated_trajectory (p_y_initial:float) -> None:
... |
from collections import OrderedDict
import numpy as np
from sklearn.metrics.cluster import normalized_mutual_info_score as nmi_score
from scipy.optimize import linear_sum_assignment
import torch
from ..viz import plot_matrix
from .basemetric import DiscreetMetric
class Clustering(DiscreetMetric):
"""
Compute... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 1 21:55:19 2018
@author: jiahan
"""
import numpy as np
import numpy.linalg as npla
import scipy as sc
import scipy.sparse.linalg as la
import scipy.sparse as sp
import matplotlib.pyplot as plt
def Grad_x(dx, nx, ny):
Gx = sc.zeros([nx, nx])
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.