text string |
|---|
<reponame>AlbertVeli/AdventOfCode
#!/usr/bin/env python3
import sys
pubkeys = list(map(int, open(sys.argv[1]).read().splitlines()))
n = 20201227
# This is actually the discrete logarithm problem
# 7**x mod n
def crack(pubkey):
loops = 0
val = 1
while val != pubkey:
val = (val * 7) % n
lo... |
<gh_stars>0
"""
This code is used for creating new netCDF files for seasonal (JJA) mean of COD, CC and TT, for each of the CMIP5 and CMIP6 models.
"""
import matplotlib.pyplot as plt
import xarray as xr
import numpy as np
import seaborn as sns
import pandas as pd
import scipy as sc
# ===== FUNCTIONS ====
#import nesec... |
#Ref: <NAME>
"""
Spyder Editor
scipy.signal.convolve2d - https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.convolve2d.html
scipy.ndimage.filters.convolve
cv2.filter2D - https://docs.opencv.org/2.4/modules/imgproc/doc/filtering.html?highlight=filter2d#filter2d
"""
import cv2
import numpy as np
from sc... |
<filename>genepi/step5_crossGeneEpistasis_Lasso.py
# -*- coding: utf-8 -*-
"""
Created on Feb 2018
@author: Chester (<NAME>)
"""
""""""""""""""""""""""""""""""
# import libraries
""""""""""""""""""""""""""""""
import os
import warnings
warnings.filterwarnings('ignore')
# ignore all warnings
warnings.simplefilter("ign... |
<reponame>RamonPujol/OTSun<gh_stars>1-10
"""
Module otsun.source that implements rays and its sources
"""
import itertools
import Part
import numpy as np
from FreeCAD import Base
from .math import pick_random_from_cdf, myrandom, tabulated_function, two_orthogonal_vectors, area_of_triangle, random_point_of_triangle
f... |
<filename>Vol1B/PageRank/spec.py
import numpy as np
import scipy.sparse as spar
import scipy.linalg as la
from scipy.sparse import linalg as sla
def to_matrix(filename,n):
'''
Return the nxn adjacency matrix described by datafile.
INPUTS:
datafile (.txt file): A .txt file describing a directed graph. L... |
<gh_stars>0
from sympy import Matrix, pprint
M = Matrix( [
[ 1, 0, 1, 0, 0, 0, 0, 0, 3 ],
[ 0, 1, 0, 1, 0, 0, 0, 0, 4 ],
[ 2, 1, 0, 0, 1, 0, 0, 0, 7 ],
[ 1, 1, 0, 0, 0, 1, 0, 0, 5 ],
[ -1, 0, 0, 0, 0, 0, 1, 0, 0 ],
[ 0, -1, 0, 0, 0, 0, 0, 1, 0 ],
[-3000, -2000, 0, 0, 0, 0, 0, 0, 0 ] ] )
pprint( M )
#... |
#Εισαγωγή των κατάλληλων βιβλιοθηκών
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import seaborn as sns
from IPython.display import Image
from os import system
import os
from statistics import mean
from mlxtend.plotting import plot_confusion_matrix
fro... |
<reponame>1uc/morinth<gh_stars>0
# SPDX-License-Identifier: MIT
# Copyright (c) 2021 ETH Zurich, <NAME>
import numpy as np
import scipy.sparse.linalg as sparse_linalg
class Newton(object):
def __init__(self, boundary_mask):
self.mask = boundary_mask.reshape(-1)
def __call__(self, F, dF, x0):
... |
<reponame>seenu-andi-rajendran/plagcomps
import hmm
from kmedians import KMedians
import outlier_detection
import classify
#from plagcomps.intrinsic import outlier_detection
from numpy import array, matrix, random
from scipy.cluster.vq import kmeans2, whiten
from scipy.spatial.distance import pdist
from scipy.cluster.... |
<filename>v2.0/chips_fits.py<gh_stars>1-10
"""chips_fits.py: Module is used to implement edge detection tecqniues using thresholding"""
__author__ = "<NAME>."
__copyright__ = ""
__credits__ = []
__license__ = "MIT"
__version__ = "1.0."
__maintainer__ = "<NAME>."
__email__ = "<EMAIL>"
__status__ = "Research"
import ma... |
<filename>sample_program_05_04_bayesian_optimization_multi_sample.py
# -*- coding: utf-8 -*-
"""
@author: <NAME>
"""
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from scipy.stats import norm
from sklearn.model_selection import KFold, cross_val_predict
from sklearn.gaussian_process i... |
import os
dirname = os.path.dirname(__file__)
import sys
sys.path.append(os.path.join(dirname,'/Users/rridden/Documents/work/code/source_synphot/'))
import source_synphot.passband as passband
import source_synphot.io as io
import source_synphot.source
import astropy.table as at
from collections import OrderedDict
impor... |
<reponame>hugomolinares/sympsi
"""
Utitility functions for working with operator transformations in
sympsi.
"""
__all__ = [
'show_first_few_terms',
'html_table',
'exchange_integral_order',
'pull_outwards',
'push_inwards',
'integral_pow_expand',
'sum_pow_expand',
'replace_dirac_delta',
... |
<reponame>viathor/OpenFermion-Cirq<filename>openfermioncirq/variational/ansatzes/low_rank_test.py<gh_stars>1-10
# 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... |
<reponame>Na2CuCl4/latex2sympy
from .context import assert_equal
import pytest
from sympy import exp, sin, Symbol, E
x = Symbol('x', real=True)
y = Symbol('y', real=True)
def test_exp_letter():
assert_equal("e", E)
assert_equal("e", exp(1))
def test_exp_func():
assert_equal("\\exp(3)", exp(3))
def te... |
<filename>ifa_smeargle/core/mathematics.py
import numpy as np
import numpy.ma as np_ma
import astropy as ap
import astropy.modeling as ap_mod
import sympy as sy
import ifa_smeargle.core as core
def ifas_masked_mean(array, axis=None):
""" This returns the true mean of the data. It only counts
valid data.
... |
<gh_stars>1-10
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.4'
# jupytext_version: 1.1.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
... |
<reponame>rimmartin/cctbx_project<gh_stars>1-10
from __future__ import absolute_import, division, print_function
# LIBTBX_SET_DISPATCHER_NAME sphinx.build
import sys
try:
# try importing scipy.linalg before any cctbx modules, otherwise we
# sometimes get a segmentation fault/core dump if it is imported after.
# ... |
<gh_stars>0
from sklearn.base import BaseEstimator, TransformerMixin
import pandas as pd # pd.isnull
import scipy.sparse
from grouplabelencode import grouplabelencode
from .onehotencode import onehotencode
from .mapping_to_colname import mapping_to_colname
from collections import Counter
import numpy as np
class On... |
<gh_stars>0
# %%
import pandas as pd
import numpy as np
import gzip
import sklearn.metrics
import pandas as pd
import minisom as som
from sklearn import datasets, preprocessing
import matplotlib.pyplot as plt
import seaborn as sbs
from matplotlib.collections import LineCollection
class SOMToolBox_Parse:
def __i... |
# CSC 321, Assignment 4
#
# This is the main training file for the vanilla GAN part of the assignment.
#
# Usage:
# ======
# To train with the default hyperparamters (saves results to checkpoints_vanilla/ and samples_vanilla/):
# python vanilla_gan.py
import os
import pdb
import pickle
import argparse
import... |
<gh_stars>0
#! usr/bin/env python
# -*- coding: UTF-8 -*-
import simpy
import scipy.stats as stats
import pandas as pd
import numpy as np
import time
import pickle
import sys
from esp_product_revenue import ESP_revenue_predictions
from ESP_Markov_Model_Client_Lifetime import ESP_Joint_Product_Probabilities, \
ESP_M... |
<gh_stars>1-10
import pysam
from multiprocessing import Pool
from collections import Counter
import statistics
import os
import re
import logging
def add_features_parser(subparsers):
parser = subparsers.add_parser('features', help='create features for bam files')
parser.add_argument('--file', '-f', required=T... |
# Copyright 2019 Xanadu Quantum Technologies Inc.
# 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 agre... |
from scipy import signal
from scipy.signal import find_peaks
import matplotlib.pyplot as plt
import numpy as np
from scipy.fftpack import dct, idct
if __name__ == "__main__":
t = np.linspace(0, 1, 500)
tri = signal.sawtooth(2 * np.pi * 5 * t, 0.5)
hs = dct(tri, type=2)
fs = (0.5 + np.arange(len(hs))... |
<filename>tests/test_emu_cal/test_cal_directbayes.py
import numpy as np
import scipy.stats as sps
import pytest
from contextlib import contextmanager
from surmise.emulation import emulator
from surmise.calibration import calibrator
##############################################
# Simple scenarios ... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 08 19:03:20 2013
Author: <NAME>
"""
if __name__ == '__main__':
import numpy as np
from statsmodels.regression.linear_model import OLS
#from statsmodels.nonparametric.api import KernelReg
import statsmodels.sandbox.nonparametric.kernel_extras as smke
... |
import numpy as np
import os
import random
import shutil
from statistics import mean
from tensorflow.python.keras.backend import dtype
from game_models.base_game_model import BaseGameModel
from convolutional_neural_network import ConvolutionalNeuralNetwork
import torch
import torch.nn as nn
import torch.optim as opti... |
<reponame>Erotemic/misc
"""
Recently, I was put into a circumstance where I needed to come up with and
remember a password I would be required to manually type in. Awful, I know.
My first thought was a classic "correct horse battery staple" style password
introduced by <NAME> in 2011 [1]_. My second thought was: is t... |
## April 2019 xyz
import torch, math
import numpy as np
def limit_period(val, offset, period):
'''
[0, pi]: offset=0, period=pi
[-pi/2, pi/2]: offset=0.5, period=pi
[-pi, 0]: offset=1, period=pi
'''
return val - torch.floor(val / period + offset) * period
def angle_dif(val0, val1, aim_scope_id):
... |
from scipy.spatial import distance
from sklearn.preprocessing import normalize
import numpy as np
class Metric():
def __init__(self, embed_dim, mode, **kwargs):
self.mode = mode
self.embed_dim = embed_dim
self.requires = ['features']
self.name = 'rho_spectrum@'+str(mode)
... |
<reponame>edawson/parliament2
"""
Testing for the gradient boosting module (sklearn.ensemble.gradient_boosting).
"""
import numpy as np
import warnings
from sklearn.utils.testing import assert_equal
from sklearn.utils.testing import assert_array_equal
from sklearn.utils.testing import assert_array_almost_equal
from s... |
<gh_stars>10-100
"""
DecMeg2014 2nd place submission code.
<EMAIL>, Jul 29th, 2014
The model is a hierarchical combination of logistic regression and
random forest. The first layer consists of a collection of 337 logistic
regression classifiers, each using data either from a single sensor
(31 fe... |
import copy
import gc
import numpy
from numpy.linalg import LinAlgError
import joblib
import pandas
import psutil
import pygmo
from scipy.optimize import minimize
from scipy.optimize import differential_evolution
import time
from typing import Dict, List, Tuple
import warnings
from .constants import Cons... |
from itertools import compress
import pandas as pd
import numpy as np
from abc import ABCMeta, abstractmethod
from surveyhelper.scale import QuestionScale, LikertScale, NominalScale, OrdinalScale
from scipy.stats import ttest_ind, f_oneway, chisquare
class MatrixQuestion:
__metaclass__ = ABCMeta
def __init__(... |
import itertools
import numpy as np
import scipy as sp
from scipy import signal
from pyitab.simulation.autoregressive import *
from pyitab.simulation.connectivity import *
from pyitab.analysis.states.metrics import *
from pyitab.analysis.states.subsamplers import *
from pyitab.analysis.states.base import *
from sklearn... |
<reponame>LUMII-Syslab/QuerySAT
from pathlib import Path
from statistics import median_high, mean
import tensorflow as tf
from metrics.base import Metric
class SATAccuracy(Metric):
def __init__(self) -> None:
self.mean_acc = tf.metrics.Mean()
self.mean_total_acc = tf.metrics.Mean()
def upd... |
import scipy.spatial as spatial
import numpy as np
import networkx as nx
import point
import math
def grid_graph(N, k):
data = np.zeros((N, 2))
ps = np.linspace(0, 1, int(math.sqrt(N)))
counter = 0
for x in ps:
for y in ps:
data[counter][0] = x
data[counter][1] = y
... |
<gh_stars>10-100
#! /usr/bin/env python3
"""DAC Tests
The tester is a Digilent Analog Discovery 2.
The DUT_DAC pin must be connected to a filter as it is a digital PWM out.
This can be done with a low pass filter.
Pinout:
PHiLIP Digilent Analog Discovery 2
DUT_DAC ------------ 1+
"""
from time import sleep
impor... |
<filename>experiments/ConfusionMatrix.py<gh_stars>10-100
import math
import statistics
from collections import OrderedDict
class ConfusionMatrix:
"""
Implementation of confusion matrix for evaluating learning algorithms; computes macro F-measure,
accuracy, confidence intervals
"""
def __init__(se... |
import os
import numpy as np
from scipy.io import wavfile
# Read the wave file, and check its length (number of samples)
def load_data(class_name, file_name, signal_samples, data_root, signal_sr, check_length=True):
file_path = os.path.join(data_root, 'dataset', class_name, file_name)
if class_name == 'backgr... |
#######################################################################################
# This is a utility library for common methods
# Author: <NAME>
# email: <EMAIL>
#######################################################################################
import numpy as np
import matplotlib.pyplot as plt
from scipy... |
import operator
import re
import sys
import sympy
import pyparsing
from chempy import Substance
from chempy import balance_stoichiometry
from chemsolve.element import Element
from chemsolve.element import SpecialElement
from chemsolve.compound import Compound
from chemsolve.compound import FormulaCompound
from chems... |
# <NAME>
# Fuzzy C Means - Algorithm validation and performance analysis
# TP 1 - Sistemas Nebulosos
import matplotlib.pyplot as plt
import numpy as np
from scipy import io
from fuzzy_c_means import fuzzy_c_means
def main():
k = 4
samples = np.asarray(io.loadmat("fcm_dataset.mat")["x"])
avg_iterations = 0... |
import numbers
from enum import Enum
from functools import partial
import numpy as np
from scipy.spatial.transform import Rotation as R
from scipy.spatial.transform import Slerp
from .utils import keys_to_list, nested_get, nested_set, quaternion2euler
def default(a, b, fraction):
"""Default interpolation for th... |
#from .pygsm import GlobalSkyModel
import numpy as np
from scipy.interpolate import interp1d, pchip
import h5py
from astropy import units
import healpy as hp
import ephem
from datetime import datetime
from pkg_resources import resource_filename
GSM2016_FILEPATH = resource_filename("pygsm", "gsm2016_components.h5")
k... |
"""This test module verifies the QFactor instantiater."""
from __future__ import annotations
import numpy as np
from scipy.stats import unitary_group
from bqskit.ir.circuit import Circuit
from bqskit.ir.gates.parameterized import RXGate
from bqskit.ir.gates.parameterized.unitary import VariableUnitaryGate
from bqskit... |
import statistics as stat
import os
def array_to_string(array):
res = ""
for a in array:
res += str(a) + ";"
return res[:-1] + "\n"
for i in range(10):
for j in range(100):
none_id = ""
vision_id = ""
a_id = ""
fr_id = ""
lu_id = ""
de_id = ""
be_id = ""
other_id = ""
nb_tax_payer = -1
di... |
# Licensed under an MIT open source license - see LICENSE
import numpy as np
from scipy.stats import nanmean, nanmedian, nanstd
from astropy.table import Table
from matplotlib.ticker import MaxNLocator
import matplotlib.pyplot as p
try:
import aplpy
except ImportError:
print("Optional package aplpy could not be i... |
<gh_stars>1-10
"""
pol_metrics.py
Scripts to measure 4 polarization metrics (as defined by DiMaggio) of a
distribution of preferences.
"""
import csv
import os.path
import numpy as np
import pandas as pd
from scipy.stats import moment, kurtosis, uniform, laplace
from scipy.misc import comb, factorialk
from sklearn i... |
<gh_stars>1-10
import time
import datetime
import statistics as stats
import feedparser as fp
from urllib import error
def read_rss(url: str) -> fp.util.FeedParserDict:
"""
Read the RSS feed from the given url.
Parameters
----------
url : str
Returns
-------
fp.util.FeedParserDict
... |
<filename>src/util_3d.py<gh_stars>0
import os
import json
import cv2
import yaml
import pyquaternion
import math
import numpy as np
from scipy.optimize import minimize
import torch
from torch import nn
from twodtobev import undistort_contours, IPM_contours, cam_intrinsic, cam_extrinsic, compute_box_bev
IOU_THRESHOLD=0... |
# Use grid search to optimise the hyper-parameters for 6 ML Models
import warnings
warnings.filterwarnings('ignore') # Ignore warnings
import pandas as pd
import numpy as np
import pickle
import math
import time
import sys
import os
import itertools
from collections import Counter
from pathlib import Path
from sklearn.... |
from scipy.stats import kurtosis, skew
from torch.utils.data import Dataset
from sklearn.datasets import make_spd_matrix
from sklearn.covariance import empirical_covariance
from sklearn.metrics import mean_squared_error
from torch.utils.data import DataLoader
import numpy as np
import itertools
import torch.nn.function... |
# Author: <NAME>
from ggp.utils import *
from ggp.kernels import SparseGraphPolynomial
from ggp.model import GraphSVGP
from scipy.cluster.vq import kmeans2
import numpy as np
import os, time, pickle, argparse
class SSLExperiment(object):
def __init__(self, data_name, random_seed):
self.data_name = data_na... |
<filename>Final Model/create_scenarios.py
# -*- coding: utf-8 -*-
"""
Created on Thur Mar 24 18:01:48 2022
@author: <NAME>
"""
# Standard Library imports
import argparse
import gzip
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import netCDF4
import numpy as np
import os
import pand... |
<filename>fit_predictors.py
#!/usr/bin/env python
import pickle
import sys
import matplotlib.pyplot as plt
import yaml
from scipy.stats import stats
from external.nas_parser import *
from nas.nas_utils.general_purpose import extract_structure_param_list
from nas.nas_utils.predictor import construct_predictors, \
... |
import numpy as np
import pandas as pd
import bottleneck
from scipy import sparse
import gc
from .utils import *
def MetaNeighbor(
adata,
study_col,
ct_col,
genesets,
node_degree_normalization=True,
save_uns=True,
fast_version=False,
fast_hi_mem=False,
mn_key="MetaNeighbor",
):
... |
<reponame>BongumusaSizwe/dqn
from cnnmodel import CNN
import gym
import numpy as np
from scipy import stats
import torch
import torchvision
import torch.nn as nn
from torch.utils.data import DataLoader, Dataset
import torchvision.transforms as transforms
import torch.optim as optim
import os
import json
from argparse ... |
<gh_stars>1000+
from __future__ import division, print_function, absolute_import
import warnings
import numpy as np
from numpy.testing import assert_raises, assert_approx_equal, \
assert_, run_module_suite, TestCase,\
assert_allclose, assert_array_equal,\
... |
import math
import re
import statistics
import time
import typing as t
from collections import deque
from pathlib import Path
from pylox.callable import LoxCallable, LoxInstance
from pylox.containers.array import LoxArray
from pylox.environment import Environment
from pylox.protocols.interpreter import SourceInterpret... |
import pandas as pd
import math
import numpy as np
from scipy.optimize import curve_fit
import setting
class Metal():
def __init__(self, name, X_P, isotopes, mass, radius, surface_energy, E_over_k, R_e, w, para):
assert len(para) == 3
assert type(X_P) == np.ndarray
self.name = name
... |
<filename>ExamPrep/Shit Comp/Python Code/SciCompRevision(DifferentialEquations)/Integration/Scipy_integrate_quad_Tutorial.py<gh_stars>0
#Imports
from scipy.integrate import quad as sciquad
#Constants
LowerLimit = 0
UpperLimit = 10
#Defining Function
def function(x):
return (x**2)
#Using Scipy.Integrate.Quad inputs ... |
import torch
import torchvision
import torchvision.transforms as transforms
import torchvision.models as models
import matplotlib.pyplot as plt
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import scipy.io as sio
import copy
import pandas as pd
import os
from PIL i... |
<reponame>Di-Weng/emotion_classification_blstm
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/7/1 0:32
# @Author : MengnanChen
# @Site :
# @File : audioFeatureExtraction.py
# @Software: PyCharm Community Edition
import numpy
from scipy.fftpack.basic import _fftpack
from scipy.fftpack.basic imp... |
"""!
@brief Log audio files from a given batch
@author <NAME> {<EMAIL>}
@copyright University of Illinois at Urbana-Champaign
"""
import os
import numpy as np
from scipy.io.wavfile import write as wavwrite
class AudioLogger(object):
def __init__(self, dirpath, fs, bs, n_sources):
"""
:param dirp... |
<filename>power_planner/graphs/weighted_reduced_graph.py
# from constraints import ConstraintUtils
from power_planner.utils.utils import get_donut_vals
from .weighted_graph import WeightedGraph
import numpy as np
from graph_tool.all import Graph, shortest_path
import time
from scipy import ndimage as ndi
import matplo... |
<reponame>Goubeast/Focal-WNet<gh_stars>0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#######################################################################################
# The MIT License
# Copyright (c) 2014 <NAME>, University of Bonn <<EMAIL>>
# Copyright (c) 2013 <NAME>, University of Bonn <<EMAIL... |
import time
from typing import List, Dict
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import stats
import board_reader
import expirement_gui.one_dim_control as one_dim
import expirement_gui.tk_plots as tk_plots
import feature_extraction
channels = {"o1": 1, "c3": 2, "fp2": 3, "fp1": 4, "c4": 5, ... |
import networkx as nx
import numpy as np
import pandas as pd
import itertools as it
import functools as ft
import math
import operator as op
from scipy import misc
import matplotlib.pyplot as pyplot
from scipy.special import gamma as gammaFunction
def generateNCRPTreesAndRemoveRepeatChildNodeAndMapPriorsToNewTrees(gam... |
<reponame>Harsha-Musunuri/SpeechSplit
import os
import sys
import pickle
import numpy as np
import soundfile as sf
from scipy import signal
from librosa.filters import mel
from numpy.random import RandomState
from pysptk import sptk
from utils import butter_highpass
from utils import speaker_normalization
from utils im... |
import argparse
import sys
import os
import glob
import numpy as np
import copy
from scipy.ndimage.filters import gaussian_filter
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from imapper.logic.scenelet import Scenelet
from imapper.logic.skeleton import Skeleton
from imapper.logic.joints im... |
#
# Copyright (c) 2019, NVIDIA CORPORATION.
#
# 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 ... |
<gh_stars>0
# Calculate a necessary condition where a 3d smooth curve is on a 2d cylinder.
# Please run it in Ipython, using "ipython 2d_cylinder_in_3d.py".
from sympy import *
s = Symbol('s')
for v1 in ('r', 't', 'n', 'b'):
for v2 in ('r', 't', 'n', 'b'):
exec(f"p{v1}{v2}=Function('p{v1}{v2}')(... |
<reponame>Sarah26-10/rPPG-CANs
from scipy import signal
import tensorflow as tf
import numpy as np
import scipy.io
import sys
import argparse
sys.path.append('../')
from model import TS_CAN
import h5py
import matplotlib.pyplot as plt
from scipy.signal import butter
from inference_preprocess import preprocess_raw_video,... |
"""
Word embedding based evaluation metrics for dialogue.
This method implements three evaluation metrics based on Word2Vec word embeddings, which compare a target utterance with a model utterance:
1) Computing cosine-similarity between the mean word embeddings of the target utterance and of the model utterance
2... |
<gh_stars>0
# Copyright (c) 2020. CSIRO Australia.
#
# 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, modify, m... |
<filename>svgd/gmm.py<gh_stars>0
import random
import jax.numpy as jnp
from jax.scipy import stats as jsps
from jax import grad, vmap, jit
import matplotlib.pyplot as plt
import numpy as np
import scipy as sp
def mvn_pdf(x, mu, sigma):
k = len(mu)
term1 = (2*jnp.pi)**(-k/2)
term2 = 1./jnp.sqrt(jnp.... |
<reponame>yirencaifu/pyWindMongoDB<filename>windMongoTools/testWindPar.py
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 25 09:58:36 2014
@author: space_000
"""
import multiprocessing
from scipy.io import loadmat
import WindPy
#%%
def calculate(args):
func,arg=args
result=func(*arg)
return result
def mgW... |
import numpy as np
import pandas as pd
from scipy.stats import invgamma, multivariate_normal
from scipy.special import logsumexp
from typing import Dict, Union
from replay_structure.metadata import MODELS_AS_STR
from replay_structure.structure_models_gridsearch import Structure_Gridsearch
from replay_structure.utils i... |
<filename>acoustics/standards/iso_1996_2_2007.py<gh_stars>0
"""
ISO 1996-2:2007
ISO 1996-2:2007 describes how sound pressure levels can be determined by direct measurement,
by extrapolation of measurement results by means of calculation, or exclusively by calculation,
intended as a basis for assessing environmental no... |
"""*******************************************************
Classes and functions for model fitting
******************************************************"""
__author__ = 'maayanesoumagnac'
import numpy as np
from scipy import optimize
class objective_no_cov(object):
def __init__(self,interpolated_model,data): ... |
__author__ = 'matt'
import chumpy.ch as ch
import numpy as np
from chumpy.utils import row, col
import scipy.sparse as sp
import scipy.special
class Interp3D(ch.Ch):
dterms = 'locations'
terms = 'image'
def on_changed(self, which):
if 'image' in which:
self.gx, self.gy, self.gz = np.g... |
"""
This script implements the modulation -> channel -> demodulation signal chain for a Flash memory, only modelling neighbouring cells.
Structure is inspired by the AFF3CT library examples for simple integration.
https://aff3ct.readthedocs.io/en/latest/user/library/examples.html
"""
#%%i
from cmath import inf
import n... |
<filename>community.py<gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#Module to simulate the null model
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from random import choices, sample
from collections import Counter
def predict(mu, s, N, S, dist, gm,NC1,NC2, rhok=np.arange(0.5,1,... |
<filename>galpopfm/dustfm.py
'''
foward modeling dust with empirical prescriptions for assigning
attenuation curves for forward modeled galaxies
'''
import numpy as np
from scipy.stats import truncnorm
def Attenuate(theta, lam, spec_noneb, spec_neb, logmstar, logsfr, dem='slab_calzetti'):
''' DEM attenuation... |
<filename>code/CNN_LSTM/predict_val.py<gh_stars>1-10
import os
import keras
from keras.layers import concatenate
from sklearn.metrics import cohen_kappa_score
import scipy.io
import math
import random
from keras import optimizers
import numpy as np
import scipy.io as spio
from sklearn.metrics import f1_score, accur... |
<filename>scripts/custom.py
import numpy as np
import skfuzzy as fuzz
import skfuzzy.control as ctrl
import scipy.ndimage as img
def custom_process(height):
""" Custom function for experimental data analysis. """
return height
def fuzzy_custom(height, growth, canopy):
""" Perform fuzzy logic analysis o... |
from pandas import read_csv
from scipy.stats import binom
import matplotlib.pyplot as plt
from numpy import arange, clip, mean
from palettable.colorbrewer.sequential import YlOrRd_9
# read data
df = read_csv('data/MTBS.500m.csv', index_col=0)
# select first half (1984 - 2000)
first_half = (df.set_index('ecoregion')
... |
<reponame>mingruimingrui/torch-datasets
""" Collection of functions to transform popular datasets into torch_dataset Datasets """
import os
import tqdm
import json
from scipy.io import loadmat
from .detection_dataset import DetectionDataset
from .siamese_dataset import SiameseDataset
def convert_coco_to_detection_d... |
<gh_stars>1-10
# coding=utf-8
from matplotlib import pyplot as plt
plt.style.use("ggplot")
import json
import numpy as np
import scipy.io as sio
from keras import backend as K
from keras.models import model_from_json
from keras.layers import Dense, Dropout, Activation, Flatten, Embedding, LSTM, GRU, Input, RepeatVect... |
import math
import cmath
import numpy as np
import sys
import os
import json
import collections
sys.path.append('/usr/src/gridappsd-python')
from gridappsd import GridAPPSD
prefix17 = '''
PREFIX r: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX c: <http://iec.ch/TC57/2012/CIM-schema-cim17#>
'''
pr... |
"""
Tests for quad.py
Notes
-----
Many of tests were derived from the file demqua## in the CompEcon
toolbox.
For all other tests, the MATLAB code is provided here in
a section of comments.
"""
import os
import unittest
from scipy.io import loadmat
import numpy as np
from numpy.testing import assert_allclose
import p... |
import numpy as np
from scipy.spatial import distance
def generate_mmc_center(var, dim_dense, num_class):
mmc_centers = np.zeros((num_class, dim_dense))
mmc_centers[0][0] = 1
for i in range(1,num_class):
for j in range(i):
mmc_centers[i][j] = - (1/(num_class-1) + np.dot(mmc_centers[i... |
# This is the code to extract Noiseprint
# python main_extraction.py input.png noiseprint.mat
# python main_showout.py input.png noiseprint.mat
#
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#
# Copyright (c) 2019 Image Processing Research Group of University Federico II of Naples (... |
<reponame>duc90/marvin
#!/usr/bin/env python
# encoding: utf-8
#
# @Author: <NAME>
# @Date: Nov 1, 2017
# @Filename: general.py
# @License: BSD 3-Clause
# @Copyright: <NAME>
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
import collections
import inspect
... |
<reponame>mdecourse/IKBT
#!/usr/bin/python
#
# BT Nodes for specific symbolic steps
# Copyright 2017 University of Washington
# Developed by <NAME> and <NAME>
# BioRobotics Lab, University of Washington
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that ... |
<reponame>xdslproject/devito<filename>tests/test_linearize.py
import pytest
import numpy as np
import scipy.sparse
from devito import (Grid, Function, TimeFunction, SparseTimeFunction, Operator, Eq,
MatrixSparseTimeFunction, sin)
from devito.ir import Call, Callable, DummyExpr, Expression, FindNode... |
<reponame>Hyunmok-Park/GNN_hyunmok
import os
import pickle
import numpy as np
from utils.topology import NetworkTopology, get_msg_graph
from model.gt_inference import Enumerate
from scipy.sparse import coo_matrix
import argparse
def mkdir(dir_name):
if not os.path.exists(dir_name):
os.makedirs(dir_name)
prin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.