text string |
|---|
<filename>svca_limix/demos/demo_gp2kronSum.py
import scipy as sp
import scipy.linalg as la
import pdb
from limix.core.covar import FreeFormCov
from limix.core.mean import MeanKronSum
from limix.core.gp import GP2KronSum
from limix.core.gp import GP
from limix.utils.preprocess import covar_rescale
import time
import cop... |
#!/usr/bin/env python
# coding: utf-8
# # Lab 4 Ordinary Differential Equations, Part 1
# In[ ]:
from scipy.integrate import solve_ivp
import matplotlib.pyplot as plt
import numpy as np
# In[ ]:
get_ipython().run_line_magic('run', './ODESolvers.py')
# ### Introduction: The basics
# Consider the given ODE
# ... |
#!/usr/bin/python3
# -*- coding=utf-8 -*-
import numpy as np
from scipy.special import expit
from common.yolo_postprocess_np import yolo_handle_predictions, yolo_correct_boxes, yolo_adjust_boxes
def yolo5_decode_single_head(prediction, anchors, num_classes, input_dims, scale_x_y):
'''Decode final layer features ... |
import argparse
import logging
import numpy as np
import scipy.sparse as sp
import scipy.io
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_auc_score
logger = logging.getLogger(__name__)
def load_label(file, variable_name="group"... |
import h5py
import random
import numpy as np
import pickle
import scipy.misc
import os
from scipy.sparse import csr_matrix
def get_sample(input_file, output_file, num_authors=40, num_forms_per_author=15):
'''
Create a small set of training data from the larger hdf5 file. Limit output to authors with a sufficie... |
<filename>rttools/peirce.py
"""Run Pierce's criterion to reject data.
Implementation after Ross (2003) using calculation method for table from Wikipedia.
Note that the table that Ross (2003) presents is for `R`, which is the square root
of what `x**2` means in Gould (1855). Also, the first value of Ross (2003) for
thr... |
import numpy as np
from PIL import Image as IMG
import cv2
from skimage.io import imread, imshow
from scipy.stats import itemfreq
def dominant_color(img):
# img should be the img object or path to the image
# read in image using openCV
img = cv2.imread(img)
# convert to float32
img = np.float32(img... |
<filename>wildcard/model/linear_cg_model.py
import numpy as np
from collections import Counter
from scipy import stats
from sklearn import linear_model
from sklearn.feature_extraction import DictVectorizer
from sklearn.feature_selection import f_regression
from sklearn.linear_model import LinearRegression
from wildcar... |
<filename>Analysis/network_eval.py
# Dependencies
from torchvision import transforms
from torchvision.datasets import MNIST
from torch.utils.data import DataLoader
import torch
import matplotlib.pyplot as pyp
import numpy as np
from datetime import datetime
from time import time
import glob
import ast
import librosa
im... |
<gh_stars>0
import pandas as pd
import numpy as np
import scipy.optimize
import ctypes
def enumerable2ctypes(enumerable):
t = ctypes.c_double*len(enumerable)
arr = t()
for i, value in enumerate(enumerable):
arr[i] = value
arr_len = ctypes.c_int
arr_len = len(enumerable)
return arr, arr_... |
import pandas as pd
import numpy as np
import itertools
import scipy.stats as stats
groupby_name_by_type = {pd.core.groupby.DataFrameGroupBy:lambda df: df.keys,
pd.core.frame.DataFrame:lambda df: None}
class CorrelationBase():
overview_legend = 'binary'
def is_computable(self,... |
# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <codecell>
from pandas import DataFrame, Series, merge, read_csv, MultiIndex, Index, concat
from subprocess import check_call
from tempfile import NamedTemporaryFile as NTF
import os, os.path
import numpy as np
from scipy.stats import ttest_ind
from itertools impor... |
<gh_stars>100-1000
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import sys
if sys.version[0] == '2':
import cPickle as pkl
else:
import pickle as pkl
import numpy as np
import tensorflow as tf
from scipy.sparse import coo_matrix
DTYPE = tf.float... |
#!/usr/bin/env python3
import os.path
import tensorflow as tf
import aug_helper
import warnings
from distutils.version import LooseVersion
import project_tests as tests
from moviepy.editor import VideoFileClip
import scipy.misc
import numpy as np
# Check TensorFlow Version
assert LooseVersion(tf.__version__) >= Loose... |
<reponame>andycasey/gmmmml<gh_stars>1-10
"""
Plot the results from the evaluations on artificial data.
"""
# TODO: Get these from somewhere else?
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import scipy.optimize as op
import pickle
from collections import OrderedDict
from glob import glob
... |
"""
SpeedFpClamp Data Analysis
<NAME>
UNC Chapel Hill Applied Biomechanics Laboratory
2021
Run the script to perform data analysis and generate all article figures
Data avaible at https://drive.google.com/file/d/1PrpgwxUbaDNYojghtbIORW3qLK66NI31/view?usp=sharing
"""
import pandas as pd
import numpy as np
... |
<filename>imitation_cl/data/helloworld.py
import os
import numpy as np
import torch
import glob
import matplotlib.pyplot as plt
from scipy import interpolate
from scipy.signal import savgol_filter
from copy import deepcopy
class HelloWorld():
def __init__(self, data_dir, filename, norm=True, device=torch.device('c... |
<reponame>sdpython/mlprodic
# -*- encoding: utf-8 -*-
# pylint: disable=E0203,E1101,C0111
"""
@file
@brief Runtime operator.
"""
from scipy.spatial.distance import cdist
from ._op import OpRunBinaryNum
from ._new_ops import OperatorSchema
from ..shape_object import ShapeObject
class CDist(OpRunBinaryNum):
atts =... |
<gh_stars>1-10
import numpy
import scipy.integrate
class Solver(object):
"""
Solver is a wrapper of scipy's VODE solver.
"""
def __init__(self, dy_dt, y_0, t_0 = 0.0, ode_config_callback = None):
"""
Initialise a Solver using the supplied derivative function dy_dt,
initial value... |
<gh_stars>0
import fractions
a, b = map(int, input().split())
def lcm(x, y):
return (x * y) // fractions.gcd(x, y)
print(lcm(a, b))
|
# This code is from https://github.com/automl/pybnn
# pybnn authors: <NAME>, <NAME>
import emcee
import logging
import numpy as np
from scipy.optimize import nnls
from scipy.stats import norm
from naslib.predictors.lce_m.curvefunctions import curve_combination_models, \
model_defaults, all_models
from naslib.pred... |
<filename>contactnets/utils/processing/process_dynamics.py
# flake8: noqa
# TODO: clean up
import csv
import glob
import math
import os
import pdb # noqa
import pickle
import random
from random import randrange
import time
from typing import List, Tuple
import click
import matplotlib.pyplot as plt
import numpy as np... |
# -*- coding: utf-8 -*-
"""
Subspace identification of a Multiple Input Multiple Output (MIMO) state space models of dynamical systems
x_{k+1} = A x_{k} + B u_{k} + Ke(k)
y_{k} = C x_{k} + e(k)
This file contains the following functions
- "estimateMarkovParameters()" - estimates the Markov parameters
- "estim... |
"""
Copyright Government of Canada 2018
Written by: <NAME>, Public Health Agency of Canada
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this work except in compliance with the License. You may obtain a copy of the
License at:
http://www.apache.org/licenses/LICENSE-2.0
Unless requi... |
<gh_stars>1-10
from scipy.spatial import distance as set_distance
import os
import imageio
import numpy as np
def SRS(points, percentage=0.2):
new_batch = np.zeros(points.shape)
for j in range(points.shape[0]):
new = None
n = int(round(points.shape[1] * percentage))
idx = np.arange(poin... |
<filename>perforad.py
import sympy as sp
import textwrap
from operator import itemgetter
verbose = False
verboseprint = print if verbose else lambda *a, **k: None
class LoopNest:
def __init__(self,body,bounds,counters,arrays,scalars,ints):
self.body = body
self.bounds = bounds
self.counters = counters
... |
<reponame>ZhengzeZhou/slime
"""
Least Angle Regression algorithm. See the documentation on the
Generalized Linear Model for a complete discussion.
"""
# Author: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# <NAME>
#
# License: BSD 3 clause
from math import log
import sys
import warnings
import numpy as np
fro... |
#!/usr/bin/env python3
#
# Copyright (c) 2017-2018 <NAME> <<EMAIL>>
# MIT license
#
"""
FITS image manipulate tool.
"""
import sys
import argparse
import numpy as np
from astropy.io import fits
from scipy import ndimage
class FITSImage:
"""
FITS image class that deals with plain 2D image (NAXIS=2), but als... |
from itertools import permutations
from operator import itemgetter
import statistics
def hamming_dist(x, y):
return bin(x ^ y).count('1')
def hamming_weight(x):
return bin(x).count('1')
def bitfield(x, n):
return [int(d) for d in bin(x)[2:].zfill(n)]
def bitwise_mode(iterable, n):
iter_bin = [bin(x... |
<filename>models/glow/invertible_1x1_conv.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Date : Jul-14-21 16:11
# @Author : <NAME> (<EMAIL>)
import math
import numpy as np
import torch
import torch.nn as nn
from torch.nn.parameter import Parameter
import torch.nn.functional as F
class Invertible_1x1_Conv(n... |
# pylint: disable=no-member
import ANNarchy_future as ann
import numpy as np
import sympy as sp
import matplotlib.pyplot as plt
mu = 0.0
sigma = 0.1
class RC(ann.Neuron):
def __init__(self, params):
self.tau = self.Parameter(params['tau'])
self.mu = self.Parameter(0.0)
self.sigma = self... |
<reponame>reading-stiener/Audio-to-audio-alignment-research
'''
Code for aligning an entire dataset
'''
import glob
import scipy.spatial
import librosa
import os
import numpy as np
import create_data
#import djitw
import collections
def load_dataset(file_glob):
"""Load in a collection of feature files created by ... |
<gh_stars>0
import cv2
import numpy as np
from skimage import transform, color, restoration, feature, filters
from skimage.morphology import disk
import numba
from numba import njit
import skimage.io as io
from scipy import optimize
from matplotlib import pyplot as plt
from scipy.stats import norm, multivariate_normal
... |
<reponame>SIGKDDanon/SIGKDD2021DeAnonV2<filename>PostDiffMixture/simulations_folder/Old/simulation_analysis_scripts/rectify_vars_and_wald_functions.py
import numpy as np
import scipy.stats
def rectify_vars_Na(df):
'''
pass in those which have NA wald
'''
assert (np.sum(df["sample_size_1"] == 0) + np.sum... |
<filename>sparse_autoencoder.py
import numpy as np
from functools import partial
import matplotlib.pyplot as plt
from scipy.optimize import fmin_l_bfgs_b
def normalizeData(patches):
# Remove DC (mean of images)
patches = patches - np.mean(patches)
# Truncate to +/-3 standard deviations and scale ... |
<gh_stars>0
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 24 11:01:42 2020
@author: amarmore
"""
# Everything related to the segmentation of the autosimilarity.
import numpy as np
import math
from scipy.sparse import diags
import musicntd.model.errors as err
import warnings
def get_autosimilarity(an_array, transpo... |
from __future__ import print_function
import autopep8
import itertools
from lark import Lark, Transformer
from os import path
from scipy.stats import rankdata
from six import iteritems, next
class MyTransformer(Transformer):
def __init__(self):
self.cmdlist = []
self.window = 2
self.v... |
<reponame>ktanidis2/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra<gh_stars>1-10
import scipy.special
import scipy.interpolate
from numpy import log, exp, cos, pi
from cosmosis.datablock import option_section
import numpy as np
def log_interp(x, y):
s = scipy.interpolate.interp1d(log(x), log(y))
... |
<gh_stars>0
from scipy import mat, sin, zeros
K = mat('1 0 0;0 2 0;0 0 3')
M = mat('4 1 0;1 4 1;0 1 2')/6.0
r = mat('0;-1;1')
def load(t): return r*sin(7.0*t) #
h = 0.005; duration = 6.0
# linear acceleration coefficients
A = 3.0*M; V = 6.0*M/h
Flex = (K + 6.0*M/(h*h)).I
MI = M.I
# initial state
t = 0
x, v, p = mat... |
<gh_stars>1-10
#!/usr/bin/env python3
# Copyright © 2021 Helmholtz Centre Potsdam GFZ German Research Centre for Geosciences, Potsdam, Germany
#
# 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
#
#... |
from tidalclassifier.cnn.individual_cnn.meta_CNN import custom_flow_from_directory, create_model, fold_tables, trainCNNOnTable
from tidalclassifier.utils.helper_funcs import ThreadsafeIter, shuffle_df
import pandas as pd
import numpy as np
from sklearn.metrics import accuracy_score, log_loss, roc_curve, roc_auc_score, ... |
import numpy as np
from scipy.cluster.vq import _vq
from vq_lp import vq_lp, lp_update_centroids
def run_():
nb, nq, d = 100000, 100, 16
ks = 256
xs = np.random.uniform(size=(nb, d))
centroids = np.random.uniform(size=(ks, d))
codes_, dists_ = _vq.vq(xs, centroids)
cb, _ = _vq.update_cluster... |
#Ref: <NAME>
"""
This code performs grain size distribution analysis and dumps results into a csv file.
Step 1: Read image and define pixel size (if needed to convert results into microns, not pixels)
Step 2: Denoising, if required and threshold image to separate grains from boundaries.
Step 3: Clean up image, if ne... |
<gh_stars>0
import matplotlib.pyplot as plt
import numpy as np
import scipy
from scipy import signal
class LQR_Control():
"""
Continuous Infinite Horizon Linear Quadratic Control
"""
def __init__(self, A, B, Q, R, target = 0):
self.Q = Q
self.R = R
self. K = self._get... |
<reponame>ngunnar/learning-a-deformable-registration-pyramid
#!/usr/bin/env python3
from argparse import ArgumentParser
import nibabel as nib
import numpy as np
from scipy.ndimage.interpolation import zoom as zoom
from model import Model
from DataGenerators import Task4Generator, MergeDataGenerator
import re
import tim... |
"""A general module with tools for use with the saltfp package"""
import math
import numpy as np
import scipy.ndimage as nd
from saltfit import interfit
from FPRing import FPRing, ringfit
def fpfunc(z, r, t, coef=None):
"""A functional form fitting the Fabry Perot parameterization. The
FP parameterization... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 8 10:35:23 2020
@author: X202722
"""
import itertools
import functools
import pandas as pd
import numpy as np
from runVAPS_rev5 import parameters
from fitVapToExpValuesTest import clapeyron, clapeyronFit
# from samplingCoefficients_fitall import samplingCoe... |
<filename>tSNE_mice/tSNE_visulizer_mice.py
import numpy as np
import umap
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn import manifold
from sklearn.cluster import KMeans
from sklearn.cluster import SpectralClustering
from sklearn.cluster import AgglomerativeClustering
from matplotl... |
<filename>preprocessing/pd.py
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import scipy.signal
from scipy.signal import savgol_filter
import preprocessing.pre_utils as pu
from sklearn.preprocessing import MinMaxScaler, StandardScaler
import preprocessing.fap as pfap
im... |
<filename>objectron.py
import os
import sys
import argparse
import numpy as np
import cv2
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from scipy.ndimage.filters import maximum_filter
from openvino.inference_engine import IECore
def detect_peak(image, filter_size=3, order=0.5):
local_max = m... |
<reponame>hurlbertvisionlab/fc4
import cv2
#import cPickle as pickle
import _pickle as cPickle
import scipy.io
import numpy as np
import os
import sys
import random
from utils import slice_list
SHOW_IMAGES = False
FOLDS = 3
DATA_FRAGMENT = -1
BOARD_FILL_COLOR = 1e-5
def get_image_pack_fn(key):
ds = key[0]
if ds... |
import numpy as np
from scipy import ndimage
class edfMap():
def __init__(self, obstMap, cellSize, mapSize):
self.cellSize = cellSize
self.mapSize = mapSize
self.map = None
self.update(obstMap)
def update(self, obstMap):
self.map = ndimage.distance_transform_edt((~o... |
<gh_stars>1-10
import sys
import numpy as np
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
plt.ioff()
import random
from scipy import sparse
from scipy.special import comb
from scipy.special import gammaln
from scipy.special import erfcx
from scipy.stats import norm
import scipy.stats
import s... |
"""
The :mod:`scikitplot.metrics` module includes plots for machine learning
evaluation metrics e.g. confusion matrix, silhouette scores, etc.
"""
from __future__ import absolute_import, division, print_function, \
unicode_literals
import itertools
import matplotlib.pyplot as plt
import numpy as np
from sklearn... |
import numpy
import random
import scipy
import scipy.signal
import librosa
import matplotlib.pyplot as plt
from ..multipitch import Multipitch
from ..chromagram import Chromagram
from ..dsp.frame import frame_cutter
from collections import OrderedDict
class MultipitchHarmonicEnergy(Multipitch):
def __init__(
... |
#!/bin/python
#-----------------------------------------------------------------------------
# File Name : event_timeslices.py
# Author: <NAME>
#
# Creation Date :
# Last Modified : Thu 16 May 2019 02:13:09 PM PDT
#
# Copyright : (c) UC Regents, <NAME>
# Licence : GPLv2
#-----------------------------------------------... |
<gh_stars>1-10
import argparse
import os
import ipdb
import numpy as np
import scipy.io as sio
import pandas as pd
import torch
import pickle
from utils import get_datadir, labels_mapping, get_data_stats
from sklearn.metrics import accuracy_score
from sklearn import preprocessing
from torch.utils.data import Dataset
... |
<filename>xclib/classifier/slice.py
import numpy as np
from multiprocessing import Pool
import time
from .base import BaseClassifier
from ..utils import shortlist_utils, utils
import logging
from ._svm import train_one
import scipy.sparse as sp
import _pickle as pickle
from functools import partial
import os
from ..dat... |
from numpy.fft import fftfreq
from scipy.fftpack import fft
import unittest
import numpy as np
from matplotlib import cm
import matplotlib.pyplot as plt
from soundsig.signal import bandpass_filter,lowpass_filter,highpass_filter, mt_power_spectrum, power_spectrum,match_power_spectrum
from soundsig.coherence import cr... |
<reponame>dfm/igrins_rv
import numpy as np
from scipy.interpolate import interp1d, splev, splrep
def bin_ndarray(ndarray, new_shape, operation='mean'):
"""
Bins an ndarray in all axes based on the target shape, by summing or
averaging.
Number of output dimensions must match number of input dimens... |
# Copyright 2019 TerraPower, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writi... |
<filename>src/EMesh.py
import numpy as np
from src.mesh import triangulate_vertices
from src.mesh import build_Laplacian
class EMesh:
"""
Construct a class to compute E_Mesh as in formula 11 using a function to pass directly the personalized blendshapes
in delta space delta_p (dp)
k:= num_of_blendsh... |
<reponame>Ravan339/LeetCode<filename>Python/max-points-on-a-line.py
# https://leetcode.com/problems/max-points-on-a-line/
# Definition for a point.
# class Point:
# def __init__(self, a=0, b=0):
# self.x = a
# self.y = b
from fractions import Fraction
class Solution:
def maxPoints(self, po... |
<filename>laplacian_eigenmaps/LE.py
from sklearn.metrics import pairwise_distances
import numpy as np
from scipy.linalg import eigh
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import warnings
import networkx as nx
class LE:
def __init__(self, X:np.ndarray, dim:int, k:int = 2, eps =... |
#!/usr/bin/python2.7
from __future__ import division
import os
import urllib, cStringIO
import pymongo as pm
import numpy as np
import scipy.stats as stats
import pandas as pd
import json
import re
from PIL import Image
import base64
import sys
'''
To generate main dataframe from pymongo database, run, e.g.:
exp1... |
# install munkres module for the calculation of the Hungarian matrix: http://software.clapper.org/munkres/#installing
# pip install munkres
from munkres import Munkres
import numpy as np
import re
import copy
import matplotlib.pyplot as plt
import math
import scipy
import six
from matplotlib import colors
color = list... |
import argparse
import os
import scipy.stats
import numpy as np
def sum_list(a):
total = 0
for i in a:
total += i
return total
def process(inp_folders, out_file_prefix):
#Result [opt_name][folder_name] = [opt_remarks]
result = {}
file_count = 0
folders = set()
for folder in ... |
from __future__ import print_function
from __future__ import absolute_import
#=======================================================================================================================
# Multilayer perceptron is given in a separate file since it is not available in the python version employed in
# the othe... |
#! /usr/bin/env python
import os
import unittest
import numpy as np
import openravepy as orpy
# Tested package
import raveutils as ru
class Test_visual(unittest.TestCase):
@classmethod
def setUpClass(cls):
# Check there is a display available
display_available = False
if os.environ.has_key('DISPLAY'):... |
<gh_stars>0
import sys
import os
import argparse
import numpy as np
from scipy.io import savemat, loadmat
from omegaconf import OmegaConf
import project_path
from sklearn.neighbors import kneighbors_graph
from util.contaminate_data import contaminate_signal
from util.t2m import t2m
from util.horpca import horpca
fro... |
<gh_stars>1-10
#!/users/grad/sherkat/anaconda2/bin/python
# Author: <NAME> - 2016
import sys, os
import re
import unicodedata
import string
from nltk.stem.wordnet import WordNetLemmatizer
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
from sklearn.decomposition import NMF, LatentDirichletA... |
<reponame>jeremiedecock/snippets
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Read the content of an audio wave file (.wav)
# See: http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.io.wavfile.read.html
from scipy.io import wavfile
rate, nparray = wavfile.read("./test.wav")
print(nparray)
print("f... |
__all__ = [
'OutlineContinents',
'GlobeSource',
]
import numpy as np
import pyvista as pv
import vtk
from .. import interface
from ..base import AlgorithmBase
class OutlineContinents(AlgorithmBase):
"""A simple data source to produce a ``vtkEarthSource`` outlining the
Earth's continents. This works ... |
"""Main entry points for scripts."""
from __future__ import print_function, division
from argparse import ArgumentParser
from collections import OrderedDict
from copy import copy
from datetime import datetime
import glob
import json
import logging
import math
import os
import scipy.stats
import numpy as np
from .ve... |
<reponame>RTMAAI/CO600-Musical-Analysis<filename>rtmaii/analysis/spectral.py
""" SPECTRAL MODULE
This module handles temporal to spectral signal conversion.
INPUTS:
Signal: Temporal wave form.
OUTPUTS:
Spectrum: Frequency spectrum of the input sample.
"""
from scipy.signal import butter, l... |
import operator
import sympy
from bigo_ast.bigo_ast import FuncDeclNode, ForNode, FuncCallNode, CompilationUnitNode, IfNode, VariableNode, \
AssignNode, ConstantNode, Operator
from bigo_ast.bigo_ast_visitor import BigOAstVisitor
class BigOCalculator(BigOAstVisitor):
def __init__(self, root: CompilationUnit... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import statsmodels.graphics.tsaplots as sgt
from statsmodels.tsa.arima_model import ARMA
from scipy.stats.distributions import chi2
import statsmodels.tsa.stattools as sts
# ------------------------
# load data
# ----------
raw_csv_data = pd.rea... |
import numpy as np
import pandas as pd
from scipy.optimize import least_squares
from scipy.optimize import OptimizeResult
from numba.typed import List
from mspt.diff.diffusion_analysis_functions import calc_msd, calc_jd_nth, lin_fit_msd_offset, lin_fit_msd_offset_iterative
from mspt.diff.diffusion_analysis_func... |
import math
import statistics
from typing import Callable, Dict, List, Tuple
def read_input() -> List[Tuple[int, ...]]:
points: List[Tuple[int, ...]] = []
nb_points = int(input())
for _ in range(nb_points):
point: Tuple[int, ...] = tuple(map(int, input().split())) # nb_items, time
points.... |
from django.db import models
from django.contrib.auth.models import User
from tinymce.models import HTMLField
from django.db.models import Q
from statistics import mean
import datetime as dt
# Create your models here.
# class categories(models.Model):
# categories= models.CharField(max_length=100)
# def __s... |
<reponame>Garettld/phys218_example
import numpy as np
import pint
ureg = pint.UnitRegistry()
# (a)
ureg.define('Solar_Mass = 2e30 * kilogram = Msolar')
M = 1 * ureg.Msolar
G = 1 * ureg.newtonian_constant_of_gravitation
c = 1* ureg.speed_of_light
rsch = G.to_base_units() * M.to_base_units() / c.to_base_units()**2 / ... |
<reponame>jvendrow/Network-Dictionary-Learning
import numpy as np
import networkx as nx
from ndl.NNetwork import Wtd_NNetwork
from sklearn.metrics import roc_curve
from sklearn.metrics import auc
from scipy.spatial import ConvexHull
import matplotlib.pyplot as plt
def recons_accuracy(G, G_recons):
"""
Calcula... |
<filename>python/data_viz.py
import sys
import random as rd
import matplotlib
#matplotlib.use('Agg')
matplotlib.use('TkAgg') # revert above
import matplotlib.pyplot as plt
import os
import numpy as np
import glob
from pathlib import Path
from scipy.interpolate import UnivariateSpline
from scipy.optimize import curve_fi... |
print("Loading dependencies")
import anndata
import random
import pandas as pd
import numpy as np
import scipy.sparse
# VIASH START
par = {
"input_mod1": "resources_test/common/test_resource.output_rna.h5ad",
"input_mod2": "resources_test/common/test_resource.output_mod2.h5ad",
"output_mod1": "resources_te... |
import numpy as np
from matplotlib import pyplot as plt
from pyWMM import WMM as wmm
from pyWMM import mode
from pyWMM import CMT
from scipy import integrate
from scipy import io as sio
filename = 'sweepdata.npz'
npzfile = np.load(filename)
x = npzfile['x']
y = npzfile['y']
Eps = npzfile['Eps']
Er = npzfile['Er']
Ez =... |
<gh_stars>0
from scipy.stats import describe
from numpy import set_printoptions, ndarray as ndarr
set_printoptions(suppress=True)
def print_description(x):
desc_x = describe(x)
if isinstance(x[0], ndarr):
# Loop every "feature" and print its description
for i in range(len(x[0])):
f... |
"""
Data Envelopment Analysis implementation
Sources:
<NAME> (2006) Service Productivity Management, Improving Service Performance using Data Envelopment Analysis (DEA) [Chapter 2]
ISBN: 978-0-387-33211-6
http://deazone.com/en/resources/tutorial
"""
import numpy as np
from scipy.optimize import fmin_slsqp
class DE... |
import os, glob, sys, warnings, array, re, math, time, copy
import numpy as np
import matplotlib.pyplot as plt
from astropy.io import fits
from astropy.io import ascii
from scipy.interpolate import interp2d, interp1d
__file__
class Convolution(object):
def __init__(self, ... |
import numpy as np
import scipy.io as sio
import os
from PIL import Image, ImageChops
from tqdm import tqdm
#download from
image_url = "http://imagenet.stanford.edu/internal/car196/car_ims.tgz"
annotation_url = "http://imagenet.stanford.edu/internal/car196/cars_annos.mat"
#cut white margin
def trim(im):
bg = Ima... |
<reponame>s4hri/hidman
import pytest
import threading
import time
import statistics
from hidman.core import HIDServer, HIDClient
class TestLatency:
def test_run(self):
serv = HIDServer()
t = threading.Thread(target=serv.run)
t.start()
client = HIDClient()
client.waitEvent... |
"""
This code implements a probabilistic matrix factorization (PMF) per weeks 10 and 11 assignment of the machine learning module part of Columbia University Micromaster programme in AI.
Written using Python 3.7 and adjusted to ensure it runs on Vocareum.
Execute as follows:
$ python3 hw4_PMF.py ratings.csv
"""
fro... |
<reponame>Anysomeday/FDSSC
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import scipy.io as sio
import tensorflow as tf
from keras.utils.np_utils import to_categorical
from keras.optimizers import Adam, SGD, Adadelta, RMSprop, Nadam
from sklearn import preprocessing
from Utils import fdssc_... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
###
# Name: Amelia & Gwyneth
# Student ID: 2289652
# Email: <EMAIL>
# Course: PHYS220/MATH220/CPSC220 Fall 2018
# Assignment: CW 11
###
import sympy as sp
import numpy as np
import matplotlib.pyplot as plt
I = np.array([[0,1],[-1,0]])
def euler_1(initP, change):
slo... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Fits distributions to data.
"""
import warnings
import time
import numpy as np
from multiprocessing import Pool, TimeoutError
from numbers import Number
import statsmodels.api as sm
import scipy.stats as sts
from scipy.optimize import curve_fit
from inspect import si... |
# Asignatura: Inteligencia Artificial (IYA051)
# Grado en Ingeniería Informática
# Escuela Politécnica Superior
# Universidad Europea del Atlántico
# Caso Práctico (ML_Clustering_Jerarquico_01)
# Importar librerias
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Cargar el conjunt... |
<gh_stars>100-1000
# -*- coding: utf-8 -*-
import numpy as np
from numpy.testing import assert_array_almost_equal
from scipy import stats
import pytest
from pmdarima.compat.pytest import pytest_error_str
from pmdarima.preprocessing import BoxCoxEndogTransformer
loggamma = stats.loggamma.rvs(5, size=500) + 5
@pytes... |
<gh_stars>10-100
import numpy as np
from scipy.ndimage import correlate
from math import ceil
from PIL import Image
from PIL.Image import ANTIALIAS
from numba import jit
import pdb
def DoG_normalization(img):
img = img.astype(np.float32)
img_out = np.zeros(img.shape).astype(np.float32)
img_sz = np.array([... |
"""
This example constructs makes a test disease model, similar to
diabetes, and sends that data to DismodAT.
1. The test model is constructed by specifying functions for
the primary rates, incidence, remission, excess mortality rate,
and total mortality. Then this is solved to get prevalence over time.
2. ... |
<reponame>alessiamarcolini/digital-pathology-classification
import os
from pathlib import Path
import numpy as np
import skimage.morphology as morph
from scipy import linalg, ndimage
from skimage import color
from skimage.filters import threshold_otsu
from sklearn.cluster import KMeans
from sklearn.decomposition impor... |
<gh_stars>1-10
# Time: O(n)
# Space: O(1)
#
# Rotate an array of n elements to the right by k steps.
#
# For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].
#
# Note:
# Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
#
cla... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.