text string |
|---|
<filename>variable_selection_management.py<gh_stars>0
# -*- coding: utf-8 -*-
# %reset -f
"""
@author: <NAME>
"""
similarity_index = 'corr'
# 'corr': correlation coefficient
# 'mic': Maximal Information Coefficient (MIC) [please install minepy https://minepy.readthedocs.io/en/latest/]
# 'rbf': Gaussian kernel... |
import xarray as xr
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
from os.path import join
from scipy.stats import norm, pearsonr
from ninolearn.learn.models.dem import DEM
from ninolearn.learn.fit import cross_hindcast, n_decades, decades, lead_times,... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
:mod:`processing`
==================
.. module:: processing
:platform: Unix, Windows
:synopsis:
.. moduleauthor:: hbldh <<EMAIL>>
Created on 2015-08-26, 14:48
"""
from __future__ import division
from __future__ import print_function
from __future__ import un... |
<gh_stars>0
import sounddevice
from scipy.io.wavfile import write
# Sample rate
cps = 22050
# Clip duration
length = 10
# Function for recording a sound clip
def record_sound():
print("Recording started!")
# Record audio data from your sound device into a NumPy array
recording = sounddevice.rec(int(lengt... |
from collections import defaultdict
from numpy import bincount, empty, log, log2, unique, zeros
from numpy.random import choice, uniform
from numpy.random.mtrand import dirichlet
from scipy.special import gammaln
from algorithm_8 import iteration as algorithm_8_iteration
from kale.math_utils import log_sample, log_sum... |
<gh_stars>1000+
import matplotlib.pyplot as plt
import numpy as np
import scipy.io as scio
from mpl_toolkits.mplot3d import Axes3D
from skimage import io
from skimage import img_as_float
import featureNormalize as fn
import pca as pca
import runkMeans as rk
import projectData as pd
import recoverData as rd
import displ... |
import sympy as sp
import numpy as np
#class map_prototype:
#
# def __init__(self,params):
# pass
#
# def step(self,x=None,n=1):
# pass
#
# def steps(self,x=None,n=1):
# pass
class logistic:
def __init__(self,a):
self.a = a
self.next = 0
def step(self,x=None,n=1):
if x is None: x = self.next
assert 0... |
<reponame>Banus/crism_ml<filename>crism_ml/io.py
"""Utilities for input/output operations."""
import logging
import os
from pathlib import Path
import pickle # nosec
from functools import wraps
import numpy as np
from crism_ml import CONF, USE_CACHE
ROOT_DIR = Path(os.path.abspath(__file__)).parent.parent
CACHE_DIR... |
import abc
import numpy as np
from ..interpolator.gspline import cSplineCalc
from scipy.sparse.linalg import spsolve
import copy
class cFunctional(metaclass=abc.ABCMeta):
''' This is a class which represents a non linear function
of a spline. In other words this represents a map
F : gpline --> R
... |
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 2 20:13:22 2018
from https://github.com/XiaoTaoWang/HiCPeaks as a reference
"""
import logging
import numpy as np
from scipy import sparse
from scipy.stats import poisson
from statsmodels.sandbox.stats.multicomp import multipletests
logger = logging.getLogger(__name__)
... |
<gh_stars>0
#!/usr/bin/python3
from pprint import pprint
# https://docs.python.org/3/library/index.html
# some Python3 built-in's
# https://docs.python.org/3/library/functions.html
# https://docs.python.org/3/library/constants.html
# https://docs.python.org/3/library/stdtypes.html
# https://docs.python.org/3/library... |
<reponame>lucapele/pele-c<gh_stars>100-1000
from __future__ import print_function, division
from collections import defaultdict
from sympy import SYMPY_DEBUG
from sympy.core import (Basic, S, C, Add, Mul, Pow, Rational, Integer,
Derivative, Wild, Symbol, sympify, expand, expand_mul, expand_func,
Function, Eq... |
<gh_stars>1-10
__author__ = 'thk22'
from scipy import sparse
from scipy.stats import rv_discrete
from sklearn.cluster import KMeans
from sklearn.metrics import pairwise_distances_argmin_min
from sklearn.utils import check_random_state
import numpy as np
class CosineMeans(KMeans):
def __init__(self, n_clusters=8, i... |
<filename>ideal_gas_flow/rayleigh.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Rayleigh Flow (1-D flow w/ heat addition)
Note:
- Star denotes conditions achieved if sufficient heat was added to achieve
sonic conditions.
"""
import math
from scipy import optimize
def mach(T0T0star, gamma):
"""Sta... |
"""
Tabular reinforcement learning algorithms -- :mod:`sc2qsr.rl.tabular`
======================================================================
https://github.com/MorvanZhou/Reinforcement-learning-with-tensorflow/
"""
# MIT License
# Copyright (c) 2017
# Permission is hereby granted, free of charge, to any person ... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import os
import ntpath
import time
from . import util
import scipy.misc
try:
from StringIO import StringIO # Python 2.7
except ImportError:
from io import BytesIO # Python 3.x
# import torchvision.utils as vutils
from tensorboardX imp... |
<reponame>TEichinger/cornac<filename>cornac/models/causalrec/recom_causalrec.py
# Copyright 2018 The Cornac Authors. All Rights Reserved.
#
# 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
#
# ... |
<reponame>tokuhirom/jawiki-kana-kanji-dict<filename>jawiki/converter.py
import logging
import re
import jaconv
from jawiki.hojin import hojin_filter
from statistics import mean
import Levenshtein
import html
from jawiki.jachars import HIRAGANA_BLOCK, KANJI_BLOCK, KATAKANA_BLOCK, kanji_normalize
NAMEISH_PATTERN = r... |
<gh_stars>1-10
"""=============
Example : face_box.py
Author : <NAME>
Description :
A code to test FaceAnalyzer by visualizing the evolution of multiple face parameters inside a pyqt5 or pyside2 interface
(Requires installing sqtui with either pyqt5 or pyside2 and pyqtgraph)
<==============... |
<gh_stars>0
# -*- coding: utf-8 -*-
"""
Tests for Spiesberger & Wahlberg 2002
"""
import unittest
import numpy as np
np.random.seed(82319)
import scipy.spatial as spatial
from batracker.localisation import spiesberger_wahlberg_2002 as sw02
class SimpleTest(unittest.TestCase):
'''With tristar and one position
... |
#!/usr/bin/env python
"""Tests for `scipr.matching` module."""
import unittest
import numpy as np
from scipy import spatial
from scipr.matching import Closest, MNN, Greedy
class TestMatching(unittest.TestCase):
"""Tests for Match algorithms."""
def setUp(self):
"""Set up test fixtures, if any.""... |
from __future__ import absolute_import
import numpy as np
import scipy as sp
import logging
from scipy import stats
from fastlmm.pyplink.snpreader.Bed import Bed
#from fastlmm.association.gwas import LeaveOneChromosomeOut, LocoGwas, FastGwas, load_intersect
from fastlmm.association.LeaveOneChromosomeOut import LeaveOne... |
<filename>Gibbs_Informative.py
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 30 15:27:01 2020
@author: rebec
"""
import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt
from datetime import datetime
startTime = datetime.now()
np.random.seed(250)
### ### ### ### ### ... |
<filename>ai4water/postprocessing/SeqMetrics/_regression.py<gh_stars>10-100
import warnings
from math import sqrt
from typing import Union
from scipy.stats import gmean, kendalltau
import numpy as np
from .utils import _geometric_mean, _mean_tweedie_deviance, _foo, list_subclass_methods
from ._SeqMetrics import Metr... |
<filename>feature.py<gh_stars>1-10
import numpy as np
from scipy.fftpack import dct
# ---------- feature-window ----------
def sliding_window(x, window_size, window_shift):
shape = x.shape[:-1] + (x.shape[-1] - window_size + 1, window_size)
strides = x.strides + (x.strides[-1],)
return np.lib.stride_tric... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
from abel.tools.polar import reproject_image_into_polar
from scipy.ndimage import map_coordinates
from scipy.ndimage.interpola... |
#Misc
import time, os, sys, pdb
from glob import glob
from fnmatch import fnmatch
#Base
import numpy as np
import pandas as pd
#Save
import json
import scipy.io as sio
import h5py
#User
from utilities import *
#Plot
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib.gridspec as gridspec
from ma... |
<reponame>SquarerFive/bf3-bots
import numpy
from PIL import Image
import networkx as nx
from pathfinding.core.diagonal_movement import DiagonalMovement
from pathfinding.core.grid import Grid
from pathfinding.finder.a_star import AStarFinder
from pathfinding.finder.dijkstra import DijkstraFinder
from pathfinding.finder... |
<gh_stars>1-10
import time
import queue
import PySpin
import numpy as np
import multiprocessing as mp
from scipy.ndimage import gaussian_filter as gaussian
_PROPERTIES = {
'FRAMERATE': {
'minimum': 1,
'maximum': 200,
'initial': 30
},
'BINSIZE': {
'initial': (2, 2)
},
... |
<reponame>marco-mariotti/pyaln
import os, io
from functools import lru_cache
from typing import Union, TextIO
import pandas as pd
import numpy as np
import statistics
from Bio import SeqIO, AlignIO, Seq, SeqRecord, Align
#from pyaln.sequtils import *
from pyaln import sequtils
#from . import sequtils
MultipleSeqAlignm... |
<filename>chapter7_语音合成/C7_2_y.py
from chapter2_基础.soundBase import *
from chapter7_语音合成.flipframe import *
from chapter3_分析实验.C3_1_y_1 import enframe
from chapter3_分析实验.lpc import lpc_coeff
from scipy.signal import lfilter
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
data,... |
import math
from dataclasses import dataclass
from scipy.interpolate import interp1d
from scipy.special import hyp1f1
from cached_property import cached_property
import numpy as np
from pb_bss.distribution.utils import _ProbabilisticModel
from pb_bss.utils import is_broadcast_compatible
from pb_bss.utils import get... |
<filename>pycqed/simulations/cz_superoperator_simulation_FAQUAD.py
"""
April 2018
Simulates the trajectory implementing a CZ gate.
June 2018
Included noise in the simulation.
"""
import time
import numpy as np
import qutip as qtp
from pycqed.measurement import detector_functions as det
from scipy.interpolate import in... |
<gh_stars>0
# -*- coding: utf-8 -*-
u"""さまざまな2D移動ロボットを表現するクラス
ノイズ無し・ありなど
"""
from abc import abstractmethod
from math import sin, cos, fabs, pi
import numpy as np
from scipy.stats import expon, norm, uniform
class Robot():
@abstractmethod
def one_step(self, time_interval):
u"""1コマすすめる
Agentが... |
<gh_stars>1-10
"""
https://github.com/bunnech/holoprot/blob/main/holoprot/utils/surface.py is the base for this file. Modifications were made.
Utilities for preparing and computing features on molecular surfaces.
"""
import os
import numpy as np
from numpy.core.numeric import full
from numpy.matlib import repmat
from ... |
<gh_stars>0
import numpy as np
from typing import Callable
def makeETCIndex(A: int = 2, m: int = 1):
"""
Explore-Then-Commit index, see Chapter 6 in [1].
Parameters
----------
A: int
Number of arms.
m : int, default: 1
Number of exploration pulls per arm.
Return
----... |
# coding: utf-8
from mpi4py import MPI
from scipy.sparse import eye as sparse_id
from psydac.linalg.basic import LinearOperator
from psydac.fem.basic import FemField
#===============================================================================
class FemLinearOperator( LinearOperator ):
"""
Linear opera... |
<gh_stars>1-10
import tensorflow as tf
tf.reset_default_graph()
from keras.applications.vgg19 import VGG19
import os
from tensorflow.python.keras.preprocessing import image as kp_image
from keras.models import Model
from keras.layers import Dense, BatchNormalization,Dropout,concatenate
from keras import backend ... |
<reponame>bopardikarsoham/qiskit-ibm-runtime<gh_stars>0
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/lice... |
<filename>metrics.py
"""
The scipt that contains all the statistical metrics for measuring the result of the fit
Each metric takes at least a pred and truth list with (n_sample, n_dimension) of y pair
"""
import numpy as np
import os
from scipy.stats import spearmanr # Spearman's Rho
from scipy.stats import kend... |
# -*- coding: utf-8 -*-
import os
import re
import copy
import time
import numpy
import pandas
import shutil
import subprocess
import multiprocessing
from scipy import stats
from ruamel import yaml
# from safirpy.safir_problem_definition import file_0 as spd_version_0
def preprocess_structured_directories(path_work... |
from __future__ import print_function
import sklearn
import mpl_toolkits
import os # for os.path.basename
from sklearn.metrics.pairwise import euclidean_distances
from sklearn.metrics.pairwise import cosine_similarity
import matplotlib.pyplot as plt
from sklearn.manifold import MDS
from sklearn.feature_extract... |
<gh_stars>1-10
import numpy as np
from scipy.special import binom
class PiecewiseFunction:
"""
Implements a one-dimensional piecewise function consisting of arbitrarily many intervals.
When called with an array of function arguments, each array element will be assigned to its appropriate interval
usi... |
# Atom Tracing Code for International Workshop and Short Course on the FRONTIERS OF ELECTRON TOMOGRAPHY
# https://www.electron-tomo.com/
import numpy as np
import scipy as sp
import scipy.io as sio
import os
import warnings
def tripleRoll(vol, vec):
return np.roll(np.roll(np.roll(vol, vec[0], axis=0), vec[1], ax... |
import os
import re
import csv
import copy
import json
import math
import importlib
import itertools
import collections
import string
import random
import warnings
import traceback
from typing import Any, Dict, List, Set, Tuple, Union, Optional
import tqdm
import pandas as pd
import click
import numpy as np
from scipy... |
import numpy as np
import networkx as nx
import argparse as ap
import math
from scipy.spatial.distance import euclidean
from sklearn.metrics.pairwise import euclidean_distances
from time import time
k = 1000
# Use Dijkstra's algorithm to compute distance from all nodes to all landmark nodes
def find_distances(node, G... |
<filename>sample.py<gh_stars>0
import numpy as np
from math import *
from sympy import *
from scipy import interpolate
from scipy.misc import comb
from matplotlib import pyplot as plt
def bernstein_poly(i, n, t):
"""
The Bernstein polynomial of n, i as a function of t
"""
return comb(n, i) * ( t**(n... |
<gh_stars>1-10
from abc import ABC, abstractmethod, abstractproperty
import numpy as np
import pandas as pd
import scipy
import collections
import math
from tqdm import tqdm
from copy import deepcopy, copy
from scipy.stats import logistic
from itertools import combinations
from copy import deepcopy, copy
from sklearn.m... |
<reponame>VoxelPi/compm<filename>ue/ue_07/problem_4.py
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import cumulative_trapezoid
x = np.linspace(0, 2*np.pi)
plt.figure()
plt.plot(x, -np.cos(x) + 1, label="$\int{sin(x)}$", linestyle="--", linewidth=2)
plt.plot(x, cumulative_trapezoid(np.sin(x... |
<filename>lossatdefault.py<gh_stars>1-10
import pandas as pd
import os
import numpy as np
import datetime
from datetime import timedelta
from pandas.tseries.offsets import DateOffset
from dateutil.relativedelta import relativedelta
import math
from collections import defaultdict
import sklearn as sk
from sklearn.prepro... |
<reponame>adambrzosko/BA-Price-Model
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 23 23:54:34 2021
@author: adam
"""
#import networkx as nx
import numpy as np
import numpy.random as random
import matplotlib.pyplot as plt
import pickle
from scipy import stats
from scipy.optimize import curve_fi... |
import inspect, time, math, random, multiprocessing, os, sys, copy
import numpy, scipy, scipy.stats
import settings
from django.template.loader import render_to_string
from . import FittingBaseClass
from . import ReportsAndGraphs
import zunzun.forms
import pyeq3
class FitUserDefinedFunction(FittingBaseClass.Fitt... |
"""
Lean rigid transformation class
Author: Jeff
"""
import logging
import os
import numpy as np
import scipy.linalg
from . import utils
from . import transformations
from .points import BagOfPoints, BagOfVectors, Point, PointCloud, Direction, NormalCloud
from .dual_quaternion import DualQuaternion
try:
from geo... |
import nltk
import random
from nltk.classify.scikitlearn import SklearnClassifier
import pickle
from sklearn.naive_bayes import MultinomialNB, BernoulliNB
from sklearn.linear_model import LogisticRegression, SGDClassifier
from sklearn.svm import SVC
from nltk.classify import ClassifierI
from statistics import mode
from... |
import numpy as np
from scipy.integrate import quad
from scipy.interpolate import interp1d
from ttim import *
ml = ModelMaq(kaq=[1, 5], z=[3, 2, 1, 0], c=[10], Saq=[0.3, 0.01], Sll=[0.001], tmin=1e-4, tmax=1e5, M=20)
w1 = HeadWell(ml, xw=0, yw=0, rw=0.3, tsandh=[(0, 1)], layers=0)
ml.solve()
def func1(tau, p0, p1, f)... |
import networkx as nx
import statistics
import matplotlib.pyplot as plt
from queue import PriorityQueue
import math
class Grafo(object):
def __init__(self, grafo_dict={}):
self.grafo_dict = grafo_dict
def vertices(self):
return list(self.grafo_dict.keys())
def arestas(self):
ret... |
<filename>src/neighborhoods.py
import pandas as pd
import numpy as np
from scipy import interpolate
import os
import os.path
from subprocess import check_call, check_output, PIPE, Popen, getoutput, CalledProcessError
from tools import *
import linecache
import traceback
import time
import pyranges as pr
pd.options.dis... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Module that containg function for features engineering
from raw time series data
"""
import numpy as np
from scipy.stats import trim_mean
from scipy.stats.mstats import trimmed_std
from scipy.stats import kurtosis, skew
from statsmodels.tsa.stattools import pacf
p_c... |
import numpy as np
from skimage import color
from scipy.spatial import KDTree
from random import random, uniform
def lincolor(n, random_sat=False, random_val=False):
""" returns linearly sampled colors from HSV space
with randomised Saturation and Value
"""
HSV = []
for h in np.linspace(0, 1, ... |
<gh_stars>0
import ctypes
from scipy.integrate import solve_ivp
import numpy as np
import mpmath
import os
class geotrace:
"""
__init__(bhspin=0.)
init_model(bhspin)
init_XK(i,j,Xcam,fovx,fovy,X,Kcon,nx,ny)
"""
# constants
G = 6.6742e-8
Msun = 1.989e33
CL = 2.99792458e10
# scaling
Lun... |
<filename>Exercise/Python/AprioriBySpark.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
import csv
import random
import operator
import sys
from scipy.linalg._interpolative import id_srand
from scipy.spatial import distance
from pyspark.sql import SparkSession
from pyspark.sql import Row
def splitstr(... |
<filename>Data-CSV/Histograms and QQ plots.py<gh_stars>0
#!/usr/bin/env python
# coding: utf-8
# In[47]:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import math
from scipy import stats
get_ipython().run_line_magic('matplotlib', 'inline')
import statsmodels.api as sm
... |
import numpy as np
from scipy.interpolate import interp1d
from scipy.io import loadmat
def err_fd_burgers_sin2():
d = np.load('../../outputs/burgers_fd/sin2_gaussian_n40/results_0100.npz')
e = np.load('../data/pyclaw_burgers1d_sine2.npz')
# Shifting is needed since this is from -0.5, 0.5 and ours from 0, ... |
import pytest
import dask.array as da
import numpy as np
from scipy import signal
import xarray as xr
import filtering
def test_frequency_filter(leewave_data):
"""Test creation and application of frequency-space step filter."""
f = filtering.LagrangeFilter(
"frequency_filter",
leewave_data,... |
import numpy as np
import matplotlib.pyplot as plt
import argparse
from scipy.signal import convolve2d
from simulation import Simulation
DIRECTIONS = [(0, 1), (0, -1), (1, 0), (-1, 0)]
MASK = np.array([[0, 1, 0], [1, 0, 1], [0, 1, 0]])
class Ising(Simulation):
def __init__(self, size, beta, initialisation_mode="... |
import warnings
import sys
from matplotlib import pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
import matplotlib as mpl
import matplotlib.colors as mplcolors
import numpy as np
import matplotlib.ticker as mtik
import types
try:
import scipy.ndimage
from scipy.stats import norm
haveSci... |
# This files contains your custom actions which can be used to run
# custom Python code.
#
# See this guide on how to implement these action:
# https://rasa.com/docs/rasa/core/actions/#custom-actions/
# This is a simple example for a custom action which utters "Hello World!"
import re
import io
import ast
import req... |
<filename>examples/substitution.py
import sys
sys.path.append("..")
import sympy
x=sympy.Symbol('x')
y=sympy.Symbol('y')
e=1/sympy.cos(x)
print e
print e.subs(sympy.cos(x),y)
print e.subs(sympy.cos(x),y).subs(y,x**2)
e=1/sympy.log(x)
e=e.subs(x,sympy.Real("2.71828"))
print e
print e.evalf()
|
from spectral_cube import SpectralCube
from astropy.io import fits
import matplotlib.pyplot as plt
import astropy.units as u
import numpy as np
from scipy.optimize import curve_fit
from scipy import *
import time
import pprocess
from astropy.convolution import convolve
import radio_beam
import sys
def run_gauss_fits_... |
<filename>statistical_parts/error_spending.py
import dash_table
import dash_html_components as html
import dash_bootstrap_components as dbc
import numpy as np
import pandas as pd
from scipy.stats import norm
from layout_instructions import spacing_variables as spacing
from layout_instructions import label, my_jumbo_b... |
#ebtel_plot.py
#<NAME>
#7 May 2015
#Import necessary modules
try:
import __builtin__
except ImportError:
import builtins as __builtin__
import logging
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import seaborn.apionly as sns
from matplotlib.ticker import Max... |
<gh_stars>0
"""
analysis/morlet.py
Time-frequency representation using Morlet wavelets
Original version written by <NAME> (Brown University)
Modified by <NAME> (NKI; added phase calculations, saving/passing in Morlet, specifying different
frequency steps and frequencies used for calculations (e.g. logarithmic fre... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
The :mod:`~araucaria.xas.xasft` module offers the following functions to perform
discrete fast Fourier transforms (FFT) on a XAFS scan:
.. list-table::
:widths: auto
:header-rows: 1
* - Function
- Description
* - :func:`ftwindow`
- Returns a FT wind... |
"""
Module to perform analysis on MRI models.
Note: fMRI support to be added in the future.
"""
import argparse
import logging
import matplotlib
matplotlib.use("Agg")
import nipy
import numpy as np
import os
from os import path
from matplotlib import pyplot as plt
from math import log
from math import sqrt
from pylea... |
<filename>python/dgl/data/flickr.py
"""Flickr Dataset"""
import os
import json
import numpy as np
import scipy.sparse as sp
from .. import backend as F
from ..convert import from_scipy
from ..transforms import reorder_graph
from .dgl_dataset import DGLBuiltinDataset
from .utils import generate_mask_tensor, load_graphs,... |
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 28 19:18:41 2018
@author: User
"""
import numpy as np
from scipy import fft, arange
def One_sided_spectra(y,Fs):
n = len(y)
Fs =float(Fs) # 轉換成浮點數才可以進行浮點運算
k = arange(n) # if n = 5 -> k = [0,1,2,3,4]
Time = n/Fs #Time
... |
# --------------------------------------------------------------------------------
# Copyright (c) 2017-2020, <NAME>, All rights reserved.
#
# Defines the basis structure of the change-detection tests and the
# change-point methods
# --------------------------------------------------------------------------------
impo... |
# How to integrate equations of motion, quick and dirty way
# Note: this template will not run as is
# get EoM into form <qdots, udots = expressions> first though
# Also, make sure there are no qdots in rhs of udots
# (meaning udot = f(q, u, t), not f(q, qdot, u, t)
# use Kane.kindiffdict to get dictionary, and use sub... |
<filename>vge_gradcam.py
import utils.arg_parser
import torch
import torch.nn.functional as F
from models.model_loader import ModelLoader
from train.trainer_loader import TrainerLoader
from utils.data.data_prep import DataPreparation
import utils.arg_parser
from utils.misc import get_split_str
from PIL import Image
imp... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 18 16:03:21 2019
@author: elijahsheridan
"""
from . import ode
import vpython as vp
from vpython import vector as vec
from vpython.no_notebook import stop_server
import numpy as np
from scipy.integrate import solve_ivp
def justOne(func, x0, tEnd=... |
<gh_stars>1-10
## Backpropagation learning on shuffled data
# to be run on a server or cluster
# Run as: python test_mf_grc_backprop_biophys_shuffle.py basedir
# Where basedir is the base directory containing spike pattern data
import numpy as np
import pickle as pkl
import scipy.io as io
from datetime import datetim... |
import pandas as pd
import numpy as np
import subprocess
import dash
dash.__version__
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output,State
import plotly.graph_objects as go
from sklearn import linear_model
reg = linear_model.LinearRegression(fit_inter... |
import cmath
import numpy as np
import math
from decimal import Decimal
#Defines constants in SI units
h = (6.626*10**-34)/(2*np.pi)
m = float(input("mass? ")*9.11*10**-31)
E = float(input("energy? ")*1.602*10**-19)
#Defines the number of barriers and boundaries
n = input("Number of barriers? ")
S = 2*(n+1)
#initial... |
<filename>linearmodels/panel/model.py
from __future__ import annotations
from typing import Dict, List, NamedTuple, Optional, Tuple, Type, Union, cast
from formulaic import model_matrix
from formulaic.formula import Formula
from formulaic.model_spec import NAAction
from formulaic.parser.types import Structured
import... |
import imp
from textwrap import indent
from time import sleep
from turtle import color
from matplotlib.font_manager import json_load
from pyspark import SparkContext, SparkConf
from pyspark.sql import SQLContext
from pyspark.sql.functions import lit
import json
import numpy as np
import yake
import requests
import re
... |
#!/usr/bin/env python
# coding: utf-8
# In[13]:
import pandas as pd
medicare = pd.read_csv("/netapp2/home/se197/RPDR/<NAME>/3_EHR_V2/CMS/Data/final_medicare.csv")
# In[14]:
medicare = medicare[(medicare.Co_CAD_R0 == 1) | (medicare.Co_Diabetes_R0 == 1) | (medicare.Co_CAD_R0 == 1) |
(medicare.... |
#!/usr/bin/env python
#produces photometry according to Bickerton & Lupton 2013 http://arxiv.org/abs/1302.4764
import sys, numpy, scipy.special as special
import pyfits
def gaussianImage(n, center_x, center_y, sigma):
image = numpy.zeros([n, n], dtype=float)
for ix in range(n):
for ... |
# --------------
# code ends here
loan_groupby= banks.groupby(['Loan_Status'])['ApplicantIncome', 'Credit_History']
mean_values =loan_groupby.mean()
# code ends here
# --------------
# Import packages
import numpy as np
import pandas as pd
from scipy.stats import mode
bank = pd.read_csv(path)
categorical_var ... |
<gh_stars>0
import math
import numpy as np
from . import divide0
def _sph_harm_norm(order, degree):
"""Normalization factor for spherical harmonics"""
# we could use scipy.special.poch(degree + order + 1, -2 * order)
# here, but it's slower for our fairly small degree
norm = np.sqrt((2*degree + 1.)/(4*... |
#! /usr/bin/env python
""" This module provides functions useful for Sersic profiles,
including a 3d deprojected approximation for a Sersic-n function.
"""
import os
from os.path import join as joinpath
import copy
### Importing the required stuff from different modules
import numpy as np
from numpy import pi, log10,... |
<filename>SatGen/evolve.py
################## Functions for satellite evolution ####################
# <NAME> 2016, HUJI --- original version
# <NAME> 2019, HUJI, UCSC --- revisions
# <NAME> 2020, Yale University
#########################################################################
import sys
from . import config... |
import numpy as np
from scipy.spatial.distance import cdist
from scipy.special import softmax
class DropClassifier:
"""Probabilistic Output Extreme Learning Machine"""
def __init__(self, hidden_layer_size=5, dropconnect_pr=0.5, dropout_pr=0.5, dropconnect_bias_pctl=None, dropout_bias_pctl=None):
self.hidden_layer_... |
<reponame>hcyz33/PlaneSweepPose
import os
import copy
import logging
import pickle
import json
from collections import OrderedDict
import aist_plusplus
import numpy as np
import scipy.io as scio
from scipy.cluster.hierarchy import linkage, fcluster
from scipy.spatial.distance import squareform
import torch
from utils... |
<reponame>MauroLuzzatto/legal-entropy
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 14 18:26:14 2020
@author: mauro
"""
import os
import sys
import pickle
import json
import configparser
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from matplotlib import colors as mco... |
import pandas as pd
import os
import re
import math
from scipy import stats
def csv_files(stock_folder):
csvs = []
for file_name in os.listdir("./" + stock_folder):
if os.path.splitext(file_name)[1] == '.csv':
csvs.append(file_name)
assert len(csvs) > 0, "Add stocks data to folder"
... |
<reponame>warnerwarner/tensortools
"""
Miscellaneous functions for interpreting low-dimensional models and data.
"""
import numpy as np
import scipy.spatial
import math
import scipy as sci
from .tensor_utils import unfold
def soft_cluster_factor(factor):
"""Returns soft-clustering of data based on CP decompositi... |
<filename>openpnm/models/geometry/throat_shape_factor.py
import scipy as _sp
def compactness(target, throat_perimeter='throat.perimeter',
throat_area='throat.area'):
r"""
Mortensen et al. have shown that the Hagen-Poiseuille hydraluic resistance
is linearly dependent on the compactness. De... |
import scipy.integrate as integrate
import math
import numpy
global ncalls
def f(x):
global ncalls
ncalls=ncalls+1
return math.log(x)/math.sqrt(x)
ncalls=0
result = integrate.quad(f, 0, 1,epsabs=1e-5,epsrel=0)
print "result=",result,"ncalls=",ncalls
def g(x):
global ncalls
ncalls=ncalls+1
return math.exp(-x*... |
# -*- coding: utf-8 -*-
"""
Boolean Node
=============
Main class for Boolean node objects.
"""
# Copyright (C) 2021 by
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# All rights reserved.
# MIT license.
from __future__ import division
import numpy as np
import pandas as pd
from statistics impo... |
#import newspaper
#from keras.models import Sequential
#import keras
import re
import os
import nltk
from gensim.models import word2vec
import json
import numpy as np
import pandas as pd
from collections import Counter
from scipy.spatial.distance import cosine, euclidean, jaccard
from nltk.classify import NaiveBayesCla... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.