text string |
|---|
<reponame>Cellon88/RedWine-Quality
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 28 20:54:49 2018
@author: yhj
"""
import numpy as np
import pandas as pd
from time import time
import scipy.stats as st
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.model_selection import Randomize... |
'''trying to solve M*v=b'''
from numpy import *
from numpy.testing import dec,assert_,assert_raises,assert_almost_equal,assert_allclose
from scipy.sparse.linalg import LinearOperator
from scipy.linalg import kron,norm,inv
from matplotlib.pyplot import *
import sys,pdb,time
from os import path
sys.path.insert(0,'../')
... |
<filename>src/graphesn/util.py
import statistics
from typing import Union, List, Optional
import torch.linalg
from torch import Tensor
from torch_geometric.typing import Adj, OptTensor
from torch_geometric.utils import to_dense_adj
from torch_sparse import SparseTensor
from graphesn import DynamicData
__all__ = ['gr... |
import torch, h5py
import numpy as np
from scipy.io import loadmat
import torch.nn as nn
import torch.optim as optim
import numpy as np
# import matplotlib
from torch.autograd import Variable
import itertools
from sklearn.preprocessing import normalize
import datetime
import json
import os, sys
import pandas as pd
im... |
<gh_stars>1-10
import mdtraj as md
from scipy.spatial import Delaunay
import numpy as np
from ..geometry import *
from .utils import round_to_nearest
def in_hull(sidechain_coords, backbone_coords ):
"""
Test if points in `p` are in `hull`
`p` should be a `NxK` coordinates of `N` points in `K` dimensions
... |
<reponame>oliverbritton/drg-pom
# neuron_biomarkers.py
# calculation of AP biomarkers from neuronal voltage traces
import sys
import numpy as np
import pandas as pd
from scipy import optimize
from matplotlib import pyplot as plt
from . import davidson_biomarkers as db
from .. import simulation_helpers as sh
from .. i... |
<filename>apps/app_saved_model.py
import os
import pickle
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.figure_factory as ff
import seaborn as sns
import streamlit as st
from scipy.spatial import Delaunay
from sklearn.metrics import (classification_rep... |
<gh_stars>0
"""
This example uses the streamline module to display field lines of a
magnetic dipole (a current loop).
This example requires scipy.
The magnetic field from an arbitrary current loop is calculated from
eqns (1) and (2) in Phys Rev A Vol. 35, N 4, pp. 1535-1546; 1987.
To get a prettier result, we use a ... |
<filename>layerID_train.py<gh_stars>0
"""Process optical images of thin flakes to distinguish layer thicknesses."""
from mpl_toolkits.mplot3d import Axes3D
from scipy.optimize import curve_fit
from read_npz import npz2dict
import os
import time
import cv2
import numpy as np
import numpy.linalg as la
import m... |
import control
import numpy as np
import scipy.linalg
def solve_riccati(A, B, Q, R):
"""
Solves discrete ARE, returns gain matrix K s.t. u = +K*x
Faster implementation than control.dlqr for systems with large n (state_dim)
"""
n = A.shape[0]
m = B.shape[1]
P = np.zeros((n, n))
L = np.l... |
<reponame>lucasmaystre/kickscore
import numba
import numpy as np
import scipy.special
from kickscore.observation.ordinal import _mm_probit_win, _ll_probit_win
from kickscore.observation.utils import *
from math import log, pi, sqrt
from scipy.stats import norm
def test_normpdf():
"""``normpdf`` should work as ex... |
#
# Solved Problems in Geostatistics
#
# ------------------------------------------------
# Script for lesson 5.2
# "Variogram Calculation"
# ------------------------------------------------
import sys
sys.path.append(r'../shared')
from numpy import *
from geo import *
from matplotlib import *
from pyla... |
from numpy import zeros, log2, ceil, arange, absolute, floor, sum
from scipy.fftpack import fft
from scipy.signal import get_window
from agilegeo.util import next_pow2
from numpy import hanning, concatenate
def spectra( data, window_length, dt=1.0, window_type='boxcar',
overlap=0.5, normalize=False ):
... |
<reponame>CarlosPena00/pytorch-unet
import os
import numpy as np
from skimage import io, transform
import scipy.misc
from scipy import ndimage as ndi
import cv2
from torchlib.datasets import imageutl as imutl
from torchlib.datasets import utility as utl
from torchlib import preprocessing as prep
def save_item(
... |
<filename>qmla/shared_functionality/probe_set_generation.py
r"""
Functions to generate sets of probe states to be used for training models.
These functions are set to exploration strategy attributes, which are then called in wrapper functions.
- probe_generation_function:
used for training, assumed to be the pro... |
<reponame>maria-zafar/HSE_FaceRec_tf
import argparse
import sys
import os.path
import os
import math
import datetime, time
import numpy as np
from sklearn import preprocessing, model_selection
from sklearn.decomposition import PCA
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC,... |
import xarray as xr
import sys
import random
from scipy import stats
import glob
from resampling import _resample_iterations_idx
random.seed(0)
def g_kde(y, x):
"""Firstly, kernel density estimation of the probability density function of randomized anomalies.
Secondly, evaluates the estimated pdf on a set of ... |
<filename>SimulationWorld.py
#!/usr/bin/env python
import copy
import time
import sys
import os
import pickle
from functools import partial
import numpy as np
import scipy.spatial
from SimulationRobot import SimulationRobot
from matplotlib import pyplot as plt
import matplotlib.animation as animation
import matplo... |
import requests
import pandas
import scipy.io.wavfile
import scipy.io
import numpy
import json
import os
import IPython.display as ipyd
import IPython.core.formatters as ipyf
import pygments.lexers as pygl
import pygments.util as pygu
import mimetypes
from zipfile import ZipFile
from dateutil.parser import parse
impor... |
<filename>sample.py
import plotly.figure_factory as ff
import plotly.graph_objects as go
import statistics
import random
import pandas as pd
import csv
df = pd.read_csv("data.csv")
data = df["temp"].tolist()
#code to show the plot of raw data
fig = ff.create_distplot([data], ["temp"], show_hist=False)
fig.show()
#... |
from scipy import optimize,arange
from math import *
import sys
import csv
import numpy as np
import matplotlib.pyplot as plt
#matplotlib inline
#vectorised 2P-3T cournot now using basinhopping
#1. get in the data, etc. ... CHECK!
#2. make arbitrary to nxm ... CHECK!
#3. make investment game ... CHECK?
#4. div;expl
... |
<filename>djfractions/forms.py
from __future__ import unicode_literals, division, absolute_import, print_function
import django
if django.VERSION[0] < 3:
from django.utils import six
SIX_OR_STR = six.string_types
else:
SIX_OR_STR = str
from django import forms
from django.core.exceptions import ValidationError
from... |
#FFT
import numpy as np
from numpy.fft import fft
from scipy.integrate import quad
from scipy import stats
def BSM_call_value_INT(S0, K, T, r, sigma):
''' Fourier-based approach (integral).
Parameters
==========
S0: float
initial stock/index level
K: float
strike price
... |
# -*- coding: utf-8 -*-
"""METRICS.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1L78bqwUCI5fD90ZFudHX_ZooObj8rdMz
"""
# Commented out IPython magic to ensure Python compatibility.
import numpy as np
import matplotlib
import matplotlib.pyplot a... |
<gh_stars>0
# 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 writing, software
# distribu... |
'''
Created on April 30, 2016
@author: doronv
'''
# standard python package imports
import numpy as np
import fractions as fr
import math as ma
import re
from pybrain.rl.environments.mazes.tasks.maze4x3 import FourByThreeMaze
import six
# read line from file split it according to separator and convert ... |
import numpy as np
from scipy.sparse import coo_matrix
"""
Mutation matrices for reversible mutations, given spectrum dimension, u and v
"""
# three populations
def calc_FB_3pop(dims, u, v):
d = int(np.prod(dims))
d1, d2, d3 = dims
# arrays for the creation of the sparse (coo) matrices
data1 = []
... |
import numpy as np
import pandas as pd
from scipy import stats
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
# GET DATA
path = '../../data/ParteI/data_sub.xlsx'
dataFrame = pd.read_excel(path, header=2, sheet_name='trials_availabl... |
"""All VarDA ingesting and evaluation helpers"""
import numpy as np
import os
import random
import torch
from scipy.optimize import minimize
from pipeline import ML_utils
from pipeline.AEs import Jacobian
from pipeline.settings import config
from pipeline.fluidity import VtkSave
from pipeline import GetData, SplitDa... |
<reponame>GEOS-ESM/GMAO_Shared
import scipy as sp
import os
from g5lib import dset
import datetime
import dateutil.rrule as rrule
class Ctl(dset.GADset):
def __init__(self):
name='QSCAT'
undef=-9999.
path=os.environ['HOME']+'/verification/stress_mon_clim'
flist=[path+'/qsc... |
<gh_stars>10-100
import time
start = time.perf_counter()
import numpy as np
import scipy.sparse as sparse
import scipy.sparse.linalg as sla
from test_data import discrete_laplacian
stop = time.perf_counter()
print(stop - start)
|
import numpy as np
import scipy.linalg
def elastic_net(A, B, x=None, l1=1, l2=1, lam=1, tol=1e-6, maxiter=10000):
"""Performs elastic net regression by ADMM
minimize ||A*x - B|| + l1*|x| + l2*||x||
Args:
A (ndarray) : m x n matrix
B (ndarray) : m x k matrix
x (ndarray) : optional, n x k... |
from os.path import dirname, realpath, join
import sys
sys.path.append(dirname(dirname(realpath(__file__))))
from tempfile import NamedTemporaryFile
import unittest
import numpy as np
from scipy.misc import imread
from oncodata.dicom_to_png.dicom_to_png import dicom_to_png_dcmtk
test_dir = dirname(realpath(__file__... |
<filename>datasets/convert_to_tfrecords.py
"""
Convert Market-1501 to TFRecords of TF-Example protos.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import os
import sys
from scipy import misc
from datasets.dataset_utils impo... |
<reponame>SakuraSa/TenhouLoggerX<gh_stars>1-10
#!/usr/bin/env python
# coding=utf-8
"""
core.tenhou.log
"""
__author__ = 'Rnd495'
import os
import json
import datetime
import urllib
from core.configs import Configs
configs = Configs.instance()
class Log(object):
"""
Log
"""
def __init__(self, ref... |
''' pca_nonlinear_mappings.py
All of the previous techniques worked best where the features were
linearly separable, either totally separable for the Perceptron,
or fairly separable for SVM, or at least the Principle Components were
separable.
When features are not linearly separable, non line... |
<gh_stars>0
"""
This module provides a prototypical interface that allows the user to
train approximation models based on given training datasets.
"""
import copy
import numpy as np
import pandas
from scipy.stats import randint as sp_randint
from scipy.stats import uniform as sp_uniform
from sklearn import... |
<reponame>Felihong/wikidata-sequence-analysis
import os
import csv
from scipy.spatial.distance import jensenshannon
"""
Calculate the base 2 js-distance value of all adjacent revisions of the given dataset.
Args:
CSV dataset of item id, revision id, ORES probability of A,B, C, D and E.
Returns:
A csv file of ... |
<gh_stars>1-10
import numpy as np
import pytest
import numpy as np
from scipy import stats, linalg, optimize
import autofit.graphical as graph
import autofit.graphical.factor_graphs.transform as transform
def test_cholesky_transform():
d = 10
A = stats.wishart(d, np.eye(d)).rvs()
cho_factor = transform... |
#!/usr/bin/env python3
from __future__ import print_function
import sys
import copy
import rospy
import moveit_msgs.msg
import actionlib
from geometry_msgs.msg import Pose
from bin_picking.msg import MoveRobotAction, MoveRobotGoal
from trajectory_msgs.msg import JointTrajectoryPoint
from scipy.spatial.transform import ... |
import os
import csv
import cv2
from scipy import ndimage
import scipy.misc
import numpy as np
import matplotlib.pyplot as plt
import sklearn
import math
### reading in the driving_log csv file
### and collecting each row detail individually
samples = []
with open('../data/driving_log.csv') as csvfile:
reader = cs... |
<filename>code/utils/experiment.py
from scipy.spatial.distance import cosine
from gensim.models import KeyedVectors
from collections import defaultdict
from sklearn.preprocessing import Imputer
import operator
from nltk import ngrams
from numpy import average
from nltk.tree import ParentedTree
import pandas as pd
# con... |
<filename>wbml/data/kemar.py
import numpy as np
import pandas as pd
import scipy.io
from .data import data_path, resource, dependency
__all__ = ["load"]
def load():
_fetch()
# Compute angles.
azimuths = np.concatenate(
(
np.array([-80, -65, -55]),
np.arange(-45, 45 + 1, ... |
import pandas as pd
import numpy as np
import os
import datetime
from scipy.spatial.distance import cdist
import geopandas as gpd
from shapely.geometry import Point
from sklearn.neighbors import BallTree
import git
from pathlib import Path
repo = git.Repo("./", search_parent_directories=True)
homedir = repo.working_di... |
<reponame>SydneyAstrophotonicInstrumentationLab/openhsi
import os
from tqdm import tqdm
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
import numpy as np
from astropy.io import fits as fitsio
from scipy.signal import find_peaks, savgol_filter
from scipy.optimize import curve_fit
from scipy import... |
<reponame>twankim/lidar_csgm
# !/usr/bin/python
#
# Demonstrates how to project velodyne points to camera imagery. Requires a binary
# velodyne sync file, undistorted image, and assumes that the calibration files are
# in the directory.
#
# To use:
#
# python project_vel_to_cam.py
#
#
# -train: Dates for tra... |
<gh_stars>0
"""
Convert MPII to TFRecords.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from os import makedirs
from os.path import join, exists
from time import time
import numpy as np
import tensorflow.compat.v1 as tf
from .common import convert_... |
import numpy as NP
from astropy.io import fits
from astropy.io import ascii
import scipy.constants as FCNST
from scipy import interpolate
import matplotlib.pyplot as PLT
import matplotlib.colors as PLTC
import matplotlib.cm as CMAP
import matplotlib.animation as MOV
from matplotlib import ticker
from scipy.interpolate... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 24 13:24:43 2020
@author: ssli
Module to calculate the m bias
mcFitFunc:
Shear bias function.
WgQuantile1DFunc:
Calculate the weighted quantile by given probabilities
designed for 1D numpy array.
WgBin2DFunc:
Calculate the ... |
import numpy as np
import scipy as sp
import logging
import unittest
import os.path
import time
import sys
import doctest
from fastlmmhpc.association import epistasis
from fastlmmhpc.association.epistasis import write
import fastlmmhpc.pyplink.plink as plink
import pysnptools.util.pheno as pstpheno
from fastlmmhpc.fea... |
<filename>code/util.py
""" Common util file
"""
import numpy as np
import numpy.random as npr
import os
import skimage.io
import skimage.transform
import time
import pdb
import networkx as nx
import scipy.sparse as sp
from sklearn.metrics import roc_auc_score
from sklearn.metrics import average_precision_score
import... |
<reponame>narahahn/continuous_measurement
"""
Continuous measurement of room impulse responses using a moving microphone.
* point source in a rectanular room
* impulse responses imulated with the image source method
* omnidirectional microphone moving on a circle at a constant speed
* captured signal computed by usin... |
<filename>experimentations/24-climate-spark-analysis-mpi-viz/pvw-spark.py<gh_stars>1-10
from __future__ import print_function
import os
import sys
import time
import gdal
from datetime import datetime
import pyspark
from pyspark import SparkContext
from paraview import simple
import vtk
from paraview.vtk import vtkIO... |
import numpy as np
from scipy.spatial.distance import cdist
from .abstract_kernel import AbstractKernel
class SquaredExponentialKernel(AbstractKernel):
"""Squared Exponential Kernel Class"""
def cov(self, model_X, model_Y=None):
"""Implementation of abstract base class method."""
# Compute the... |
<filename>prepomm/analysis.py
"""
Miscellaneous analysis functions
"""
import itertools
import os.path
import scipy.spatial
import mdtraj as md
from simtk import unit as u
from .tools import _traj_from_file_or_traj
def max_atom_distance(file_or_trajectory):
trajectory = _traj_from_file_or_traj(file_or_trajectory... |
<reponame>jsyony37/csld
#!/usr/bin/env python3
"""
Fit a linear model
A x = b
"""
import numpy as np
from numpy.linalg import norm
import scipy as sp
import scipy.sparse
try:
from cssolve.bregman_func import bregman_func
except ImportError:
print("Failed to import bregman_func")
pass
try:
from bc... |
<reponame>LouisFaure/scFates
from typing import Optional, Union
from typing_extensions import Literal
from anndata import AnnData
import numpy as np
import pandas as pd
from pandas import DataFrame
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import minimum_spanning_tree
from scipy.sparse.csgraph impor... |
<filename>dataset.py
from config import *
from scipy.io import loadmat
from keras.utils import np_utils
import pickle
def load(file_path=dataset_path):
"""
load dataset from a .mat file and save mapping to ASCII into a file
:param
file_path: path to the .mat file (default value specified in config... |
<filename>taskRankGraphs.py
"""
Creates graphs for task re-ranking metrics from an ECResults checkpoint.
Requires metrics to be available in a recognitionTaskMetrics dict: you can specify this via --storeTaskMetrics.
Or you can attempt to back add them using the --addTaskMetrics function.
Usage: Example script is in t... |
<gh_stars>0
#! /usr/bin/env python
from __future__ import print_function, division
__author__ = '<NAME>'
from depexoTools import models, AeRes
from depexoTools.source_finder import FWHM2CC
from depexoTools.wcs_helpers import WCSHelper
import numpy as np
from scipy.ndimage import gaussian_filter
from astropy.wcs impor... |
<gh_stars>0
"""
协变基矢量,是不是某一点上,曲线坐标系到笛卡尔坐标系的变换矩阵?
如果知道某个矢量的极坐标读数,用这个变换矩阵可以找到笛卡尔读数?
需要知道极坐标的参数方程。即笛卡尔x,y如何用r, theta表示。 然后对两个方程求r和theta的偏导数。
三维情况差不多。可以用笛卡尔和球面坐标来表示。
二维就用曲线来表示。一样可以讨论 christoffel symbol
如何设置坐标刻度?
"""
import matplotlib.pyplot as plt
from matplotlib.axes import Axes
from sympy import *
from sympy.diffgeo... |
<filename>code/Practica2.py
#!/usr/bin/env python
# coding: utf-8
# # Pràctica 2: Neteja i anàlisis de les dades
#
# El següent notebook esta orientat a resoldre la pràctica 2 de l'assignatura *M2.951 - Tipologia i cicle de vida de les dades* del màster en Data Science de la UOC.
#
# ### Nota important
#
# Per pode... |
import numpy as np
from numpy.lib.npyio import save
import os
import sys
from scipy.interpolate import griddata
from scipy.ndimage.filters import gaussian_filter
from scipy.ndimage.filters import rank_filter
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib import colors
savedir = "/scratch/ws//... |
<reponame>JouniVatanen/NLP-and-Deep-Learning
# https://udemy.com/recommender-systems
# https://deeplearningcourses.com/recommender-systems
from __future__ import print_function, division
from builtins import range
# Note: you may need to update your version of future
# sudo pip install -U future
import numpy as np
imp... |
<filename>examples/metrica.py
# -*- coding: utf-8 -*-
"""
* Find packing for real-time metrica data
* Owner: <NAME>
* Version: V1.0
* Last Updated: May-14-2020
"""
import os
import sys
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial import distance
from collections import de... |
<reponame>nicolas-chaulet/bempp
# Copyright (C) 2011-2012 by the BEM++ Authors
#
# 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
#... |
<gh_stars>0
import pvlib
import numpy as np
import pandas as pd
# import pytz
# from collections import OrderedDict
# from functools import partial
import scipy
import datetime
import os
import warnings
import time
from pvlib.singlediode import _lambertw_i_from_v, _lambertw_v_from_i
from pvlib.pvsystem import calcpara... |
<gh_stars>1-10
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
added the explore relations part after 735561
"""
import os
import sys
import gc
sys.path.insert(1, os.getcwd()+'/..')
sys.path.insert(1, os.getcwd()+'/../keras-resnet/')
# sys.path.insert(1, '/home/labs/ahissarlab/arivkind/imagewalker')
# sys.path.in... |
import random
import tensorflow as tf
import numpy as np
import time
from datetime import timedelta
from PIL import Image
import scipy.io
import os
import argparse
import math
import sys
sys.path.append('libs')
sys.path.append('tools')
from configs import FLAGS
from data_loader import load_image, load_label
import ada... |
<filename>mem_leak_detection/algo_based_on_backward_movement.py
import warnings # `do not disturbe` mode
import pandas as pd
import numpy as np
from sklearn.preprocessing import PolynomialFeatures
from sklearn import datasets, linear_model
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.model_sel... |
<reponame>kimjaed/simpeg
from __future__ import print_function
import unittest
import numpy as np
import scipy.sparse as sp
from SimPEG import Mesh
from SimPEG import Utils
from SimPEG import SolverLU
from SimPEG import EM
from scipy.constants import mu_0
# import matplotlib
# matplotlib.use('Agg')
import matplotlib.... |
#!/usr/bin/python
########################################################################
### Elhadad lab member fair-share code
########################################################################
import platform
import sys
# If in ibnezra
if platform.node() == 'ibnezra':
sys.path.append('/nlp/anaconda3')
... |
<reponame>rhiannonlynne/powerspectrum
# Run a test to evaluate parameters of 2d gaussian through FFT/PSD/ACovF.
# This is useful, because a Gaussian should be analytically predictable through each of these transformations.
# Summary:
# The FFT of a gaussian is a Gaussian, with sigma_fft (in frequency space) = 1/(2*p... |
from typing import Optional
import logging
import numpy as np
from scipy import optimize as opt
logger = logging.getLogger(__name__)
class Optimizer:
def __init__(self, *args):
pass
def optimize(self, objective_function):
pass |
import array
import numpy as np
from collections import defaultdict, Counter
from scipy.sparse import csr_matrix
from nltk.tokenize import sent_tokenize
from nltk import word_tokenize
from .storage import DictTokenStats
from .utils import aggragate_by_cnt, get_entropy
class TokenzierMixin(object):
"""Common utitl... |
<reponame>pradyunkumar/Letoplay<filename>test.py<gh_stars>1-10
import sounddevice as sd
from scipy.io.wavfile import write
from visualizer import make_plots
from time import sleep
SAMPLE_RATE = 44100
CHANNELS = 1
MIC_ID = 6 # Device ID of Mic used
sd.default.device = 6
fname = input("File name: ") + '.wav'
fs = 441... |
from scipy.io.wavfile import read
import os
import sys
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["font.family"] = "Times New Roman"
import pysptk
try:
from .peakdetect import peakdetect
from .GCI import SE_VQ_varF0, IAIF, get_vq_params
except:
from peakdetect import peakdetect
fr... |
<gh_stars>1-10
import numpy as np
import matplotlib.pyplot as plt
import itertools
import warnings
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
from scipy.integrate import solve_ivp
import scipy.integrate
from sklearn.metrics import mean_squared_error
from s... |
import matplotlib.pyplot as plots
import numpy as np
from scipy.stats import norm
def plot_function(D,input_node, mu, sigma, batch_size, sess):
figure,axis=plots.subplots(1)
xaxis=np.linspace(-6,6,1000)
axis.plot(xaxis, norm.pdf(xaxis,loc=mu,scale=sigma), label='p_distribution')
r=1000
... |
"""Implementation of :class:`RationalField` class. """
from sympy.external.gmpy import MPQ
from sympy.polys.domains.groundtypes import SymPyRational
from sympy.polys.domains.characteristiczero import CharacteristicZero
from sympy.polys.domains.field import Field
from sympy.polys.domains.simpledomain import... |
<filename>openmmtools/tests/test_mixing.py
"""
Test Cython and weave mixing code.
"""
import copy
import numpy as np
import scipy.stats as stats
def mix_replicas(n_swaps=100, n_states=16, u_kl=None, nswap_attempts=None):
"""
Utility function to generate replicas and call the mixing function a certain numbe... |
from __future__ import annotations
from datetime import date, datetime, time, timezone
from unittest import TestCase
from math import ceil
from statistics import mean
from jsonclasses_pymongo.connection import Connection
from tests.classes.simple_animal import SimpleAnimal
from tests.classes.simple_datetime import Simp... |
# -- coding: utf-8 --
"""
This module contains tools for rasterizing vector data.
"""
import numpy
import pandas
import rasterio.features
from rasterio.enums import MergeAlg
from scipy.interpolate import Rbf, griddata
from shapely.geometry import mapping
from geocube.logger import get_logger
def _remove_missing_data... |
'''
Module for reading Cosmo Skymed HDF5 imagery. This is more or less
a line-for-line port of the reader from NGA's MATLAB SAR Toolbox.
'''
# SarPy imports
from .sicd import MetaNode
from . import Reader as ReaderSuper # Reader superclass
from . import sicd
from ...geometry import geocoords as gc
from ...geometry im... |
#!/usr/bin/env python
# coding: utf-8
# # Regression Project: The California Housing Prices Data Set
# ### Context
# This is the dataset used in the second chapter of <NAME>'s recent book *'Hands-On Machine learning with Scikit-Learn and TensorFlow'. (O'Reilly)*
#
# It serves as an excellent introduction to implemen... |
<reponame>1Konny/idgan
import os
import sys
from PIL import Image
from pathlib import Path
from torchvision import transforms
def preprocess_celeba(path):
crop = transforms.CenterCrop((160, 160))
resample = Image.LANCZOS
img = Image.open(path)
img = crop(img)
img_256_path = celeba_256_dir / path.... |
<reponame>chulbioinfo/CSAVanalysis
# CSCV program to detect convergent single codon variants
# Version 1.0 (14.Nov.2020)
# written by <NAME> (e-mail: <EMAIL>)
# This code was developed and conducted in Python 3.7.1 (v3.7.1:260ec2c36a, Oct 20 2018, 14:57:15) [MSC v.1915 64 bit (AMD64)]
# OS for development and analysis:... |
#!/usr/bin/python
import argparse
import time
from scipy.misc import toimage
from sampleEnvMapShDataset import *
def test(dataPath, imgDir, imgPath, shOrder, linearCS):
dims = [1, 128, 256]
img = EnvMapShDataset.loadImg(imgPath, dims[1:3], linearCS)
toimage(img[0]).show()
rseed = 0 # int(time.time()... |
from __future__ import division, print_function
import numpy as np
import sys
from scipy.constants import c, pi
from joblib import Parallel, delayed
from mpi4py.futures import MPIPoolExecutor
from mpi4py import MPI
from scipy.fftpack import fftshift, fft
import os
import time as timeit
os.system('export FONTCONFIG_PATH... |
<reponame>alknemeyer/physical_education
import sympy as sp
from pyomo.environ import (
ConcreteModel, Set, Var, Param, Constraint,
)
from dataclasses import dataclass
from typing import Callable, Dict, List, Any, Optional, TYPE_CHECKING, Tuple, Union
from . import utils
if TYPE_CHECKING:
from .variable_list im... |
from __future__ import print_function, absolute_import, division
import unittest
import bosonic as b
import numpy as np
from scipy.special import factorial, binom
MAX_PHOTONS = 5
MAX_MODES = 10
class TestMath(unittest.TestCase):
def test_factorial(self):
"""Test the custom factorial implementation up t... |
from cmath import rect
from numpy import real, vectorize, deg2rad, maximum, sqrt, empty, zeros, nan
from pandapower import F_BUS, T_BUS
from pandapower.pf.pfsoln_numba import calc_branch_flows_batch
from pandapower.pypower.idx_bus import BASE_KV
from pandapower.results_branch import _get_trafo3w_lookups
from pandapow... |
#%%
import pandas as pd
import numpy as np
from sklearn.model_selection import KFold
import os
from sklearn.feature_extraction.text import TfidfVectorizer
from scipy.sparse import hstack, save_npz
import sys
# import argparse
# parser = argparse.ArgumentParser(description='Split data for a data leverage campaign')
# p... |
""" Classes for Population and Individual objects. """
import numpy as np
from scipy.stats import norm
from collections.abc import MutableSequence
from .settings import DOMINANCE, RECOMBINATION_RATE, LOCUS_NUM, FITNESS_FUNCTION
class Population(MutableSequence):
""" Creates instance of Population object. individu... |
import scipy
import numpy as np
import pandas as pd
from Modeling.Pytorch.utilis_rnn import *
from Controllers.template_controller import template_controller
from CartPole.state_utilities import create_cartpole_state, cartpole_state_varname_to_index
import yaml, os
config = yaml.load(open(os.path.join('SI_Toolkit_Ap... |
<gh_stars>100-1000
# some code to create a nice animation within the notebook.
#this takes a couple of minutes on my machine so I commented it out
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from mpl_toolkits.mplot3d import Axes3D
from functools import partial
from ... |
<gh_stars>0
# encoding: utf-8
from __future__ import division, print_function
from scipy.linalg import eigh
from scipy.optimize import minimize
try:
import autograd.numpy as np
from autograd import grad
except ImportError:
import numpy as np
from warnings import warn
warn("Package autograd not fo... |
<reponame>marcosgrala/serieCoef
# encoding: utf-8
# encoding: iso-8859-1
# encoding: win-1252
import numpy as np
import matplotlib.pyplot as plt
from scipy import integrate
import scipy.fftpack
import pandas as pd
import glob
from scipy import signal
import time
def normD(a):
norm = 0
for i in range(3):
... |
#!/usr/bin/env python
import numpy as np
import sys
from sklearn.datasets import load_svmlight_file
from sklearn.metrics import accuracy_score
import scipy.sparse
import scipy.stats
from uda_common import zero_pivot_columns, zero_nonpivot_columns, read_pivots, evaluate_and_print_scores, align_test_X_train, get_f1, find... |
import pytest
import itertools
from sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor
import numpy as np
import scipy.spatial.distance as sc
import utils.distances as sk
from utils.evaluation import mse, accuracy
from utils.distances import euclidean
from supervised.knn import KNN_Classifier, KNN_Reg... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.