text string |
|---|
<filename>fully-conv-classification/train_model_random_files.py<gh_stars>1-10
import os
# os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
# os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
import keras.backend as K
import tensorflow as tf
import numpy as np
from argparse import ArgumentParser
from tensorflow.keras.callbacks import (... |
<reponame>mariabuechner/gi_simulation
"""
GUI module for gi-simulation.
Usage
#####
python mainGUI.py [Option...]::
-d, --debug show debug logs
@author: buechner_m <<EMAIL>>
"""
import numpy as np
import sys
import re
from functools import partial
import os.path
import scipy.io
import logging
# Set kivy log... |
import json
import math
from dataclasses import dataclass, field
from datetime import date, timedelta, datetime
from pathlib import Path
from typing import Dict, Iterator, Optional, Sequence, Tuple, List
from dataclasses_json import DataClassJsonMixin
from scipy.stats import fisher_exact
from data_utils import json_i... |
# -*- coding: utf-8 -*-
#MIT License
#Copyright (c) 2017 <NAME>
#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in the Software without restriction, including without limitation the rights
#to use, copy, mod... |
<filename>mixmind/recipe.py
"""
DrinkRecipe class encapsulates how a drink recipe is calculated and formulated,
can provide itself as a dict/json, tuple of values, do conversions, etc.
Just generally make it better OOP
"""
import re
from fractions import Fraction
from recordtype import recordtype
import itertools
impor... |
<reponame>VivaaindreanNg/CMCS-Temporal-Action-Localization<filename>utils.py<gh_stars>0
from skimage.measure import label
from skimage.morphology import dilation
import os
import matlab
import json
import subprocess
import numpy as np
import pandas as pd
import torch
import torch.nn.functional as F
import random
from ... |
# [Description] ------------------------------
# Module name "Geocoding_ICOLD_QA.py"
# This module loops through all geocoding solutions for each ICOLD WRD record (output of Geocoding_ICOLD.py)
# and rank them based on their corresponding QA levels (see Table 5 in Wang et al. (2021). For each unique
# ICOLD WRD re... |
<gh_stars>1-10
from __future__ import division
from math import gamma
import numpy as np
import scipy as sp
from scipy.special import hyp2f1
from scipy.optimize import fmin
from functools import wraps
import inspect
__all__ = [
'cartesian', 'toy_data', 'coefficients', 'partials', 'stabilize', 'geometric_sum',
... |
#!/usr/bin/env python
# author: <NAME>
# email: <EMAIL>
# license: MIT
# Please feel free to use and modify this, but keep the above information.
"""
Script to check a calculation in a paper
and import :math:`a_0` and :math:`u` in kg
"""
from scipy.constants import hbar
from scipy.constants import pi
from scipy.cons... |
#!/usr/bin/python3
import bezier
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import scipy.optimize
# define control points
p_start = np.array([[1,2,3]]).T
p_end = np.array([[3,5,2]]).T
p0 = 0.5*(p_start + p_end) - np.array([[0,0,2]]).T
control_points = [p_start,p0,p_end... |
import time
import logging
from math import isclose
import numpy as np
from scipy.integrate import solve_ivp
try:
import pycvodes
except ImportError:
pycvodes = None
else:
from pycvodes import integrate_adaptive, integrate_predefined
from .trajectories import Trajectory
from .utils import GRAV_ACC, AIR_DE... |
<filename>finalytics/pricer/pricer_modules.py<gh_stars>0
'''
Created on Sep 17, 2016
@author: ashokmuthusamy
Adopted from http://www.codeandfinance.com/finding-implied-vol.html
'''
import pandas as pd
import numpy as np
import os
from scipy.stats import norm
import datetime as dt
def find_vol(target_value, call_pu... |
<filename>demo/python/scipy/scipy-integr3-01-tplquad.py
import scipy.integrate as spi
import numpy as np
print('Triple integral computed by SciPy tplquad')
print('Example 3-01 tplquad')
print('Integral of x + yz^2 from z=1 to z=2, y=z+1 to y=z+2 and from x=y+x to x=2(y+z)')
integrand = lambda x, y, z : x + y * z ** 2... |
<filename>simulator/static/python/rbatools/rba/core/targets.py
"""Module processing target information."""
# python 2/3 compatibility
from __future__ import division, print_function, absolute_import
# global imports
import numpy
from collections import namedtuple
from scipy.sparse import hstack
# local imports
from ... |
import numpy as np
from numpy.core.function_base import _logspace_dispatcher
from sklearn.preprocessing import OneHotEncoder
import pandas as pd
import scipy.sparse as sp
import torch
from torch.nn.functional import threshold
# 转换成独热编码
def encode_onehot(labels):
onehot_encoder = OneHotEncoder()
labels_oneho... |
import math
import numpy as np
from scipy.signal import convolve2d
from scipy.optimize import least_squares
import scipy.ndimage as scimg
import skimage.measure as skimsr
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
# Adapted version inspired by agpy gaussfitter
def gauss2d(x, y, h, a, x0,... |
<gh_stars>0
import glob
import time
import pickle
import matplotlib.pyplot as plt
from moviepy.editor import VideoFileClip
from sklearn.svm import SVC
from sklearn.preprocessing import StandardScaler
from sklearn.cross_validation import train_test_split
from sklearn.metrics import accuracy_score
from CarND.lesson_fun... |
import numpy as np
import cupy #Requires Cuda environment (and numpy). Also set CUPY_CACHE_DIR=/gpfs/gpfs0/deep/cupy, pip install cupy-cuda112
import pandas as pd
from scipy.stats import norm, percentileofscore
import scipy.stats as ss
import matplotlib.pylab as plt
import matplotlib as mpl
import itertools
# code in... |
import cmath as cm
import numpy as np
class Source:
def __init__(self, freq_hz, depth):
self.freq_hz = freq_hz
self.depth = depth
def aperture(self, k0, z):
pass
def max_angle(self):
pass
class GaussSource(Source):
def __init__(self, *, freq_hz, depth, beam_width,... |
import logging
from typing import Iterable
from tqdm import tqdm
import numpy as np
import scipy.sparse as ss
logger = logging.getLogger(__name__)
def activate_neighbors(
rule_matches_z: np.ndarray, indices: Iterable[np.ndarray]
) -> np.ndarray:
"""
Take provided closest neighbors and add their rule... |
<reponame>erwanM974/hibou_sensor_partial_observation_experiment<gh_stars>0
#
# Copyright 2022 <NAME> (github.com/erwanM974)
# 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.apac... |
<gh_stars>0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
A Python implementation of the method described in [#a]_ and [#b]_ for
calculating Fourier coefficients for characterizing
closed contours.
References
----------
.. [#a] <NAME> and <NAME>, “Elliptic Fourier Features of a
Closed Contour," Computer Visio... |
<reponame>huseinzol05/Hackathon-Huseinhouse
import utils_emotion
import utils_person
import model_emotion
import model_person
import settings_emotion
import settings_person
import tensorflow as tf
import numpy as np
import cv2
import tensorflow as tf
import os
from scipy import misc
_, output_dimension_emotion, label_... |
import eqpy
import sympy
from eqpy._utils import raises
def test_constants():
assert eqpy.nums.Catalan is sympy.Catalan
assert eqpy.nums.E is sympy.E
assert eqpy.nums.EulerGamma is sympy.EulerGamma
assert eqpy.nums.GoldenRatio is sympy.GoldenRatio
assert eqpy.nums.I is sympy.I
assert eqpy.nums... |
import numpy as np
from scipy import interpolate
import InstrumentDriver
class Driver(InstrumentDriver.InstrumentWorker):
"""This class implements downsampler."""
def performSetValue(self, quant, value, sweepRate=0.0, options={}):
"""Perform the Set Value instrument operation."""
return value
... |
<gh_stars>1-10
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 1 11:19:13 2017
@author: Thomas
"""
import numpy as np
import scipy.io
import keras
from keras.models import Sequential
from keras.layers import Dense, Activation
from keras.utils import np_utils
#%% Load dataset
from sklearn.datasets import fetch_mlda... |
import os.path
from os import path
import pwrcommon as pc
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from statistics import mean
def readData(dataPathP100):
freqs = [544, 556, 569, 582, 594, 607, 620, 632, 645, 658, 670, 683, 696, 708, 721, 734, 746, 759, 772, 784, 797, 810, 822, 835,... |
<gh_stars>0
import numpy as np
import scipy.linalg
from ch_bin.core.clustering.solve_qp import solve_qp
def convex_hull_distance(query: np.ndarray, points: np.ndarray, solver: str = "quadprog") -> float:
"""
Finds distance to the convex hull using the given solver.
:param query: Point to find the distan... |
<gh_stars>1-10
from db import db
import datetime
from scipy.interpolate import interp1d
from haishoku.haishoku import Haishoku
from time import sleep
from face import face
from color import color
date_range = 3000 * 24 * 60 * 60
delta_date = 0.01 * 24 * 60 * 60
date_format = '%Y-%m-%d %H:%M'
# output_file = 'D:/DataSo... |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 10 13:54:57 2016
@author: User
"""
import numpy
import scipy.constants as const
HaToInvcm=219474.6313705
BohrToAngstrom=0.52917721067
AmgstromToBohr=1.88972688
kcalmol1Tocm1=349.75
kcalmol1ToHa=0.00159362
konst1=7399643.84752676 # prevzal jsem ze sveho pr... |
<gh_stars>1-10
__author__ = 'paulo.rodenas'
from scipy.io import wavfile
import numpy as np
import ewlplot
import math
import sys
rate_full_music, dat_full_music = wavfile.read('/Users/paulo.rodenas/workspaceIdea/easywaylyrics/05-Sourcecode/03-Reference/echonestsyncprint/music/Iron_Maiden_Judas_Be_My_Guide_NoiseRemova... |
<gh_stars>1-10
#!/usr/bin/env python
"""Duffing oscillator SDE MAP state-path and parameter estimation."""
import importlib
import numpy as np
import sympy
import sym2num.model
from numpy import ma
from scipy import interpolate, stats, signal
from ceacoest import jme
from ceacoest.modelling import symjme, symsde, ... |
<reponame>giuliapezzutti/eeg-preprocessing<filename>src/ERDS.py
import numpy as np
import scipy.signal
from matplotlib import pyplot as plt
from more_itertools import locate
def compute_erds(epochs, rois, fs, t_min, f_max=50, path=None):
"""
Function to compute ERDS maps for a set of epochs according to diffe... |
<filename>omnizart/utils.py
"""Various utility functions for this project."""
# pylint: disable=W0212,R0915,W0621
import os
import re
import types
import logging
import uuid
import concurrent.futures
import importlib
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
import jsonschema
import pretty... |
import numpy as np
from NumbaLSODA import lsoda_sig, lsoda
from scipy.integrate import solve_ivp
import timeit
import numba as nb
# NumbaLSODA
@nb.cfunc(lsoda_sig,boundscheck=False)
def f_nb(t, u_, du_, p_):
u = nb.carray(u_, (3,))
p = nb.carray(p_, (3,))
sigma, rho, beta = p
x, y, z = u
du_[0] = s... |
<filename>maize_detrend_polyfit.py<gh_stars>0
#coding=utf-8
import pandas as pd
from scipy import polyfit
#import pylab
#import pylab
import glob
def Polyfit_detrend(x,y): #主程序,相当于C语言的main函数
a,b,c = polyfit(x, y, 2)
y_quad = a*x*x + b*x + c #利用拟合得到的系数,计算x向量对应的y向量
# 拟合结果绘图
# pyla... |
# Dataloader of ISCNet.
# author: ynie
# date: Feb, 2020
# Cite: VoteNet
import copy
import torch.utils.data
from torch.utils.data import DataLoader
from net_utils.libs import random_sampling_by_instance, rotz, flip_axis_to_camera
import numpy as np
from models.datasets import ScanNet
import os
from net_utils.box_util ... |
#!/usr/bin/python3
from collections import defaultdict
import copy
import matplotlib.pyplot as plt
import numpy as np
import scipy.ndimage
from typing import Dict, List
def scipy_conn_comp(img: np.ndarray) -> Dict[int, List[np.ndarray]]:
"""
labelsndarray of dtype int
Labeled array, wher... |
<reponame>xperthunter/BMRB_tools
import json
import sys
import statistics
data = None
with open('refdb.json') as fp:
data = json.load(fp)
count = {}
for item in data:
seq = item['seq']
for i in range(1, len(seq) -1):
if seq[i] != 'L': continue # focus on most common first
a3 = seq[i-1:i+2]
for atom in it... |
<reponame>YangLabHKUST/LOG-TRAM
import pandas as pd
import numpy as np
import logging
import sys
import copy
import os
from scipy import linalg
import scipy.stats as st
from scipy.stats import norm
import gc
import warnings
warnings.filterwarnings('ignore')
##
# Data loading and preprocessing
##
def configure_loggin... |
# -*- coding: utf-8 -*-
"""
create synthetic S, X1, X2, y quadraple
"""
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats
import time
import datetime
import sys
import os
import copy
import itertools
from sklearn import svm
from sklearn import tree
from sklearn import ensemble
from sklearn import li... |
import numpy as np
import pandas as pd
import scipy
from glob import glob
import numpy as np
import matplotlib.pyplot as plt
from skimage import transform
from __future__ import print_function, division
from keras.layers import Input, Dense, Reshape, Flatten, Dropout, Concatenate
from keras.layers import BatchNormal... |
<reponame>LXP-Never/Speech-signal-processing
import numpy as np
import matplotlib.pyplot as plt
from scipy.io import wavfile
from python_speech_features import mfcc, logfbank
# 读取输入音频文件
sampling_freq, audio = wavfile.read("input_freq.wav")
# 提取MFCC和滤波器组特征
mfcc_features = mfcc(audio, sampling_freq)
filterban... |
from __future__ import division
import logging
import sys
import os
import math
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
import xml.etree.ElementTree as ET
from collections import OrderedDict
import numpy as NP
from scipy.constants import mu_0
from scipy.io import savemat
from scipy.interpol... |
import branca.colormap as cmap
import folium
from folium.plugins import TimeSliderChoropleth
import geopandas as gpd
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
from scipy.stats import multivariate_normal
def load_data():
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from sklearn import datasets
from sklearn.model_selection import train_test_split
from scipy.stats import mannwhitneyu
import random
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import log_loss, accuracy_score, roc_auc_score, brier_score_loss
... |
<gh_stars>10-100
#!/usr/bin/python
# -*- coding: utf-8 -*-
""" fit a time-series model to SEAREV power production data
the model is based on an AR(2) for speed data
then speed is transformed into power knowing the speed->torque function
<NAME> — April 2013
"""
from __future__ import division, print_function, unicode... |
import pandas as pd
import numpy as np
import pylab as plt
import seaborn as sns
from sklearn import neighbors
from scipy.cluster import hierarchy
from scipy.spatial import distance
from scipy.spatial.distance import squareform,pdist
def one_nn_class_baseline(X,labels):
''' given a pointcloud X and labels, compute... |
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import time
class RandomWalkWithAbsorbingBarrier:
def __init__(self, length):
self.length = length
self.x_initial = 0
self.life_time = 0
def render(self, x_0):
self.x_initial = x_0
... |
<reponame>VictorOnink/Wind-Mixing-Diffusion
import utils
import settings
import numpy as np
import pandas as pd
from seabird.cnv import fCNV
from copy import deepcopy
import scipy.stats as stats
import analysis
def data_standardization():
"""
Running all the data standardization functions. Each standardizatio... |
<reponame>phylatechnologies/ibd_classification_benchmark
import numpy as np
import pandas as pd
import statsmodels.api as sm
from sklearn.preprocessing import OneHotEncoder
import statistics
import math
import sys
import itertools
np.seterr(over='raise')
def batch_pp(df, batch_column,ignore):
"""This function take... |
import numpy as np
from scipy.stats import t
def outliers_iqr(x, ret='filtered', coef = 1.5):
"""
Simple detection of potential outliers based on interquartile range (IQR).
Data that lie within the lower and upper limits are considered
non-outliers. The lower limit is the number that lies 1.5 IQRs be... |
# https://open.kattis.com/problems/temperatureconfusion
from fractions import Fraction
n, d = map(int, input().split('/'))
f = Fraction(n, d)
f -= 32
f *= Fraction(5, 9)
print('%s/%s' % (f.numerator, f.denominator))
|
import os
from collections import defaultdict, namedtuple
from datetime import datetime, timedelta
from json import dumps
from typing import Any, AnyStr, Dict, List, NamedTuple, Union
import numpy as np
import requests
import tensorflow as tf
from fastapi import FastAPI
from kafka import KafkaProducer
from pydantic im... |
<gh_stars>1-10
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import os
from scipy.ndimage import imread
def get_data(directory, num_validation=2000):
'''
Load the SFDDD dataset from disk and perform preprocessing to prepare
it for the neural net classifier.
'''
# Load the raw S... |
from chiscore import davies_pvalue, optimal_davies_pvalue
class StructLMM:
r"""
Structured linear mixed model that accounts for genotype-environment interactions.
Let n be the number of samples.
StructLMM [1] extends the conventional linear mixed model by including an
additional per-individual ef... |
import pandas as pd
import numpy as np
import os
import sys
import pdb
from scipy.stats import binom_test
from statsmodels.stats import multitest
from collections import Counter
from GLOBAL_VAR import *
alignmetn_dir = '/work-zfs/abattle4/heyuan/tissue_spec_eQTL_v8/datasets/TFBS_ChIP_seq/STAR_output'
SNP_in_TFBS_di... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2015 mjirik <<EMAIL>>
#
# Distributed under terms of the MIT license.
"""
"""
import numpy as np
from loguru import logger
# logger = logging.getLogger()
import argparse
from scipy import ndimage
from . import qmisc
class ShapeModel():... |
#
# Valuation of European Call Options in BSM Model
# Comparison of Analytical, int_valueegral and FFT Approach
# 11_cal/BSM_option_valuation_FOU.py
#
# (c) Dr. <NAME>
# Derivatives Analytics with Python
#
import numpy as np
from numpy.fft import fft
from scipy.integrate import quad
from scipy import stats
import matpl... |
<filename>morl/population_3d.py
import numpy as np
import torch
import torch.optim as optim
from copy import deepcopy
from sample import Sample
from utils import get_ep_indices, generate_weights_batch_dfs, update_ep, compute_hypervolume, compute_sparsity, update_ep_and_compute_hypervolume_sparsity
from scipy.optimize i... |
"""Perform JPEG compression steps."""
import struct
from enum import Enum
from collections import namedtuple
import numpy as np
from scipy.fftpack import dct, idct
from ycbcr import rgb_to_ycbcr, ycbcr_to_rgb
class QuantizationTable(object):
def __init__(self, coefficients):
if coefficients.shape != (... |
"""
The :mod:`sbd` module implements a class which handles the loading and processing of the SBD (Semantic Boundary Dataset)"""
# Author: <NAME> (help of In<NAME> from another joint project,
# and help of <NAME> for point sampling)
# next two lines might work/be necessary only for mac
import mat... |
<gh_stars>10-100
# inpainting module
# part of "PYTHON Codes for the Image Inpainting Problem"
#
# Authors:
# <NAME> (email: sp751 at cam dot ac dot uk)
# <NAME> (email: cbs31 at cam dot ac dot uk)
#
# Address:
# Cambridge Image Analysis
# Centre for Mathematical Sciences
# Wilberforce Road
# CB3 0WA, Ca... |
<gh_stars>0
#A library of code to examine properties of bulk water and near solutes
#
#Should eventually be able to handle local densities and fluctuations,
#solute-water and water-water energies, 3-body angles, hydrogen bonds,
#energy densities, and all of this as a function of space. Additionally,
#should also be abl... |
# -----------------------------------------------------------------------------
# Copyright (c) 2019 <NAME>
# Distributed under the terms of the BSD License.
# -----------------------------------------------------------------------------
import sys
import tqdm
import som, mnist, plot
import numpy as np
import matplotli... |
<gh_stars>0
import numpy as np
from scipy.io import loadmat
# from scipy.optimize import fmin_cg
# Ignore overflow and divide by zero of np.log() and np.exp()
# np.seterr(divide = 'ignore')
# np.seterr(over = 'ignore')
def sigmoid(z):
return 1.0 / (1.0 + np.exp(-z))
def predict(Theta1, Theta2, X):
# Useful ... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import datetime
import logging
import warnings
import os
import pandas_datareader as pdr
from collections import Counter
from scipy import stats
from sklearn.metrics import r2_score, mean_squared_error, mean_absolute_percentage... |
<gh_stars>1-10
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.figure import Figure
from scipy.stats import kde
def do_density_diagramm(X,Y,X_short_name,Y_short_name,X_unit,Y_unit,Xlim,Ylim,fileout,show=True):
fig = plt.figure(figsize=(8.27, 11.69), dpi=100)
ax =fig.add_subplot(111)
... |
import warnings
import cvxpy as cp
import numpy as np
import numpy.linalg as la
import pandas as pd
import scipy.stats as st
from _solver_fast import _cd_solver
from linearmodels.iv import IV2SLS, compare
from patsy import dmatrices
from sklearn.base import BaseEstimator, ClassifierMixin, RegressorMixin
from sklearn.u... |
<filename>smallworld/tools.py
"""
Various handy things.
"""
import numpy as np
import networkx as nx
import scipy.sparse as sprs
def assert_parameters(N,k_over_2,beta):
"""Assert that `N` is integer, `k_over_2` is integer and `0 <= beta <= 1`"""
assert(k_over_2 == int(k_over_2))
assert(N == int(N))
... |
import numpy as np
# a = range(1000)
#
# b1 = a[0:10]
# b2 = a[10:20]
#
# c1 = []
# c1.append(b1)
# c1.append(b2)
#
# c2 = []
# c2.append(b1)
# c2.append(b2)
#
# d = []
# d.append(c1)
# d.append(c2)
# d = np.array(d)
# print(np.shape(d))
#
#
# import numpy as np
# import scipy as sp
# import matplotlib.pyplot as plt
#... |
<filename>OpenControl/ADP_control/system.py
import numpy as np
from scipy import integrate
from ..visualize import Logger
class LTI():
"""
This class present state-space LTI system.
Attributes:
dimension (tuple): (n_state, n_input).
model (dict): {A, B, C, D, dimension}.
ma... |
<gh_stars>0
#!/usr/bin/python3
#
#################################################
# #
# Title: PyFace #
# FileName: pyface.py #
# Author: <NAME> #
# Date: 05/12/2019 ... |
<filename>blowdown.py
###############################################################
# blowdown.py
#
# Script to calculate orifice size of ideal gas relief problem.
# Usage: ./blowdown.py 25 900
# Simulates blowdown through a 25 mm diameter orifice for 900 seconds.
#
# Dependencies: see requirements.txt
# <NAME> - 202... |
import numpy as np
from sklearn.ensemble import RandomForestRegressor
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
import sklearn.metrics as metrics
from scipy import stats
import matplotlib.pyplot as plt
import pykoda
def main():
START_HOUR = 9
EN... |
<gh_stars>1-10
#! /usr/bin/env python
import glob
import os.path as op
import os as os
import nibabel as nib
import pandas as pd
import numpy as np
import scipy as sp
import itertools
from nilearn.masking import compute_epi_mask
import matplotlib.pyplot as plt
import matplotlib as mpl
# Nilearn for neuro-imaging-sp... |
import numpy as np
from mpl_toolkits import mplot3d
from matplotlib import pyplot as plt
import matplotlib
matplotlib.rcParams['pdf.fonttype'] = 42
import pandas as pd
from traj_complete_ros.toppra_eef_vel_ct import plot_plan
from fastdtw import fastdtw
from scipy.spatial.distance import euclidean
def get_time_inde... |
#!/usr/bin/env python
import sys
sys.path.append('../lib/')
import numpy as np
import scipy.stats as stats
import pints
#
# Set up prior for Model A
#
class ModelALogPrior(pints.LogPrior):
"""
Unnormalised prior with constraint on the rate constants.
# Adapted from
https://github.com/CardiacModellin... |
import numpy as np
import scipy as sc
import qutip as qt
from qictp.qictp import purity
from numpy.testing import assert_,assert_equal,assert_almost_equal
def test_purity():
"""
Test the `purity` function.
"""
psi = qt.fock(3)
rho_test = qt.ket2dm(psi)
test_pure = purity(rho_test)
assert_equal(test_pure,1.1) |
#
# nd2cat (n-dimensional 2 categorical)
# Author: <NAME>
#
import numpy as np
import pandas as pd
import scipy.ndimage
import skimage
import skimage.color
import skimage.io as io
import skimage.transform as transform
from scipy.ndimage.filters import maximum_filter
from sklearn.cluster import KMeans
from sklearn.clu... |
<gh_stars>0
# coding: utf-8
# created by deng on 7/27/2018
from xgboost.sklearn import XGBClassifier
from lightgbm.sklearn import LGBMClassifier
from sklearn.svm import SVC, LinearSVC
from sklearn.model_selection import train_test_split, GridSearchCV, StratifiedKFold
from sklearn.linear_model import SGDClassifier
from... |
<filename>scripts/imLCAscript.py
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 25 13:54:12 2016
@author: Eric
"""
import argparse
import LCALearner
import scipy.io as io
parser = argparse.ArgumentParser(description="Learn dictionaries for LCA with given parameters.")
parser.add_argument('-o', '--overcom... |
<reponame>drewleonard42/CoronaTemps
# -*- coding: utf-8 -*-
"""
Created on Tue May 12 14:39 2015
@author: <NAME>
"""
import numpy as np
from scipy.io.idl import readsav as read
from os.path import expanduser
def gaussian(x, mean=0.0, std=1.0, amp=1.0):
"""Simple function to return a Gaussian distribution"""
... |
'''
Target: Compute structure similarity (SSIM) between two 3D volumes
Created on Jan, 22th 2018
Author: <NAME>
reference from: http://simpleitk-prototype.readthedocs.io/en/latest/user_guide/plot_image.html
'''
import SimpleITK as sitk
from multiprocessing import Pool
import os
import h5py
import numpy as np
import... |
import numpy as np
import scipy as sc
from fuel.datasets import H5PYDataset
from fuel.utils import find_in_data_path
from fuel.transformers import *
from scipy.misc import toimage
class SVHN(H5PYDataset):
N_global = None
height_global = None
width_global = None
n_iter_global = None
def fix_repres... |
<reponame>brettChapman/cimcb_vis
import sys
import numpy as np
import pandas as pd
import scipy.spatial as sp, scipy.cluster.hierarchy as hc
from scipy.spatial.distance import squareform
def cluster(matrix, transpose_non_similarity, is_similarity, distance_metric, linkage_method):
"""Performs linkage clustering gi... |
<filename>tests/test_utils_covariance.py<gh_stars>0
from numpy.testing import assert_array_almost_equal, assert_array_equal
import numpy as np
from scipy.signal import coherence as coh_sp
import pytest
from pyriemann.utils.covariance import (covariances, covariances_EP, eegtocov,
... |
<reponame>vikalibrate/FortesFit
import sys
import os
import glob
import numpy as np
from scipy.interpolate import interp1d
from scipy.integrate import trapz
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from astropy import units as u
from astropy.table import Table
import h5py
import emcee
from... |
<reponame>wingbender/SpinningUp
import numpy as np
from scipy.integrate import solve_ivp
G = 9.81
def odeFunc(t,y,a):
# y = [x,v], y_dot = [v,-g]
# y = [x,y,z,u,v,w,ax,ay,az]
return [y[1],-G+a]
sol = solve_ivp(odeFunc,[0,4],[100,0],t_eval=[4],args=[9.81])
print(sol.y[0][0])
|
<filename>sensor.py
import abc
import numpy as np
import scipy.stats
import smc_tools.util
class Sensor(metaclass=abc.ABCMeta):
def __init__(self, position, pseudo_random_numbers_generator):
# position is saved for later use
self.position = position
# pseudo random numbers generator
self._pseudo_random_... |
<reponame>herrlich10/mripy<filename>mripy/math.py<gh_stars>1-10
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import, unicode_literals
from collections import OrderedDict
import itertools
import numpy as np
from numpy.polynomial import polynomial
from scipy impo... |
import pytest
from pytest import approx
import numpy as np
from scipy.integrate import solve_ivp
from pysodes.odeint import integrate_const
def lotka_volterra(z, dzdt, t):
x, y = z
a = 1.5
b = 1.0
c = 3.0
d = 1.0
dzdt[0] = a*x - b*x*y
dzdt[1] = -c*y + d*x*y
return dzdt
def lotka_... |
from __future__ import print_function, division
import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from train_steering_wheel.train import (
MODEL_HEIGHT as CNN_MODEL_HEIGHT,
MODEL_HEIGHT as CNN_MODEL_WIDTH,
ANGLE_BIN_SIZE as CNN_ANGLE_BIN_SIZE,
extract_steering_wheel_i... |
#!/usr/bin/python
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import patches
from matplotlib.pyplot import axvline, axhline
from collections import defaultdict
def zplane(z, p, filename=None):
"""Plot the complex z-plane given zeros and poles.
"""
# get a figure/plot
ax = plt.s... |
import pytest
from scipy.stats import lognorm
import numpy as np
import matplotlib.pyplot as plt
from SOSAT import StressState
from SOSAT.constraints import FaultingRegimeConstraint
from SOSAT.constraints import SU
# depth in meters
depth = 1228.3
# density in kg/m^3
avg_overburden_density = 2580.0
# pore pressure gr... |
from PIL import Image
import scipy.ndimage as sc
import scipy.misc as sm
# import numpy as np
a = Image.open('images/lena512.jpg')
b = sc.filters.maximum_filter(a, size=5, footprint=None, output=None, mode='reflect', cval=0.0, origin=0)
b = Image.fromarray(b)
b.show()
|
<gh_stars>1-10
'''
mnist_gan.py
Trains a GAN model on the MNIST database.
'''
import os # path manipulation and OS resources
import time # Time measurement
import yaml # Open configuration file
import math # math operations
import shutil # To copy/move files
import argparse # command line argumments parser
import num... |
from uvicmuse.constants import *
from uvicmuse.helper import *
from uvicmuse.MuseBLE import MuseBLE as muse
from uvicmuse.MuseFinder import MuseFinder
# from .constants import *
# from .helper import *
# from .MuseBLE import MuseBLE as muse
# from .MuseFinder import MuseFinder
from functools import partial
import sock... |
import numpy as np
import time
import cv2
from cv2 import aruco
import pyqtgraph as pg
from scipy.signal import argrelmin
import argparse
def smooth(y, box_pts):
if len(y) < box_pts:
return y[-1]
box = np.ones(box_pts)/box_pts
y_smooth = np.convolve(y, box, mode='valid')
return y_smooth
pars... |
#! /usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
# import funkcí z jiného adresáře
import sys
import os.path
import unittest
import scipy
import numpy as np
import logging
logger = logging.getLogger(__name__)
path_to_script = os.path.dirname(os.path.abspath(__file__))
sys.path.append(o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.