text string |
|---|
import os
import networkx as nx
import logging
import math
import networkx.algorithms.community.lukes as lukes
from datetime import datetime
import statistics
from utils import helpers
import globals
MSA = None
#get total score of all vertices in a set
def total_score(vSet):
total_score = 0
for v in vSet:
to... |
#! /usr/bin/env python
# Copyright 2012-2015 <NAME> <<EMAIL>> and collaborators.
# Licensed under the MIT License.
"""Compute diagnostics regarding the quality of gain/phase calibration.
NB. The GainCal class should be generically useful.
"""
from __future__ import absolute_import, division, print_function, unicode_... |
import csv
import os
from zipfile import ZipFile
import nltk
from flask import (Blueprint, flash, redirect, render_template, request, url_for, Flask)
from flask_table import Table, Col, LinkCol
from gensim.models import Word2Vec
from scipy import spatial
from sklearn.metrics.pairwise import cosine_similarity
from werk... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 19 10:56:26 2021
@author: thanh
"""
import copy
import math
from sympy import *
import itertools
import random
import IALib as IA
def makesingletestfile_nomanual(funcname):
filename=funcname+'/'+funcname+ "_timetestsingle.txt"
file=open(f... |
<gh_stars>0
# -*- coding: utf-8 -*-
r"""Wigner D class
This class allows you to quickly calculate Wigner D matrix values using the symbolic lookup Wigner D
functionality available from sympy.physics. It will be slow when first calculating a set of l, m,
and j values but will hence-forth become fast and evaluate quick... |
from scipy.stats import kurtosis, skew
from rackio_AI.utils.utils_core import Utils
import pywt
import numpy as np
import pandas as pd
from rackio_AI.decorators.wavelets import WaveletDeco
from easy_deco.progress_bar import ProgressBar
from easy_deco.del_temp_attr import set_to_methods, del_temp_attr
# @set_to_methods... |
<filename>python/archive/get_mps_synthetic.py
"""Extract MP components from synthetic data and write to file"""
import numpy as np
from scipy.io import savemat
from readers import SyntheticReader
from imagerep import mp_gaussian
# Input and output paths
IN_FPATH = '/home/mn2822/Desktop/WormOT/data/synthetic/fast_3d... |
from nengo.dists import *
from sobol_seq import i4_sobol_generate
class SphericalCoords(Distribution):
def __init__(self, m):
self.m = m
def sample(self, num, d=None, rng=np.random):
shape = self._sample_shape(num, d)
y = rng.uniform(size=shape)
return self.ppf(y)
def pd... |
<filename>scripts/tests_model/test_estimation_on _video/BPM_estimation_on_real_video.py
##
## Importing libraries
##
#Tensorflow/KERAS
import tensorflow as tf
from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.models import model_from_json
from tensorflow.python.keras.utils import np_ut... |
<filename>admin-tools/time-mathmp-sympy-fns.py
#!/usr/bin/env python
"""
Program to time mpmath pi vs sympy pi
"""
from timeit import timeit
import mpmath
import math
import sympy
PRECISION = 100
mpmath.mp.dps = PRECISION
ITERATIONS = 2000
# print(mpmath.pi, "\n")
def math_pi():
return math.pi
def mpmath_pi(... |
<reponame>paarthgupta/Mars-Orbital-Plane-Data-Analytics
import numpy as np
import pandas as pd
import math
import math
from scipy.optimize import minimize
from scipy.stats.mstats import gmean
import matplotlib.pyplot as plt
import matplotlib.patches as pt
#coordinates of mars in 3 dimentions
#x: [-1.4529736727603795,... |
import scipy.io
import sys
import os
import pycurl
index = {}
index['WNID'] = 1
index['IMAGENETID'] = 0
index['WORDS'] = 2
index['HEIGHT'] = 6
def load_synsets(meta_fn):
meta = scipy.io.loadmat(meta_fn)
synsets = meta['synsets'][0]
return synsets
def parse_height(synsets):
synsets_height = [int(sy... |
#!/usr/bin/env python
"""
m2g.stats.qa_tensor
~~~~~~~~~~~~~~~~~~~~
Contains functions to generate intermediate qa figures for the directional field directions
for models used during the tractrography step.
"""
import warnings
warnings.simplefilter("ignore")
from argparse import ArgumentParser
from scipy import ndi... |
# !/usr/bin/python
# -*- coding: utf-8 -*-
"""
This script is designed to store some kind of feature engineering methods.
"""
# Import necessary libraries.
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import scipy
import warnings
import logging
from scipy.stats import kstest
from scipy.stats ... |
<filename>src/lowRankMatrixFactorization/lowRankMatrixFactorization.py
'''
Created on Feb 12, 2020
@author: <NAME> <EMAIL>
'''
import logging
import numpy as np
from scipy import optimize
###############################################################################
class LowRankMatrixFactorization(object):
''... |
from astropy.convolution import Box1DKernel
import emcee
import numpy as np
from scipy import integrate, optimize, signal
from .utils import acf, get_noise, smooth
def Vrng_Basri2011(y):
"""Basri et al. 2011, AJ, 141, 20"""
vrng = np.percentile(y, 95) - np.percentile(y, 5)
return vrng
def HFrms_Basri20... |
<filename>dev/cluster_sampling/dev__cluster_sampling/mc_sampler_iterate_w_cluster.py
import os,shutil,sys
import numpy as np
from mpi4py import MPI
import pandas as pd
from collections import OrderedDict
from pypospack.pyposmat.data import PyposmatConfigurationFile
from pypospack.pyposmat.data import PyposmatDataAnalyz... |
<reponame>lffloyd/reddit-topic-modelling
import numpy as np
import copy
from scipy.spatial.distance import cosine
from gensim.models import KeyedVectors
class MemoryFriendlyFileIterator(object):
def __init__(self, filename):
self.filename = filename
def __iter__(self):
for line in open(self.f... |
#!/usr/bin/env python
# vi: set ft=python sts=4 ts=4 sw=4 et:
######################################################################
#
# See COPYING file distributed along with the psignifit package for
# the copyright and license terms
#
######################################################################
__do... |
<reponame>sauravbose/asthma-biomarker
#Database tools
import pandas as pd
#Math tools
import numpy as np
import itertools
#ML tools
from sklearn.feature_selection import chi2
from sklearn.feature_selection import f_classif
from skrebate import ReliefF, MultiSURF
from scipy import stats
def corr_fs(X_df,X_train_all,X... |
import os
import scipy
import sys
from pipeline_preprocessing import pipeline_preprocessing
import pandas as pd
import numpy as np
from helpers import from_csv_to_nparray
from csv_helpers import csv_helpers
from sklearn.preprocessing import Imputer
def main():
import matplotlib.pyplot as plot
... |
from __future__ import print_function
from __future__ import division
from scipy import sparse
from utils.data import load_data, show_data_splits, shape_data
from utils.evaluation import mask_array_rows, evaluate
from utils.neighbors import normalize_rowwise, songcoo2artistcoo, artistsim2songsim
import argparse
impo... |
import numpy as np
np.random.seed(204)
from scipy.integrate import ode
import matplotlib.pyplot as plt
import matplotlib
matplotlib
matplotlib.rc('font', family='FreeSans', size=14)
N = 36 # Number of swarm particles
t0 = 0.0
y0= []
for theta_idx in np.arange(12):
theta = (theta_idx + 1) / 12 * 2 * np... |
"""
Extracts the cell x gene expression matrix from an AnnData object
From sc-rna-tools package
Created on Mon Jan 10 15:57:46 2022
@author: <NAME> (<EMAIL>)
"""
# external package imports
from typing import Optional
from scipy.sparse import issparse
from pandas import DataFrame
from anndata import AnnData
# mitsa p... |
<gh_stars>0
import matplotlib.pyplot as plt
import numpy
from scipy.constants import pi, epsilon_0
plt.figure(figsize=(3.5, 3.5))
plt.style.use("science")
alpha = 5
delta = numpy.linspace(4.5, 5.5, 1000)
eps = 1 / (1 - alpha / delta)
# print(eps)
plt.plot((delta - alpha)/alpha * 100, eps, "o", markersize=2)
plt.axhlin... |
<reponame>gogobd/pytorch-vq-vae
import os
import glob
import math
import random
import sys
import time
import numpy as np
from PIL import Image
from scipy.signal import savgol_filter
from six.moves import xrange
import umap
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import to... |
<reponame>milad-ahmadi/GAIRD<filename>utils.py
"""
Codes from https://github.com/Newmu/dcgan_code and https://github.com/LeeDoYup/AnoGAN
"""
from __future__ import division
import math
import pprint
import scipy.misc
import numpy as np
pp = pprint.PrettyPrinter()
get_stddev = lambda x, k_h, k_w: 1/math.sqrt(k_w*k_h*x... |
# libraries
import numpy as np
import pandas as pd
import requests
import scipy.stats as ss
import matplotlib as mpl
import json
import plotly.graph_objects as go
from urllib.request import urlopen
with open('../data/census-key.txt') as key:
api_key = key.read().strip()
years = ['2017', '2018']
county = '*'
stat... |
<gh_stars>0
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:light
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.11.4
# kernelspec:
# display_name: Python 3 (PHYS-581-2021)
# language: python
# metadata:
# ... |
<reponame>alex4200/Long-range-micro-connectome
import requests
import os
from scipy import sparse
import numpy
class ConnectomeInstance(object):
"""A class representing a whole neocortex connectome instance with a method to download and instantiate
a connection matrix representing incoming connections into a ... |
<reponame>ProGamerCode/FitML
'''
https://hackernoon.com/visualizing-parts-of-convolutional-neural-networks-using-keras-and-cats-5cc01b214e59
https://stackoverflow.com/questions/43895750/keras-input-shape-for-conv2d-and-manually-loaded-images
'''
import matplotlib.pylab as plt
import matplotlib.image as mpimg
import n... |
import numpy as np
import tensorflow as tf
from scipy import spatial
import operator
def weight_variable(shape, name=None):
initial = tf.glorot_uniform_initializer()
return tf.Variable(initial(shape), name=name)
def bias_variable(shape, name=''):
initial = tf.zeros_initializer()
return tf.Variable(ini... |
import numpy as np
import os
from scipy import stats
from sklearn.model_selection import LeaveOneOut
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics.pairwise import cosine_distances
import torch
from pytorch_metric_learning.distances import CosineSimilarity
import matplotlib.pyplot as plt
from m... |
<reponame>geometer/sandbox
import itertools
import numpy as np
from scipy.optimize import minimize
from .core import CoreScene, Constraint
class TwoDCoordinates:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return '(%.5f, %.5f)' % (self.x, self.y)
def __eq__... |
import re
import numpy as np
import pandas as pd
from collections import Counter, defaultdict
from scipy.sparse import csr_matrix
def sanitize_input(input_str_list):
r"""Replace all instances of 'weird' characters and spaces in string elements of a input_str_list sequence with '_'.
Examples:
[a/?, b\... |
<filename>LSA/hash_counting.py
#from bitarray import bitarray
from ctypes import c_uint16
import glob,os
from collections import defaultdict
import numpy as np
import scipy.stats as stats
import gzip
from LSA import LSA
class Hash_Counting(LSA):
def __init__(self,inputpath,outputpath):
super(Hash_Counting... |
<reponame>ramsdalesteve/forest
import os
import re
import datetime as dt
from functools import partial
import scipy.ndimage
import numpy as np
def timeout_cache(interval):
def decorator(f):
cache = {}
call_time = {}
def wrapped(x):
nonlocal cache
nonlocal call_time
... |
from __future__ import division
import numpy as NP
import multiprocessing as MP
import itertools as IT
import progressbar as PGB
# import aipy as AP
import astropy
from astropy.io import fits
import astropy.cosmology as CP
import scipy.constants as FCNST
import healpy as HP
from distutils.version import LooseVersion
im... |
<reponame>sambit-giri/BCMemu
"""
Created by <NAME>
"""
import numpy as np
from scipy import special
from scipy.interpolate import splev, splrep
import os
import pickle
import pkg_resources
def ps_suppression_8param(theta, emul, return_std=False):
log10Mc, mu, thej, gamma, delta, eta, deta, fb = theta
# fb = ... |
import numpy as np
import random
import time
import collections
import h5py
import csv
import os
import scipy.io as sio
import sc_config
import tensorflow as tf
Dataset = collections.namedtuple('Dataset', ['data', 'target'])
class ScoreData:
def __init__(self, config):
self.pathname = config.test_data
... |
import numpy as np
import os
from scanorama import *
from scipy.sparse import vstack
from sklearn.cluster import KMeans
from sklearn.metrics import roc_auc_score
from sklearn.preprocessing import normalize, LabelEncoder
from experiments import *
from mouse_brain import keep_valid
from process import load_names
from ut... |
"""
Cosmology routines: A module for various cosmological calculations.
The bulk of the work is within the class :py:class:`Cosmology` which stores a
cosmology and can calculate quantities like distance measures.
"""
from dataclasses import dataclass, asdict
import numpy as np
# Import integration routines
from scip... |
#!/usr/bin/env python3
# Fits coefficients for Earth perihelion and aphelion dates
# approximated as in Meeus "Astronomical Algorithms" chapter 38.
# Supplementary to https://astronomy.stackexchange.com/a/42016
import skyfield.api as sf
import skyfield.searchlib as sfs
import numpy as np
import scipy.optimize as opt
... |
'''
Created on May 8, 2016
@author: doronv
'''
# standard python package imports
import numpy as np
import fractions as fr
import collections as co
import math as ma
import re
# read line from file split it according to separator and convert it to type
def processInputLine(inputFile, inputType = int, i... |
<filename>src/contexts/ssim.py<gh_stars>0
#!/usr/bin/python3
import argparse
import numpy as np
from numpy.lib.arraypad import _validate_lengths
from PIL import Image
from scipy.ndimage import gaussian_filter
def crop(ar, crop_width, copy=False, order='K'):
'''Crop numpy array at the borders by crop_width.
... |
# -*- coding: utf-8 -*-
"""
Miscellaneous Helpers and Utils
===============================
"""
from __future__ import division
import sys
import csv
import ast
from datetime import datetime
from collections import defaultdict
import pytz
import numpy as np
import pandas as pd
from scipy import optimize
from IPyth... |
<filename>dolo/tests/test_triangular_solve.py
import unittest
#from dolo.symbolic.symbolic import Variable,Parameter,TSymbol
#import pickle
class TriangularSolveCase(unittest.TestCase):
def test_solve_simple_system(self):
from dolo.misc.triangular_solver import triangular_solver
system = [
... |
# -*- coding: utf-8 -*-
"""
Copyright (c) 2020 tamalone1
"""
import cmath
from math import radians
from rotor_balancing.Rotor import Rotor
# Baseline reactions (length)
XA = cmath.rect(8.6, radians(63))
XB = cmath.rect(6.5, radians(206))
# Create Rotor instance with baseline reactions motions
rotor = Rotor(XA, XB)
# ... |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
import numpy as np
from scipy.spatial import cKDTree
from trackpy.utils import validate_tuple
def draw_point(image, pos, value):
image[tuple(pos)] = value
def feat_gauss(r, rg=0.333):
""" ... |
import numpy as np
from numpy import shape
from scipy import fftpack
class cos_basic:
'''
基础离散余弦变换类
'''
def __init__(self, matrix):
self.matrix = matrix
def do_cos(self):
data = fftpack.dct(fftpack.dct(self.matrix, axis=0, norm='ortho'), axis=1, norm='ortho')
return np.l... |
'''
===============================================================================
-- Author: <NAME>, <NAME>
-- Create date: 04/11/2020
-- Description: This codes is for detection and ecxtraction of
any text in wild range by MSER and SWT.
-- Status: In progress
======================... |
import os
import numpy as np
import scipy.io as sio
import pandas as pd
from openseapy.dataset import SNADataset
class CoreLoader:
"""
Core class for data loading.
"""
def __init__(self, amplify=1e12, time_row=None, sample_rate=None, use_generic_trace_id=True):
"""
Parameters
... |
import arcpy
import os
from itertools import takewhile
from scipy.spatial import Delaunay
import numpy as np
import matplotlib.pyplot as plt
import shutil # for deleting temp files, folders
import math
def createSubdir(workspace, subdirList):
for subdir in subdirList:
if not os.path.isdir(worksp... |
<filename>tracklib/analysis/neda/neda.py
"""
Main module of the neda inference package
This introduces the `Environment` class, which we use to facilitate repeating
tasks like running MCMC, calculating or estimating evidence. Finally, the
`main` function runs the whole scheme. Note that both of these are imported
into... |
#!usr/bin/python
"""
author : <NAME>
author : 18998712
module : Applied Mathematics(Numerical Methods) TW324
task : computer assignment 05 question 2
since : Friday-27-04-2018
"""
def composite_midpoint(f, m, a=0.0, b=1.0):
h = (b - a) / m
return h * sum([f((a+h/2.0) + i*h) for i in xrange(0, m)])
def... |
<reponame>zubba02/pyTri
######################################################################################
################### pyTri ###################
################### ###################
################### <NAME> Em... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 22 15:23:33 2019
Mean comparison
@author: salim
"""
#load basiclibraries
import os
import numpy as np
import pandas as pd
from pandas.api.types import CategoricalDtype #For definition of custom categorical data types (ordinal if necesary)
import mat... |
<reponame>carina-kauf/ngym_usage<filename>analysis/decomposition/jpca_utils.py
"""
The MIT License (MIT)
Copyright (c) 2020 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restrict... |
<reponame>chunglabmit/phathom
import numpy as np
from scipy.stats import poisson
import maxflow
import tqdm
from functools import partial
import multiprocessing
from phathom import utils
# import warnings # Leads to import errors with skimage.filters.gaussian
# warnings.filterwarnings("error")
def poisson_pdf(x, mu)... |
from __future__ import print_function
import keras
from keras import backend as K
import tensorflow as tf
import pandas as pd
import os
import pickle
import numpy as np
import scipy.sparse as sp
import scipy.io as spio
import isolearn.io as isoio
import isolearn.keras as iso
def load_data(batch_size=32, valid_se... |
<filename>ant_tracker/tracker/track.py
from dataclasses import dataclass
from enum import auto
import numpy as np
from memoized_property import memoized_property
from typing import Dict, List, NewType, Optional, Tuple, Type, TypeVar, TypedDict
from .blob import Blob
from .common import Color, ColorImage, FrameNumber,... |
"""
from keras.layers import Input
from keras.engine.topology import Layer
import scipy as sci
import numpy as np
from scipy.stats import bernoulli
import random
class DropConnect(Layer):
def __init__(self, input_dim, output_dim, p):
self.train = True
self.prob = p or 0.5
if self.prob >=... |
import numpy as np
from sklearn.model_selection import RepeatedStratifiedKFold, StratifiedShuffleSplit
from sklearn.linear_model import LogisticRegression
from sklearn.isotonic import IsotonicRegression
from scipy.special import expit
import matplotlib.pyplot as plt
from sklearn.metrics import f1_score
import ti... |
"""
Library of metrics for various purposes, including
quantifying the amount of association between confound and target,
degree of variability across different confound levels or groups,
degree of harmonization achieved (e.g. reduction in variance of means/medians)
"""
import numpy as np
from scipy import stats
fr... |
# These are all the modules we'll be using later. Make sure you can import them
# before proceeding further.
from __future__ import print_function
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import random
import numpy as np
import os
import sys
import tarfile
from IPython.display import display, Im... |
#2D
import numpy as np
x=np.arange(2,10).reshape(2,4) #(2,4)->(2*4) # Elements in 'arange'.
print(x)
#3D
import numpy as np
y=np.arange(24).reshape(4,3,2)
print(y)
#Append
import numpy as np
x=np.array([[10,20,30],[100,110,120]])
print('Array:',x)
x=np.append(x,[[40,60,50],[90,80,70]])
print("Append Array x:",x)
y... |
import numpy as np
import pandas as pd
import copy
from time import time
from typing import *
from sklearn.svm import SVC
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from scipy.spatial import distance
from scipy.stats import chisquare
from prettytable import PrettyTable
from project_libs import C... |
<reponame>oliverlee/antlia
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import pickle
import numpy as np
import scipy.signal
import matplotlib.pyplot as plt
import seaborn as sns
from antlia import filter as ff
from antlia import plot_braking as braking
from antlia import plot_steering as steering
from ant... |
<gh_stars>1-10
import os
import math
import re
import io
import cv2
import numpy as np
from scipy.optimize import linear_sum_assignment
import time
import base64
from IPython.display import clear_output, Image, display
from scipy.spatial import distance
class Tracker(): # Class to keep track of trackers
def __init... |
<gh_stars>1-10
# -*- coding: utf-8 -*-
"""
@author: abhilash
"""
# random Search for Algorithm Tuning
from pandas import read_csv
from sklearn.linear_model import Ridge
from sklearn.model_selection import RandomizedSearchCV
from scipy.stats import uniform
filename = 'pima-indians-diabetes.csv'
names = ['pre... |
<reponame>jorgemira/euler-py
'''Problem 5 from project Euler: Smallest multiple
https://projecteuler.net/problem=5'''
from fractions import gcd
RESULT = 232792560
def lcm(num1, num2):
'''Return least common multiple of two numbers'''
return num1 * num2 // gcd(num1, num2)
def lcmm(numbers):
'''Retur... |
import pickle
import numpy as np
from scipy import stats
breath_type="strong"
model_name="strong_multi_cnn-lstm_0"
list_test_acc=[]
list_test_eer_KNN=[]
list_test_eer_GMM=[]
with open('results/outputs/'+breath_type+'/list_test_acc_'+model_name, 'rb') as filehandle:
list_test_acc = pickle.load(filehand... |
import tensorflow as tf
from tensorflow import keras as tfk
import tensorflow.python.keras.backend as K
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.regularizers import l2
from tqdm import tqdm
from scipy.special import softmax
from matplotlib import pyplot as plt
from abc import ABC, abstr... |
<filename>utils/dataio.py
"""
Data in-out.
FUnctions that deal with input and output of data and conversion to tensors.
Most of the data in/out funcionality is gathered from library DLTK:
https://github.com/DLTK
"""
import SimpleITK as sitk
import os
import numpy as np
from utils.utils import resize_image
from keras.... |
<gh_stars>0
from sympy import S, Integral, sin, cos, pi, sqrt, symbols
from sympy.physics.vector import Dyadic, Point, ReferenceFrame, Vector
from sympy.physics.vector.functions import (
cross,
dot,
express,
time_derivative,
kinematic_equations,
outer,
partial_velocity,
get_motion_params... |
<reponame>albertometelli/remps
"""
Relative entropy policy model search
Reference: https://pdfs.semanticscholar.org/ff47/526838ce85d77a50197a0c5f6ee5095156aa.pdf
Idea: use REPS to find the distribution p(s,a,s') containing both policy and transition model.
Then matches the distributions minimizing the KL between the p ... |
<reponame>jackblandin/rlpomdp<filename>research/rl/env/discrete_mdp.py
# Core modules
import logging.config
# 3rd party modules
import gym
import numpy as np
from abc import ABC, abstractmethod
from gym.spaces import Discrete, Tuple
from scipy.optimize import linprog
class DiscreteMDP(gym.Env):
metadata = {'rend... |
import numpy as np
from skimage.transform import resize
from skimage.util import montage
from matplotlib import cm
import matplotlib.pyplot as plt
import imageio
from tqdm import tqdm
import os
import torch
import pandas as pd
import nibabel as nib
from scipy import stats
class Image3dToGIF3d:
"""
Displaying 3... |
# -----------------------------------------------------------------------------
# Copyright 2020 <NAME>
#
# 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 numpy as np
from scipy.optimize import fsolve
import matplotlib.pyplot as plt
hbar = 6.582*10**(-25) #GeV*s
me = 0.511*10**(-3) #GeV
mmu = 0.1056 #GeV
alpha = 1.0/137.0 #fine structure constant
mpi = 0.135 #GeV
mK = 0.495 #GeV
c = 3*10**8 #m/s
AU = 1.496* 10**11 #m
mu = 1.8*10**(-3) #GeV
md = 4.3*10**(-3) #GeV
... |
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
import sys
import numpy as np
from numpy import array
from qiskit import *
from E import *
from angles import *
from circuit import *
from state_dict import *
from b_values_data import *
from scipy.optimize import minimize
from custom_optimizers import *
#error_calls = []
#momenta_calls = []
#opt_energy = []
#opt_para... |
<reponame>john-qingwang/py_nodal_dg
import unittest
import numpy as np
import scipy.io as sp_io
import two_d.geometry as geo
class TestGeometry(unittest.TestCase):
"""Checks the correctness of functions in geometry.py."""
def setUp(self):
"""Initializes common variables in the test."""
supe... |
<gh_stars>1-10
################################################################################
"""
rhythm.py provides a mapping between alternate representations of rhythmic
values: fractions, rhythmic symbols, lists of the same or strings of the same.
A fraction is a ratio (or Fraction) of a whole note, e.g.
1/4=... |
import numpy as np
from keras.models import load_model
import scipy.cluster.hierarchy as shc
from sklearn.cluster import AgglomerativeClustering
import sys
sys.setrecursionlimit(10**6)
import matplotlib.pyplot as plt
sys.path.append('../BioExp')
from BioExp.helpers.metrics import *
from BioExp.helpers.losses import *
... |
<filename>examples/linhao_support.py
import csv
import logging as logger
import os
from _csv import writer as csv_writer
from collections import defaultdict
import numpy as np
import scipy
from matplotlib import pyplot as plt
import imagepipe.raw_functions
import imagepipe.tools.helpers
import imagepipe.wrapped_funct... |
<reponame>Yolanda-HT/Scribe-py
from tqdm import tqdm
import pandas as pd
import numpy as np
from scipy.sparse import isspmatrix
from .causal_network import cmi
CLR_DDOF = 1
def causal_net_dynamics_coupling(adata,
TFs=None,
Targets=None,
... |
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.ext.hybrid import hybrid_property
import statistics
from sqlalchemy import func
from .run import Run
from ..database import db
class Task(db.Model):
""" A task in a dataset. Usually associated with various runs. """
__table_args__ = (
db... |
<filename>visualization/viz_utils.py
import os
import numpy as np
from scipy.spatial.distance import mahalanobis
from sklearn.covariance import ShrunkCovariance
from sklearn.preprocessing import StandardScaler
import pandas as pd
from multiprocessing import Pool, Queue
def normalize_array_between(data, old_low, old_h... |
<filename>pystein/tests/test_utilities.py
"""Unittests for the Symbolic utilities Module
"""
from sympy import symbols, Matrix, Function, Derivative
from pystein import coords
from pystein import utilities
class TestUtilities:
"""Test utilities Module"""
def test_tensor_pow(self):
"""Test tensor po... |
import csv
import importlib
import os
import cv2
import numpy as np
from PIL import Image
from scipy import signal
import transforms
from tools import generate_sdfdi
def read_video(filename):
"""
Receives a filename of a video, opes the file and saves all concurrent frames in a list as ndarray
:param fi... |
<gh_stars>0
"""Functions for excising RFI."""
from __future__ import annotations
import h5py
import numpy as np
import warnings
import yaml
from astropy.convolution import Box1DKernel, convolve_fft
from cached_property import cached_property
from dataclasses import dataclass, field
from matplotlib import pyplot as plt... |
<gh_stars>0
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Central Pattern Generator model for teaching
# FvW 06/2020
import os
import sys
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import matplotlib.animation as animation
from matplotlib.animation import FuncAn... |
import numpy as np
import scipy as sp
from xfel.grid.optimize import DataSet
from xfel.utils import chunks
class GibbsSGD(object):
def __init__(self, likelihood, projection, quadrature,
data, prior=None, params=None,
eps=1e-3, decay_rate=1e-2,
batchsize=500):
... |
<reponame>mlund/scipp
# SPDX-License-Identifier: BSD-3-Clause
# Copyright (c) 2022 Scipp contributors (https://github.com/scipp)
# @author <NAME>, <NAME>
from fractions import Fraction
from typing import Dict, Iterable, List, Mapping, Set, Union
from ..core import DataArray, Dataset, DimensionError, VariableError, bi... |
<filename>code/preamble.py
import numpy as np
import pandas as pd
from scipy import stats
from scipy.interpolate import interp1d
import matplotlib.pyplot as plt
from tqdm import tqdm, tqdm_notebook
import random
from time import time as tictoc
from scipy.optimize import fmin
from scipy.optimize import minimize
from sci... |
import ot
import numpy as np
import torch
from copy import deepcopy
from tqdm import tqdm
import pandas as pd
from scipy.spatial.distance import cdist
from math import ceil
from apex import amp
import os,sys,inspect
current_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
urbangan_dir =... |
<reponame>solepomies/MAOOAM<gh_stars>10-100
"""
Tensor computation module
=========================
The equation tensor for the coupled ocean-atmosphere model
with temperature which allows for an extensible set of modes
in the ocean and in the atmosphere.
.. note :: These are calculated using ... |
"""
evaluation_config_batch.py
Author: <NAME>
Description:
This file implements an EvaluationConfig sub-class. In contrast to EvaluationConfigNormal,
this class keeps track of the maximum scores of batches of games played by the strategy provided
by the synthesizer and returns the average of the maximum scores as the... |
#!/usr/bin/python3
from os.path import join
from re import sub
import numpy as np
import matplotlib as ma
# ma.use("agg")
import matplotlib.pylab as plt
def readParameters(pathToSimFolder):
parameters = {}
electrodes = []
with open(join(pathToSimFolder, "in.txt")) as parameterFile:
for line in ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.