text string |
|---|
<reponame>lefevre-fraser/openmeta-mms<filename>bin/Python27/Lib/site-packages/sympy/combinatorics/perm_groups.py<gh_stars>0
from random import randrange, choice
from math import log
from sympy.core import Basic
from sympy.combinatorics import Permutation
from sympy.combinatorics.permutations import (_af_commutes_with,... |
<filename>pypower/opf_consfcn.py<gh_stars>100-1000
# Copyright (c) 1996-2015 PSERC. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
"""Evaluates nonlinear constraints and their Jacobian for OPF.
"""
from numpy import zeros, ones, conj, exp, r_... |
from tfumap.load_datasets import load_CIFAR10, load_MNIST, load_FMNIST, mask_labels
import tensorflow as tf
from tfumap.paths import MODEL_DIR
import numpy as np
pretrained_networks = {
"cifar10_old": {
"augmented": {
4: "cifar10_4____2020_08_09_22_16_45_780732_baseline_augmented", # 15
... |
"""
list line counts
"""
import argparse
import os
import subprocess
import re
import collections
import sys
import json
import typing
import statistics
def list_files_in_folder(path: str, extensions: typing.Optional[typing.List[str]]):
for root, directories, files in os.walk(path):
for file in files:
... |
<gh_stars>1-10
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import scipy as sp
from sys import path
path.insert(0, '/home/thais/dev/alveus/') # needed to import alveus
path.insert(0, '/home/oem/Documents/Code/2018/Projects/ESN/alveus/') # needed to import alveus
from alveus.data.generator... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Estimate image statistics (2D or 3D). Combination of ct_segnet.stats and ct_segnet.measurements.
1. signal-to-noise ratio (SNR) for binarizable datasets.
2. accuracy metrics for segmentation maps.
"""
import numpy as np
from multiprocessing import cpu_c... |
<filename>dojo/linear/ridge.py
import numpy as np
from scipy import linalg
from ..base import Regressor
from ..exceptions import MethodNotSupportedError
from ..metrics import mean_squared_error
__all__ = [
"Ridge",
]
class Ridge(Regressor):
"""L2 regularized Linear Regression model.
Ridge regressio... |
<reponame>DionEngels/MBxPython
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 7 12:21:19 2020
@author: s150127
"""
from scipy.fftpack import ifftn
import numpy as np
from math import pi
import math
import cmath
import matplotlib.pyplot as plt
import time # for timekeeping
def makeGaussian(size, fwhm = 3, center=None... |
<reponame>moble/galgebra
from sympy import symbols
from mv import MV
from printer import xdvi,Format
def main():
#Format()
coords = (x,y,z) = symbols('x y z')
(ex,ey,ez,grad) = MV.setup('e*x|y|z','[1,1,1]',coords=coords)
s = MV('s','scalar')
v = MV('v','vector')
b = MV('b','bivector')
p... |
<reponame>BatFresh/ICC_algorithm_implement<filename>Dataset.py
from Taskgraph_pre import GRAPH_PRE_A,GRAPH_PRE_ResNet18,GRAPH_PRE_Vgg16,GRAPH_PRE_Inceptionv3,GRAPH_PRE_AlexNet
# configure
decistion_time_number = 2
default_timewindow = 30
lookahead_window_size = default_timewindow
# --------------Task Composing-----... |
#////////////////////////////////////////////////////////////////////////////////////
#// Authors: <NAME> and <NAME>
#// (Ph.D. advisor: <NAME>),
#// Many subsequent changes for open-sourcing were made by <NAME>
#// (Ph.D. advisor: <NAME>)
#//
#// BSD 3-Clause License
#//
#// Copyright (c) 20... |
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 23 11:56:05 2020
@author: <NAME>
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import optimize
import requests
import io
import datetime
import csv
import urllib
if True:
url = 'https://raw.githubusercontent.com/datasets/covid-19... |
import matplotlib
matplotlib.use('PS')
import matplotlib.pyplot as plt
import pickle
from keras.layers import Conv2D, BatchNormalization, Input, concatenate, ZeroPadding2D
# from keras.layers import Dense, Activation, Lambda, Conv2D, MaxPool2D, Flatten, BatchNormalization, Input, concatenate
from keras.layers.advanced... |
<filename>pvfit/modeling/double_diode/equation.py
import numpy
from scipy.constants import convert_temperature
from scipy.optimize import minimize_scalar, newton
from pvfit.common.constants import k_B_J_per_K, minimize_scalar_bounded_options_default, newton_options_default, q_C
def current_sum_at_diode_node(*, V_V, ... |
# -*- coding: utf-8 -*-
"""
Spectrogram.
:copyright: 2015 Agile Geoscience
:license: Apache 2.0
"""
import numpy as np
from scipy.fftpack import fft
from scipy.signal import get_window
from bruges.util import next_pow2
def spectrogram(data, window_length,
dt=1.0,
window_type='boxcar'... |
import numpy as np
import scipy.sparse as sp
from .walker import RandomWalker
from .utils import Word2Vec
from .trainer import Trainer
class DeepWalk(Trainer):
r"""An implementation of `"DeepWalk" <https://arxiv.org/abs/1403.6652>`_
from the KDD '14 paper "DeepWalk: Online Learning of Social Represen... |
<reponame>pswapnesh/iam-essentials
import skimage.morphology as morph
import numpy as np
from napari.types import ImageData, LabelsData
import scipy.ndimage as ndi
'''
dilation erosion etc.
dilation without touching
remove smalle holes
remove small objects
remove objects with contraints
'''
def iam_binary_dilatio... |
<filename>evaluation/eval_utils_v1.py
"""
Evaluation-related codes are modified from CASS
"""
import copy
import json
import logging
import math
import os
from ctypes import *
from pprint import pprint
import cv2
import matplotlib.pyplot as plt
import numpy as np
import scipy.misc
import skimage.color
from tqdm im... |
import pickle
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.stats import norm
import multiprocessing as mp
from functools import partial
import os
import linecache
import sys
import traceback
from inspect import getmembers, isfunction
import inspect
plt.rcParams.update({'figure.m... |
"""
Derived module from dmdbase.py for forward/backward dmd.
"""
import numpy as np
from scipy.linalg import sqrtm
from .dmd import DMD
class FbDMD(DMD):
"""
Forward/backward DMD class.
:param svd_rank: the rank for the truncation; If 0, the method computes the
optimal rank and uses it for trunc... |
<reponame>cchandre/RG
#
# BSD 2-Clause License
#
# Copyright (c) 2021, <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright ... |
import scipy as sp
import torch
from aljpy import arrdict
import numpy as np
def quad_kernel(a, b):
return 1/((a - b)**2).sum(-1)
def random_problem(S=3, T=5, D=2, device='cuda'):
prob = arrdict.arrdict(
sources=np.random.uniform(-1., +1., (S, D)),
charges=np.random.uniform(.1, 1., (S,)),
... |
#coding=utf-8
#!/usr/bin/env python
# --------------------------------------------------------
# Faster R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by <NAME>
# --------------------------------------------------------
"""
Demo script showing detections in s... |
<reponame>nathane1/MetPy<filename>src/metpy/calc/tools.py
# Copyright (c) 2016,2017,2018,2019 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
"""Contains a collection of generally useful calculation tools."""
import functools
from operator import item... |
from __future__ import print_function
import os
import shutil
import warnings
import tempfile
import pickle
import numpy
import scipy.linalg as linalg
from galpy.util.config import __config__
_SHOW_WARNINGS= __config__.getboolean('warnings','verbose')
class galpyWarning(Warning):
pass
# galpy warnings only shown if... |
import random
import math
import copy
import numpy as np
import sys
from PIL import Image
from metrics import AEBatch, SEBatch
import time
import torch
import scipy.io as scio
class Estimator(object):
def __init__(self, opt, setting, eval_loader, criterion=torch.nn.MSELoss(reduction="sum")):
self.datasets_... |
from argparse import ArgumentParser
import imageio
from PIL import Image
from tqdm import tqdm
from scipy.spatial import ConvexHull
import numpy as np
import coremltools as ct
import matplotlib.pyplot as plt
# output nodes in CoreML model
VAL_ALIAS = 'var_452' # value in kp_detector output, shape (1,10,2)
JAC_ALIAS... |
<filename>pyapprox/tests/test_polynomial_sampling.py
import unittest
import numpy as np
from scipy import stats
from pyapprox.polynomial_sampling import christoffel_function, \
get_fekete_samples, christoffel_weights, interpolate_fekete_samples, \
get_lu_leja_samples, get_quadrature_weights_from_fekete_samples... |
import numpy as np
from scipy import stats
from sklearn import metrics
import torch
def d_prime(auc):
standard_normal = stats.norm()
d_prime = standard_normal.ppf(auc) * np.sqrt(2.0)
return d_prime
def calculate_stats(output, target):
"""Calculate statistics including mAP, AUC, etc.
Args:
o... |
from scipy import stats
from crayon.Runner import Jobs
import numpy as np
def ks_test(
sample_a: Jobs, sample_b: Jobs, metric_name: str, p_limit: int = 0.05
):
"""
Returns True if sample_a and sample_b are sampled from the same distribution.
I.e. if the kolmogorov smirnow test outputs a p value higher... |
"""
Calculation EM for many EBTEL runs and fit slopes
"""
import os
import pickle
import logging
import numpy as np
from scipy.optimize import curve_fit
import em_binner as emb
try:
import __builtin__
except ImportError:
import builtins as __builtin__
#Resolve Python 2/3 exception problem
exc = getattr... |
<reponame>spWang/gitHooks
#!/usr/bin/env python
# coding=utf-8
import subprocess
import os
import statistics
from util.colorlog import *
'''公开函数'''
def key_words():
return ["re-", "re_", "review-", "review_", "rbt-","rbt_"]
pass
def log_operation_not_permitted(file_path, func_desc, cammand):
print "\n"
... |
""" Transient single-phase flow """
from time import time
import numpy as np
import scipy.optimize
import ressim
import matplotlib
matplotlib.use('Agg')
matplotlib.rcParams['image.cmap'] = 'jet'
import matplotlib.pyplot as plt
from spatial_expcov import batch_generate
np.random.seed(42) # for reproducibility
nx,... |
<filename>openfermioncirq/experiments/hfvqe/circuits_test.py
import cirq
import numpy as np
import scipy as sp
import pytest
from openfermioncirq.experiments.hfvqe.circuits import (
rhf_params_to_matrix,
ryxxy,
ryxxy2,
... |
<reponame>macsz/SlowFast<filename>slowfast/datasets/transform.py
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import logging
import math
import numpy as np
# import cv2
import random
import torch
import torchvision as tv
import torchvision.transforms.functional as F
f... |
from numpy import pi
import numpy as np
import math
#from sympy import Matrix
import pylab
#import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
#from scipy.interpolate import Rbf
import pickle
from scipy.sparse import csr_matrix
from scipy.sparse import lil_matrix
from scipy.sparse.linalg import sps... |
<gh_stars>1-10
import argparse
import numpy as np
import os
from tqdm import tqdm
import scipy.io as sio
import pathlib
import shutil
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Cars data preparation')
parser.add_argument('--path-to-data', type=str, default='./data/', metavar='Path', he... |
<reponame>stacowrap/nasa-climate-data
#!/usr/bin/env python3
import csv
from pathlib import Path
from statistics import mean
from sys import stderr
DEST_PATH = Path('data', 'wrangled', 'nasa-co2-temps.csv')
SRC_DIR = Path('data', 'collated')
SRC = {
'co2_new': SRC_DIR / 'co2-mm.csv',
'co2_old': SRC_DIR / 'ghga... |
<reponame>fmi-basel/improc<gh_stars>0
import numpy as np
from scipy.ndimage.filters import gaussian_filter
from scipy.ndimage import find_objects
from skimage.transform import rescale
def resample_labels(labels, factor):
'''Resample labels one by one with a gaussian kernel'''
# TODO check alignment for float... |
<gh_stars>0
"""This module contains utilities for methods."""
import logging
from math import ceil
import numpy as np
import scipy.stats as ss
import elfi.model.augmenter as augmenter
from elfi.clients.native import Client
from elfi.model.elfi_model import ComputationContext
logger = logging.getLogger(__name__)
d... |
#!/usr/bin/env python
import sys
import math
import numpy as np
import scipy.cluster.hierarchy
from cafysis.file_io.drid import DridFile
if len(sys.argv) != 5:
print('Usage: SCRIPT [DRID file] [prefix] [cutoff] [nskip (to calculate frame id)]')
sys.exit(2)
drid_filepath = sys.argv[1]
prefix = sys.argv[2]
cut... |
<gh_stars>1-10
import numpy as np
import sys
import logging
import pickle
import matplotlib.pyplot as plt
from pathlib import Path
from scipy.optimize import minimize_scalar
from itertools import product
import ray
import pandas as pd
import click
from neslab.find import distributions as dists
from neslab.find import... |
from functools import wraps
import os, os.path
import shutil
import subprocess
import numpy
from scipy import special
import apogee.tools.read as apread
import apogee.tools.path as appath
from apogee.tools import toAspcapGrid,_aspcapPixelLimits
from apogee.spec.plot import apStarWavegrid
def specFitInput(func):
"""... |
<reponame>FHead/hic-param-est-2017
"""
Markov chain Monte Carlo model calibration using the `affine-invariant ensemble
sampler (emcee) <http://dfm.io/emcee>`_.
This module must be run explicitly to create the posterior distribution.
Run ``python -m src.mcmc --help`` for complete usage information.
On first run, the n... |
#! /usr/bin/python3
import pandas as pd
import numpy as np
from scipy.sparse import csr_matrix
import scipy
from tqdm import tqdm
import argparse
root_path = '../../tencent_dataset/preliminary_contest_data/'
def trainpred_pair(index):
train_ary = scipy.sparse.load_npz(root_path + 'train_{}.npz'.format(index))
... |
import os
import re
import pandas as pd
from scipy import sparse, io
import numpy as np
def save_i_featvec(data_file_dir, output_file_dir, feat_file):
df = pd.read_csv(data_file_dir+feat_file, header=None, skiprows=1, sep='\t')
df = df.set_index(0)
df.to_csv(output_file_dir+feat_file.replace('.tsv', '.csv... |
<reponame>tombh/sktime<gh_stars>1000+
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
from joblib import Parallel
from joblib import delayed
from scipy import sparse
from sklearn.pipeline import FeatureUnion as _FeatureUnion
from sklearn.pipeline import _fit_transform_one
from sklearn.pipeline import _tr... |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative wo... |
# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
# with the License. A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file acco... |
<reponame>RosieCampbell/CADL<gh_stars>1-10
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
from libs import utils
from libs import dataset_utils
from libs import vgg16, inception, i2v
from libs import stylenet
def test_libraries():
import os
i... |
<gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 22 16:42:12 2017
Originial Author: <NAME>
Licence: BSD 3-clause
@author: dhingratul
Newton's Root Finding Algorithm'
"""
from scipy.optimize import newton
from sklearn.utils.testing import assert_almost_equal
def f(x):
return 6*x... |
"""
Segment song motifs by finding maxima in spectrogram cross correlations.
"""
__date__ = "April 2019 - November 2020"
from affinewarp import ShiftWarping
import h5py
from itertools import repeat
from joblib import Parallel, delayed
import matplotlib.pyplot as plt
plt.switch_backend('agg')
try: # Numba >= 0.52
fr... |
import unittest
import numpy
import chainer
from chainer.backends import cuda
import chainer.functions as F
from chainer import testing
def _ndtri_cpu(x, dtype):
from scipy import special
return numpy.vectorize(special.ndtri, otypes=[dtype])(x)
def _ndtri_gpu(x, dtype):
return cuda.to_gpu(_ndtri_cpu(c... |
"""Helper classes used through PJLink to facilitate MathLink communication
"""
from .MathLinkEnvironment import MathLinkEnvironment as Env
from .MathLinkExceptions import MathLinkException
###############################################################################################
# ... |
import sympy
from sympy import Function, dsolve, Symbol
# symbols
t = Symbol('t', positive=True)
wf = Symbol('wf', positive=True)
# unknown function
u = Function('u')(t)
# solving ODE with initial conditions
u0 = 0.4
v0 = 2
k = 150
m = 2
F0 = 10
wn = sympy.sqrt(k/m)
#wf = 2*sympy.sqrt(k/m)
F = F0*sympy.sin(wf*t)
ics... |
<filename>SkeletonTracking/train.py<gh_stars>1-10
import cv2
import json
import lmdb
import numpy as np
import os.path
import scipy.io as sio
import struct
import sys
import caffe
def generateLmdbFile(lmdb_path, img_folder, json_file, caffee_path, mask_folder = None):
print('Creating ' + lmdb_path + ' from ' + js... |
<filename>examples/scft/Sphere.py
# For the start, change "Major Simulation Parameters", currently in lines 20-27
# and "Initial Fields", currently in lines 70-84
import os
import numpy as np
import time
from scipy.io import savemat
from scipy.ndimage.filters import gaussian_filter
from langevinfts import *
fro... |
<filename>sparse_data/utils.py
# coding=utf-8
# Copyright 2020 The Google Research Authors.
#
# 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
... |
<filename>fpch2scph/idpflex/test/test_helper.py
from __future__ import print_function, absolute_import
import h5py
import numpy as np
import os
import pytest
import sys
from copy import deepcopy
from distutils.version import LooseVersion
from scipy.cluster.hierarchy import linkage
from idpflex import cnextend as cnx,... |
<gh_stars>0
import io
import os
import datetime
import warnings
import pandas as pd
import requests
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from scipy.ndimage.filters import gaussian_filter
from astropy import units as u
from astropy.coordinates import SkyCoord
from ... |
#!/usr/bin/python3
import argparse, logging, os, pickle, random, sys
from collections import OrderedDict
import numpy as np
from scipy.spatial.distance import cosine
# local imports
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from lib.data import *
from lib.utils import *
def parse_arguments()... |
<filename>process_dataset.py
# -----------------------------------------------------
# Generate Annotations for Person Search Dataset
#
# Author: <NAME>
# Creating Date: Mar 16, 2018
# Latest rectifying: Mar 18, 2018
# -----------------------------------------------------
import os
import os.path as osp
import numpy ... |
import pandas as pd
import numpy as np
import scipy.spatial as spatial
import scipy.stats as stats
def parse_args():
from argparse import ArgumentParser, FileType
parser = ArgumentParser(description='Find overlap between new dataset and reference')
parser.add_argument(
'--reference',
requir... |
<reponame>CompbioLabUnist/dream_challenge-anti-pd1_response<filename>jwlee230/Program/Python/step08.py
"""
step08.py: get R2 scores
"""
import argparse
import multiprocessing
import pandas
import scipy.stats
import step00
def r2_score(x, y):
"""
r2_score: get R2 score between x and y
"""
return scipy.... |
"""
Joint Random Variables Module
See Also
========
sympy.stats.rv
sympy.stats.frv
sympy.stats.crv
sympy.stats.drv
"""
from __future__ import print_function, division
from sympy import Basic, Lambda, sympify, Indexed, Symbol, ProductSet, S, Dummy
from sympy.concrete.products import Product
from sympy.concrete.summat... |
<reponame>starkgate/DOPlearning
from __future__ import division
import torch
from torch.autograd import Variable
from scipy.sparse import coo_matrix
pixel_coords = None
def set_id_grid(depth):
global pixel_coords
b, h, w = depth.size()
i_range = Variable(torch.arange(0, h).view(1, h, 1).expand(1,h,w)).... |
<reponame>uhoefel/coordinates
import sympy as sym
from metric import Metric
from coordinate_system_implementation_generator import JavaCoordinateSystemCreator
sigma = sym.symbols('sigma',real=True, positive=True)
tau = sym.symbols('tau', real=True, positive=True)
phi = sym.symbols('phi', real=True, positive=Tru... |
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 14 20:41:09 2015
@author: oliver
"""
import numpy as np
from sympy import symbols, sin
import mubosym as mbs
from interp1d_interface import interp
###############################################################
# general system setup example
myMBS = mbs.MBSworld('quart... |
#!/usr/bin/env python
# Copyright (c) 2014, Robot Control and Pattern Recognition Group, Warsaw University of Technology
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions o... |
<gh_stars>1-10
from sympy import (symbols, Symbol, sinh, nan, oo, zoo, pi, asinh, acosh, log,
sqrt, coth, I, cot, E, tanh, tan, cosh, cos, S, sin, Rational, atanh, acoth,
Integer, O, exp, sech, sec, csch, asech, acsch, acos, asin, expand_mul,
AccumBounds, im, re)
from sympy.core.function import ArgumentInd... |
<reponame>lelegan/sympy<filename>sympy/geometry/util.py
"""Utility functions for geometrical entities.
Contains
========
intersection
convex_hull
are_similar
"""
from __future__ import print_function, division
from sympy import Symbol, Function, solve
from sympy.core.compatibility import string_types, is_sequence
... |
import os
import numpy as np
import pandas as pd
import scipy.io as sio
from sklearn.model_selection import train_test_split
position_list = ['unknown', 'wrist', 'waist', 'chest', 'ankle', 'arm', 'pocket']
device_list = ['unknown', 'smartphone', 'smartwatch', 'imu']
PATH_DATA = os.path.join(os.path.dirname(os.path.abs... |
<gh_stars>0
import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt
# define grid
p_grid = np.linspace(0, 1, num=20)
# define prior
prior = np.repeat(1, 20)
# Other priors
# prior[p_grid < 0.5] = 0
# prior = np.exp(-5 * np.abs(p_grid - 0.5))
# compute likelihood at each value in grid
likeliho... |
<filename>clustergrammer/upload_pages/clustergrammer_py_v112_vect_post_fix/calc_clust.py<gh_stars>1-10
def cluster_row_and_col(net, dist_type='cosine', linkage_type='average',
dendro=True, run_clustering=True, run_rank=True,
ignore_cat=False, calc_cat_pval=False):
''' c... |
import numpy as np
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
from matplotlib import cm
from scipy.spatial import Delaunay
from scipy.linalg import eigh
from truss2d import Truss2D, update_K_M
DOF = 2
lumped = True
# number of nodes in each direction
nx = 20
ny = 4
# geometry
a = 10
... |
import numpy as np
from fenics import *
from poisson_problem import nonlinear_neumann_poisson_problem
from tensor_train_from_tensor_action import tensor_train_from_tensor_action, randomized_SVD
from tensor_maximum_singular_value import tensor_maximum_singular_value
from tensor_operations import tensor_train_symmetric_p... |
# Copyright 2019-2021 Cambridge Quantum Computing
#
# 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 a... |
# encoding: utf-8
"""Unit tests for ckan/logic/validators.py.
"""
import warnings
import copy
import decimal
import fractions
import mock
import pytest
import ckan.lib.navl.dictization_functions as df
import ckan.logic.validators as validators
import ckan.model as model
import ckan.tests.factories as factories
impor... |
"""
Torch argmax policy
"""
import numpy as np
from scipy.special import softmax
from torch import nn
import rlkit.torch.pytorch_util as ptu
from rlkit.policies.base import Policy
class SoftmaxDiscretePolicy(nn.Module, Policy):
def __init__(self, qf, temperature=1):
super().__init__()
self.qf = q... |
# Developed by Redjumpman for Redbot.
# Inspired by Spriter's work on a modded economy.
# Creates 1 json file, 1 log file per 10mb, and requires tabulate.
# STD Library
import asyncio
import gettext
import logging
import logging.handlers
import os
import random
from copy import deepcopy
from fractions impo... |
"""
Tests for ImageLoader.
"""
import os
import unittest
import tempfile
from scipy import misc
from PIL import Image
import deepchem as dc
import zipfile
class TestImageLoader(unittest.TestCase):
"""
Test ImageLoader
"""
def setUp(self):
super(TestImageLoader, self).setUp()
self.current_dir = os.pat... |
<reponame>achistef/Master-Thesis-code<filename>src/head size/ABD_heads.py
# import packages
import json
import random
import time
import warnings
from _collections import defaultdict
from pathlib import Path
from statistics import mean, pvariance
import networkx as nx
import numpy as np
import scipy.sparse as sps
impo... |
<gh_stars>1-10
# Script to simulate constant pressure reactor for a given time it spits out
# temps and species concentrations at all the time steps.
# 17 NOV 2009 Started reactor simulator based on Equilibrium.py and an
# old reactor simulator I wrote for the TEOS work - ras81
from Cantera import *
from Cantera.Re... |
# encoding: utf-8
"""Module to create random test instances of matrix product arrays"""
from __future__ import division, print_function
import functools as ft
import itertools as it
import collections
import numpy as np
from scipy.linalg import qr
from six.moves import range
from . import mparray as mp
from . impo... |
<reponame>reppertj/terminal-ascii-art<gh_stars>1-10
from scipy.spatial import cKDTree
class ANSITree:
def __init__(self, ansi_dict):
self.ansi_values = list(ansi_dict.keys())
colors = [rgb for key, rgb in ansi_dict.items()]
self.tree = cKDTree(colors)
def nearest_ansi(self, color):
... |
import numpy as np
import scipy.stats as st
from niscv.clustering.probability import Probability
import multiprocessing
import os
from functools import partial
from datetime import datetime as dt
import pickle
def experiment(dim, b, size_est, show, size_kn, ratio, resample=True, mode=0):
results = []
mean = n... |
# Copyright 2016 <NAME>
#
# 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
try:
from QGL import *
from QGL import config as QGLconfig
... |
<reponame>python-like-r/python-like-r
import numpy as np
from scipy.stats import t
import statsmodels.api as sm
import matplotlib.pyplot as plt
from src.models.BaseRegressor import BaseRegressor
from src.utility.helper import rounded_str, get_p_significance
class lm(BaseRegressor):
"""lm is used to fit linear mo... |
<reponame>dulkith/gradio
"""
This module defines various classes that can serve as the `output` to an interface. Each class must inherit from
`OutputComponent`, and each class must define a path to its template. All of the subclasses of `OutputComponent` are
automatically added to a registry, which allows them to be ea... |
"""
Simulation utils, allowing to flexibly consider different DGPs
"""
# Author: <NAME>
from typing import Any, Optional, Tuple
import numpy as np
from scipy.special import expit
def simulate_treatment_setup(
n: int,
d: int = 25,
n_w: int = 0,
n_c: int = 0,
n_o: int = 0,
n_t: ... |
import sys
import nibabel as nib
import numpy as np
import json
from nilearn.image import resample_to_img, reorder_img, new_img_like
from scipy.ndimage import binary_erosion
def load_json(filename):
with open(filename, 'r') as opened_file:
return json.load(opened_file)
def dump_json(dataobj, filename):... |
<gh_stars>10-100
"""Sparse approximations for Gaussian process models
Models implemented include GP Gaussian regression/Probit classification,
GP latent variable model, GP state space model and Deep GPs
Inference and learning using approximate EP (or Black-box alpha)
"""
import sys
import math
import numpy as np
imp... |
import scipy
from sentence_transformers import SentenceTransformer
#########################################################################
### compute similarity
#########################################################################
def load_distance_scorer(is_cuda):
distance_scorer = SentenceTransformer('sts... |
<reponame>Ron024/colour
# -*- coding: utf-8 -*-
"""
Meng et al. (2015) - Reflectance Recovery
=========================================
Defines objects for reflectance recovery using *Meng, Simon and Hanika (2015)*
method:
- :func:`colour.recovery.XYZ_to_sd_Meng2015`
See Also
--------
`Meng et al. (2015) - Reflect... |
<gh_stars>0
#!/usr/bin/env python3
##########################################
# Duino-Coin Python AVR Miner (v2.5.7)
# https://github.com/revoxhere/duino-coin
# Distributed under MIT license
# © Duino-Coin Community 2019-2021
##########################################
# Import libraries
import sys
from configparser imp... |
import tensorflow as tf
import gpumemory
import numpy as np
from util import *
import os
from scipy import misc
import timeit
from net import base_net, refine_net
flags = tf.app.flags
flags.DEFINE_string('alpha_path', None, 'Path to alpha files')
flags.DEFINE_string('trimap_path', None, 'Path to trimap files')
flags.D... |
import os, glob
from statistics import NormalDist
import pandas as pd
import numpy as np
import input_representation as ir
SAMPLE_DIR = os.getenv('SAMPLE_DIR', './samples')
OUT_FILE = os.getenv('OUT_FILE', './metrics.csv')
MAX_SAMPLES = int(os.getenv('MAX_SAMPLES', 1024))
METRICS = [
'inst_prec', 'inst_rec', 'inst... |
<filename>benchmarks/benchmark.py
import os
import sys
import re
import subprocess
import traceback
import statistics
python = "python3"
progname = "/Users/emery/git/scalene/benchmarks/julia1_nopil.py"
number_of_runs = 1 # We take the average of this many runs.
# Output timing string from the benchmark.
result_regexp... |
import numpy as np
from PIL import Image
from scipy.ndimage import filters
# 关于scipy
# http://docs.scipy.org/doc/scipy/reference/ndimage.html
# 高斯模糊
# 图像的高斯模糊是非常经典的图像卷积例子。
# 本质上,图像模糊就是将(灰度)图像 I 和一个高斯核进行卷积操作:
im = np.array(Image.open('test.jpg').convert('L'))
# guassian_filter() 函数的最后一个参数表示标准差。
im2 = filters.gaussian_... |
<gh_stars>0
"""
This is the main tester script for shape reconstruction, shape gemeration and shape interpolation (or fix geometry/structure).
for each 'id' folder, there are the 'input','generation', and 'recon' shapes.
for the interpolation, there are three folders: interpolate, interpolate_geo and int... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.