text string |
|---|
<reponame>hellodu-dev/team_schedule
# coding:utf-8
"""
<NAME>, <NAME>
May 15, 2017
修改 <NAME>
June 21, 2017
July 21,2017
"""
import math
import geopy.distance
import numpy as np
from scipy import inf
from sklearn.neighbors import NearestNeighbors
# 分割线左边判断角度的点和距离
leftCheckDirection = [30.610773, 104.040650]
# 分割线右边判断... |
# SE Lin
from sympy import Symbol
from sympy.abc import*
from sympy.logic.boolalg import to_cnf
from sympy.logic.boolalg import Not, And, Or
from sympy.logic.inference import satisfiable, valid
from mpmath import*
from itertools import product
import sys
from copy import deepcopy
from shutil import copyfile
from itert... |
<reponame>LukasBeddrich/ndatautils<filename>tests/test_utils_fit_beam_center.py
""" Script to test the 'fit_beam_center' method"""
import matplotlib.pyplot as plt
import numpy as np
import os
from lmfit import Model
from pprint import pprint
from sys import path
from scipy.stats import multivariate_normal
path_ndata... |
<reponame>WangPeng-Lab/scGCO_0910
import math
import random
import parmap
import itertools
from itertools import repeat
from scipy.spatial import distance
import operator
from tqdm import tqdm
from functools import reduce
from sklearn import mixture
import statsmodels.stats.multitest as multi
import networkx as nx
imp... |
<reponame>dntaylor/coffea
from .lookup_base import lookup_base
from ..util import awkward
from ..util import numpy
from ..util import numpy as np
from copy import deepcopy
from scipy.special import erf
from numpy import sqrt, log, log10, exp, abs
from numpy import maximum as max
from numpy import minimum as min
from ... |
import logging
import warnings
from typing import Tuple, Union
import anndata
import h5py
import numpy as np
import pandas as pd
import scipy.sparse as sp_sparse
from anndata._core.sparse_dataset import SparseDataset
from numba import boolean, float32, float64, int32, int64, vectorize
logger = logging.getLogger(__nam... |
import cv2
import matplotlib.pyplot as plt
import saliency_map.pySaliencyMap as pySaliencyMap
from saliency_map.helpFunctions import *
from saliency_map.regionBasedSegment import *
import numpy as np
from scipy import spatial
import matplotlib.pyplot as plt
import numpy as np
from skimage.filters.rank import entropy... |
# Copyright (c) 2020-2022, NVIDIA CORPORATION. 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 of source code must retain the above copyright notice, this list of
# c... |
import pandas as pd
import scipy.stats as st
ridge=pd.read_csv('results/ridge.tsv', index_col=0, sep='\t')
cnn=pd.read_csv('results/cnn.tsv', index_col=0, sep='\t')
ffn=pd.read_csv('results/ffn.tsv', index_col=0, sep='\t')
# print(ridge)
print()
print('Two sided t-test for paired samples (CNN vs Ridge):')
for var ... |
<gh_stars>1-10
# -*- coding: utf-8 -*-
# pylint: disable=invalid-name, too-many-arguments, bad-whitespace
# pylint: disable=too-many-lines, too-many-locals, len-as-condition
"""Copyright 2015 <NAME>.
FilterPy library.
http://github.com/rlabbe/filterpy
Documentation at:
https://filterpy.readthedocs.org
Supporting bo... |
<gh_stars>10-100
import os
import scipy.misc
import numpy as np
from datetime import datetime
from model import DCGAN
from utils import pp, visualize, to_json, show_all_variables
import utils
import tensorflow as tf
flags = tf.app.flags
flags.DEFINE_integer("epoch", 5, "Epoch to train [25]")
flags.DEFINE_float("lear... |
<gh_stars>0
from fractions import Fraction
def reduce(fraction):
num, den = fraction[0], fraction[1]
if num == den:
return [1, 1]
if num > den:
num, den = fraction[1], fraction[0]
return [
Fraction(num % den, den)._denominator,
Fraction(num % den, den)._nume... |
# internal data manipulations
import numpy as np # operate on data from the hdf5 file and image generation
import pandas as pd # Data frames from numpy arrays, especially for output
# image generation, manipulation, and analysis
import cv2
from matplotlib import path # dealing with voronoi facets polylines as paths... |
import math
from random import uniform
import numpy as np
from typing import Callable
from scipy import integrate
from scipy.special import roots_chebyt
# binary search for sample points that are distributed based on arc_length
from mule_local.rexi.pcirexi.gauss_cache import GaussCache
from mule_local.rexi.pcirexi.... |
#
# Copyright 2018, 2020 <NAME>
# 2018, 2020 <NAME>
# 2015-2016 <NAME>
#
# ### MIT license
#
# 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... |
import cmath
import math
import os
import pickle
import sys
import warnings
import numpy as np
from termcolor import colored as col
from src.mltoolbox.metrics import METRICS
def load_test_logs(test_folder_path, return_setup=True):
try:
with open("{}/.setup.pkl".format(test_folder_path), 'rb') as setup_f... |
from math import *
from fractions import *
def solve():
n, k, b = [int(x) for x in raw_input().split()]
v = (b*(b+1))/2
if n < v:
print -1
return
if n == v:
for i in xrange(1, b): print i,
print b
return
tmp = (k*(k+1))/2
tmp -= ((k-b)*(k-b+1))/2;
if tmp < n:
print -1
return
x = b+1
wh... |
<filename>SE3.py
"""
"""
from LieGroup import LieGroup
from LieGroupElement import LieGroupElement
from LieAlgebra import LieAlgebra
from LieAlgebraElement import LieAlgebraElement
from typing import List
import numpy as np
import scipy.linalg as sl
from SO3 import SO3, so3, SO3element, SO3element
import copy
class s... |
__author__ = '<NAME>'
import numpy as np
import scipy
from ..abstract_scale_factor import ScaleFactorABC
class LogScaleFactor(ScaleFactorABC):
def __init__(self, log_prior=None, log_prior_sigma=None):
super(LogScaleFactor, self).__init__(log_prior, log_prior_sigma)
self._sf = 0
self._lo... |
"""
Module for Principal Component Analysis.
Features:
* pca and kernel pca
* pca through singular value decomposition (SVD)
Author: <NAME> (copyright)
Date: 10/01/2012
e-mail: <EMAIL>
Modified by: <NAME> (sibt.ul.hussain dot gmail.com), date=01-01-2013
"""
import numpy as np... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from datetime import datetime
import tensorflow as tf
import numpy as np
from PIL import Image
from sklearn.metrics import confusion_matrix
from sklearn.metrics import average_precision_score
from sklearn.metri... |
<reponame>pan3rock/DisbaTomo
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
import argparse
from scipy.stats import gaussian_kde
import os
from objective_function import (ObjectiveFunctionDerivativeUsed, Forward)
import yaml
params = {'axes.labelsize': 14,
'axes.titlesize': 16,
... |
<filename>grasp_evaluator/grasp_evaluator.py
# Copyright (c) 2020 NVIDIA Corporation
# 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 r... |
<filename>train_adni_warp_adv.py
import argparse
import tqdm
import os
import pickle as pkl
import scipy as sp
import torch
from pprint import pprint
# from codebase import utils as ut
# from codebase.models.vae_relu import VAE3d, Siamese_Network
# from codebase.train import train, train3d, train3d_1,train3d... |
import numpy as np
import pdb
from .base import StructuredModel
from struntho.inference.maxmin_spmp_sequence import maxmin_spmp_sequence_p, maxmin_spmp_sequence_p2
from struntho.inference.sum_product_chain import sum_product_p
from struntho.inference._maxmin_spmp_sequence import maxmin_spmp_sequence_c, maxmin_spmp_se... |
import abc
try:
import anndata
except ImportError:
anndata = None
import batchglm.api as glm
import dask
import logging
import numpy as np
import pandas as pd
import scipy
import scipy.sparse
import sparse
from typing import Union
from .det import _DifferentialExpressionTestSingle, DifferentialExpressionTestWa... |
# ------------------------------------------------------------#
# All functions having to do with the ground go in this file #
# ------------------------------------------------------------#
import numpy as np
import scipy.interpolate as interpolate
import matplotlib.pyplot as plt
import VEHICLE
class Ground:
def ... |
import sys
sys.path.append('../')
from pathlib import Path
import time
import numpy as np
import scipy.optimize
import pickle
import matplotlib.pyplot as plt
from py_diff_pd.common.common import ndarray, create_folder
from py_diff_pd.common.common import print_info, print_ok, print_error, print_warning
from py_diff_p... |
<filename>spritstat/services/price.py
from dataclasses import dataclass
from decimal import Decimal
from enum import Enum, unique
import json
import logging
from statistics import mean, median
from typing import Dict, List, Tuple, Union, Optional
import urllib3
from spritstat import models
_LOG = logging.getLogger(_... |
# -*- coding: utf-8 -*-
import tensorflow as tf
import numpy as np
import scipy.misc as misc
import cv2
import matplotlib.pyplot as plt
from flowlib import read_flo, read_pfm
from data_augmentation import *
from utils import mvn
class BasicDataset(object):
def __init__(self, crop_h=320, crop_w=896, batch_size=4... |
<gh_stars>0
import warnings
from itertools import permutations
from math import isinf, isnan
import numpy as np
import pandas as pd
from scipy.stats import entropy, ks_2samp, spearmanr, SpearmanRConstantInputWarning
from sklearn.neighbors import KernelDensity
from sklearn.metrics import matthews_corrcoef, mean_square... |
import numpy as np
from numba import njit
import scipy as sp
import scipy.optimize as spo
from netket.stats import (
statistics as _statistics,
mean as _mean,
sum_inplace as _sum_inplace,
)
from netket.utils import (
MPI_comm as _MPI_comm,
n_nodes as _n_nodes,
node_number as _rank
)
from mpi... |
<filename>src/features/SparseInteractions.py
from itertools import combinations
import numpy as np
from scipy import sparse
from sklearn.base import BaseEstimator, TransformerMixin
class SparseInteractions(BaseEstimator, TransformerMixin):
def __init__(self, degree=2, feature_name_separator="_"):
self.de... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import numpy as np
from scipy import integrate
A = np.array([3.332, 1.862])
B = np.array([0.631, 1.218])
C = np.array([0.986, 0.238])
__all__ = ["calcHG",
"calcQ"]
def _calcW(alpha):
"""
Calculate W component.
Phi_i = W*Phi_iS + (1 - W)*Phi_iL; ... |
<filename>src/mdataframe/plots.py
import pandas as pd
import numpy as np
import scipy as sp
import math
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.gridspec as grid
from mpl_toolkits.axes_grid1 import make_axes_locatable
from cycler import cycler
def generate_heatmap_fig... |
# Copyright 2020 The constraintula 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
#
# Unless required by applicable law or agreed... |
import numpy as np
import csv
from scipy import signal
from scipy.signal import butter, filtfilt
import wget
import os
import time
import tensorflow as tf
from sklearn.utils import class_weight
from scipy.interpolate import CubicSpline
from scipy import ndimage
import argparse
# lib path
PATH = os.path.dirname(os.pat... |
import re
import sys
from io import BytesIO
from binascii import unhexlify
from collections import OrderedDict
from datetime import datetime, timedelta, date
from decimal import Decimal
from email.mime.text import MIMEText
from fractions import Fraction
from ipaddress import ip_address, ip_network
from uuid import UUID... |
<filename>s06_classes_intro/exercises/exp_apx.py
__author__ = 'ferrard'
# ---------------------------------------------------------------
# Imports
# ---------------------------------------------------------------
import cmath
import math
import numpy as np
# ---------------------------------------------------------... |
<reponame>sangillee/TPLSp<filename>evalTuningParam.py<gh_stars>1-10
import numpy as np
from scipy.stats import rankdata, spearmanr, pearsonr
import matplotlib.pyplot as plt
class evalTuningParam:
def __init__(self, TPLScvmdl, type, X, Y, compvec, threshvec, subfold = 0):
""" Evaluating tuning paramet... |
<gh_stars>1-10
"""Implementations of MCMC algorithms targetting continuous target
distributions
Rwmh is adaptive random-walk Metropolis-Hastings, the version presented in
<NAME>. and <NAME>. (2009). Examples of adaptive MCMC.
Journal of Computational and Graphical Statistics, 18(2):349–367.
Elliptical is e... |
import cv2
import os
import numpy as np
import sys
import skimage
from skimage.measure import label
from scipy.ndimage.filters import gaussian_filter
rt = '../intermediate_result/data/AIC20_track4/test-data/'
videos = os.listdir(rt)
wrt_fgmask = './data/mask_diff/'
if not os.path.exists(wrt_fgmask):
os.makedi... |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.4.2
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# %% jupyter={"outputs_hidden": false}
from sympy imp... |
<reponame>tushar-corbic/esda
"""
A-DBSCAN implementation
"""
__author__ = "<NAME> <<EMAIL>>"
import warnings
import pandas
import numpy as np
from libpysal.cg.alpha_shapes import alpha_shape_auto
from scipy.spatial import cKDTree
from collections import Counter
from sklearn.cluster import DBSCAN
from sklearn.neighbor... |
import time
startTime = time.time()
# read lines into a list
with open ('input', 'r') as input_file:
lines = []
for line in input_file:
lines.append( line.strip() )
## helper functions
def wait_for_next_departure( time_now, bus_line ):
return bus_line - ( time_now % bus_line )
def next_departur... |
import matplotlib.pyplot as plt
from astropy.io import ascii
from matplotlib import rcParams
import numpy as np
import seaborn as sns
from scipy import interpolate
#Useful functions ... speaking of which, I reccomend yg to add a file / module to that folder where all python modules are kept on your computer
#so you c... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# BCDI: tools for pre(post)-processing Bragg coherent X-ray diffraction imaging data
# (c) 07/2017-06/2019 : CNRS UMR 7344 IM2NP
# (c) 07/2019-present : DESY PHOTON SCIENCE
# authors:
# <NAME>, <EMAIL>
from matplotlib import pyplot as plt
import matplot... |
<filename>meta_learning_framework/meta_learning_model.py
import numpy as np
import pandas as pd
import statistics
from time import time
from tqdm import tqdm
from types import GeneratorType
import warnings
from sklearn.model_selection import cross_val_predict
from sklearn.preprocessing import OneHotEncoder
from sklear... |
#!/usr/bin/env python
# _*_ coding: UTF-8 _*_
import os
import cv2
import json
import torch
import codecs
import numpy as np
from scipy.io import wavfile
def crop_resize_gray_frame(frame, roi_bound=None, roi_size=(96, 96), gray=True):
if roi_bound is None:
cropped_frame = frame
else:
assert le... |
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats
errorbars_on = 1
linear_reg_on = 1
class graph:
x = []
y = []
x_u = []
y_u = []
graph_title = ""
x_title = ""
y_title = ""
name = ""
figure = 0
axis = 0
def __init__(self, x_data, y_data, X_unc, Y... |
# -*- coding: utf-8 -*-
"""
=========
PTC, SNR
=========
This code is used to characterize image sensors and cameras. More specifically, it focuses on two main parameters: firstly, the PTC (Photon Transfer Curve)
which allows us to calculate the Gain of the camera in e-/ADU, the FWC (Full Well Capacity) in e- and the... |
import dgl
import random
import torch
from torch.utils.data import *
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
from load_data import *
from utils import *
from model import *
from sensors2graph import *
import torch.nn as nn
import argparse
import scipy.sparse as sp
parser... |
<filename>scipy/linalg/tests/test_cython_lapack.py
from numpy.testing import TestCase, run_module_suite, assert_allclose
from scipy.linalg import cython_lapack as cython_lapack
from scipy.linalg import lapack
class test_lamch(TestCase):
def test_slamch(self):
for c in b'esbpnrmulo':
asser... |
<reponame>wrattler/wrattler
# Mainly text manipulation utils
from src.utils import create_folders
# Latex, and visualization utils
from src.utils import print_to_file, save_object
import csv
import numpy as np
import os
from src.Config import Config
from src.Model import PtypeModel
from src.PFSMRunner import PFSMRun... |
<filename>thesis-codes/bordes-re/experiment.py
#!/usr/bin/python
#number of relations = db.Features1.distinct("relation").length
#number of unique lefthandside+righthand side = db.Features1_externalRef.count()
#db.Features1.count()
import random
import math
import numpy as np
import scipy.sparse as sp
im... |
<reponame>Breeze1in1drizzle/MindLink-Exploring
'''
@date: 2021.03.09
@author: <NAME>
This file is for implementations of several kinds of Fourier Transform,
such as Fast Fourier Transform, Short-Time Fourier Transform and so on.
对于MAHNOB-HCI数据集来说,一个文件代表的是 119s 的数据采集。眼动数据集每秒60个样本,采样率60Hz。
其实是接近120s,但是第一秒没到60个,所以一般从第2s开始... |
<gh_stars>0
import numpy as np
import scipy
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import scanpy as sc
from matplotlib import colors
import sklearn
layer_to_color_map = {'Layer{0}'.format(i+1):sns.color_palette()[i] for i in range(6)}
layer_to_color_map['WM'] = sn... |
<filename>Robots/PUMA.py<gh_stars>0
#<NAME> : <EMAIL>
#19110192
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as p3
import sympy as sp
from .Tools import *
#Crude Stanford Maniulator without any logic
#Takes only torque as input and calculates other properties using... |
<filename>pyrfm/random_feature/tests/test_random_fourier.py
import numpy as np
from scipy.sparse import csr_matrix
from sklearn.utils.testing import assert_allclose_dense_sparse
from pyrfm import RandomFourier
from sklearn.metrics.pairwise import rbf_kernel
import pytest
# generate data
rng = np.random.RandomState(0)
... |
"""Estimate the oracle performance on the scruples corpus."""
import json
import logging
import click
import numpy as np
from scipy import stats
import tqdm
from .... import utils, settings
from ....data.labels import Label
from ....baselines.metrics import METRICS
logger = logging.getLogger(__name__)
# constant... |
"""Using transfer learning to predict one or more labels in a single domain.
"""
from .base import BaseBayesianTransfer
import numpy as np
from scipy import stats
from sklearn.exceptions import NotFittedError
from abc import abstractmethod
from functools import reduce
from operator import add
class BaseSingleDom... |
import numpy as np
from tinytag import TinyTag
from scipy.io.wavfile import read, write
import os, sys, csv
def get_duration(filename):
'''
reads song metadata ard returns duration
'''
return TinyTag.get(filename).duration
def guess_first_and_last_DownBeat(filename):
'''
Reads a .wav audio fil... |
import os
import cv2
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import interactive
import scipy
def rgb_min_image(image):
# extractes the min of the rgb values and outputs
# a gray scale image
rgb_image = np.amin(image, axis= 2)
return rgb_image
def min_filter(image):
# p... |
<gh_stars>1-10
import numpy as np
import scipy.linalg
from pirt import PointSet
if True:
# Precalculate a matrix for fitting a quadratic polynom to three points
# to find the subpixel maximum value in an 1D image.
# a x x + b x + c
_precalculated_A1 = np.matrix(" 1 -1 1; 0 0 1; 1 1 1") #... |
<reponame>cwood1967/SBEMimage<filename>src/acquisition.py
# -*- coding: utf-8 -*-
# ==============================================================================
# This source file is part of SBEMimage (github.com/SBEMimage)
# (c) 2018-2020 <NAME> Institute for Biomedical Research, Basel,
# and the SBEMimage de... |
"""Classes for building bridges and running simulations."""
import os
from enum import Enum
from itertools import chain
from timeit import default_timer as timer
from typing import List, Union, Tuple, Optional, Callable
import numpy as np
from matplotlib import cm as cm, colors as colors, pyplot as plt
from scipy.int... |
<gh_stars>1-10
# Created on 11/9/21 at 11:02 AM
# Author: <NAME>
import os
import scipy.stats
# import scipy.io.wavfile
# import soundfile as sf
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchvision.utils
import torchvision
from torch.autograd import Variab... |
from sympy.core.add import Add
from sympy.core.mul import Mul
from sympy.core.power import Pow
from sympy.core.symbol import Symbol
from sympy.core.basic import Basic, S
from sympy.core.numbers import Integer
from sympy.core.sympify import sympify
from sympy.core.numbers import igcd, ilcm
from polynomial import Poly,... |
"""The dialog for calculating minimal cut sets"""
import io
import traceback
import scipy
from qtpy.QtCore import Qt, Slot
from qtpy.QtWidgets import (QButtonGroup, QCheckBox, QComboBox, QCompleter,
QDialog, QGroupBox, QHBoxLayout, QHeaderView,
QLabel, QLineEdit... |
<filename>utils/test_dense_overlap.py
from .dense_overlap import compute_dense_overlap
from scipy.io import loadmat
import numpy as np
d = loadmat("dense_overlap.mat")
ofx, ofy = d['ofx'][0, 0], d['ofy'][0, 0]
stx, sty = d['stx'][0, 0], d['sty'][0, 0]
vsx, vsy = d['vsx'][0, 0], d['vsy'][0, 0]
dx1, dy1, dx2, dy2 = d[... |
## Copyright (C) 2019, <NAME> <<EMAIL>>.
## This program is licenced under the BSD 2-Clause licence
## contained in the LICENCE file in this directory.
import numpy as np
import os
from ivector_PLDA_OSI import iv_OSI
from ivector_PLDA_CSI import iv_CSI
from ivector_PLDA_SV import iv_SV
from gmm_ubm_OSI im... |
import json
import fire
import imageio
import numpy as np
import torch
from scipy.optimize import linear_sum_assignment
from torchvision.models.detection import fasterrcnn_resnet50_fpn
from torchvision.transforms.functional import to_tensor
def track(
video_path: str,
output_path: str = "out.json",
scor... |
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
import RT as rt
from scipy import signal
#plt.rcParams['xtick.top'] = plt.rcParams['xtick.labeltop'] = True
#lt.rcParams['xtick.bottom'] = plt.rcParams['xtick.labelbottom'] = False
## Ricker wavelet
vec2 = signal.ricker(100, 3)
nt = 512
nq = 25... |
<gh_stars>0
'''
Python interface file for pykodiak.so
<NAME>
Oct 2018
'''
import ctypes
import os
import numpy as np
from numpy.ctypeslib import ndpointer
from sympy import Mul, Expr, Add, Pow, Symbol, Number, sin, cos, atan
from sympy.parsing.sympy_parser import parse_expr
def get_script_path(filename):
'''ge... |
<filename>homogenous_transform.py
#!/usr/bin/env python
from sympy import symbols, cos, sin, pi, simplify, pprint
from sympy.matrices import Matrix
# Create symbols for joint variables
# The numbers 1 to 4 correspond to each rotation in the order specified to you.
q1, q2, q3, q4 = symbols('q1:5')
rtd = 180 / pi
dtr =... |
<gh_stars>1-10
# !/usr/bin/env python3
# -*- coding: utf-8 -*-
# Reference: https://github.com/12wang3/rrl
import os
import numpy as np
import shutil
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, TensorDataset
from torch.utils.data.dataset import random_split
from torch.utils.tensorboard ... |
"""
This module illustrates the Fraction object, useful for applications that
require accurate representations of integer fractions
"""
from fractions import Fraction
num1 = Fraction(1, 3)
num2 = Fraction(1, 7)
print(num1 * num2) # Fraction(1, 21)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# #########################################################################
# Copyright (c) 2018, UChicago Argonne, LLC. All rights reserved. #
# #
# Copyright 2018. UChicago Argonne, LLC. This ... |
<reponame>wavestate/wavestate-iirrational
"""
"""
from __future__ import division, print_function, unicode_literals
import numpy as np
import scipy
import scipy.signal
from wavestate.iirrational.utilities.np import logspaced
from wavestate.iirrational.utilities.mpl import mplfigB
from wavestate.iirrational.statespace ... |
<reponame>MattHartfield/CattleSDS<gh_stars>0
# 26th September 2018
# Python script for executing msprime simulations of Holstein demography,
# Calculate mean tip lengths to determine age range of mutations
# Execute with python3 MSP_Holstein.py 1000 > MSP_Results.dat
# (Results piped to STDOUT)
# Updated 18th Jan 2019... |
<reponame>sdurant/scikit-rf<gh_stars>0
'''
.. module:: skrf.media.freespace
========================================
freespace (:mod:`skrf.media.freespace`)
========================================
A Plane-wave in Freespace.
'''
from scipy.constants import epsilon_0, mu_0
from numpy import real, imag
from .distrib... |
"""Merge Grib2 RAP temps into netcdf file."""
import os
import datetime
import sys
import tempfile
import requests
import numpy as np
from scipy import interpolate
import pygrib
from pyiem.util import ncopen, utc, logger
from metpy.units import units
LOG = logger()
def main(argv):
"""Go Main Go"""
utcnow = ... |
import os
import numpy as np
import scipy.misc
# Call this script from the /train folder to compute label weights for training set
counter = 0
num_pixels_per_class = np.zeros(12)
def addFrequencyInFile(filename_full_path):
global num_pixels_per_class
img = scipy.misc.imread(filename_full_path)
assert img.dtype ... |
#
# pipeline that takes
# a galaxy healpix map
# a random healpix map
# a mask healpix map
# splits it if not provided
# does the linear/quadratic fit
# does a NN fit
#
# 1) run Lin fit, nnbar w weights, Cl w weights
# $> mpirun -np 2 python run_pipeline.py --verbose --hpfit linfit
# --nnbar nnbar... |
<filename>pco2box/model.py
import os
import numpy as np
import pylab as pl
import pandas as pd
from scipy.stats import linregress
import oceanbox
import co2sys
from .figures import plot_timeseries
DATADIR = os.path.join(os.path.dirname(__file__), "indata")
def calc_talk(salt, pref):
"""Calculate Total Alkali... |
<gh_stars>1-10
import plotly.graph_objects as go
from pandas import DataFrame
import numpy as np
from scipy import interpolate
def make_trace(
data,
opacity=0.9,
coloraxis="coloraxis",
lighting=dict(ambient=0.6, roughness=0.9, diffuse=0.5, fresnel=2),
surf_name="loss surface",
marker=dict(symb... |
import tensorflow as tf
import numpy as np
import gym
import util as U
import argparse
from scipy import signal
import os
import policies as pol
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--animate", default=False, action='store_true')
parser.add_ar... |
<reponame>Chachay/MPCC
import json, os, argparse
import numpy as np
import scipy as sp
import pandas as pd
from util.cubic_spline_path import CubicSplinePath
from controller.mpc_controller import SimModel, NMPC
from model.sim_model import VehicleSimModel
base_path = "../C++/Params/"
def load_param(file_name):
w... |
import rospy
import tf
from kuka_arm.srv import *
from trajectory_msgs.msg import JointTrajectory, JointTrajectoryPoint
from geometry_msgs.msg import Pose
from mpmath import *
from sympy import *
import numpy
import os
import pickle
import collections
import types
import traceback
import pprint
pp = pprint.PrettyPrint... |
<reponame>rantahar/tscfat
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 2 12:28:09 2020
@author: arsi
Functions for distance matrix and similarity matrix calculation.
"""
from scipy.spatial.distance import pdist, squareform
import numpy as np
from Source.Utils.argument_loader imp... |
<filename>car_racing/tests/lmpc_test.py<gh_stars>1-10
import pickle
import sympy as sp
import numpy as np
import random
from control.lmpc_helper import LMPCPrediction
from racing import offboard
from utils import base, racing_env
from utils.constants import *
def lmpc_racing(args):
if args["save_trajectory"]:
... |
<reponame>esantus/evalution2<gh_stars>1-10
'''
Created on Oct 4, 2012
@author: <NAME>, <NAME>
'''
import numpy as np
import logging
import scipy.linalg as splinalg
from sparsesvd import sparsesvd
from warnings import warn
from time import time
from math import sqrt
from composes.matrix.matrix import Matrix
from compo... |
import os
import matplotlib.pyplot as plt
import warnings
import logging
import numpy as np
from datetime import datetime, timedelta
from scipy import signal
from shapely.geometry import box, Point, LineString
from . import matfunc, timefunc
C = 299792458 # Vacuum speed of light
# https://ops.cresis.ku.edu/wiki/inde... |
<gh_stars>1-10
"""
Gaussian Model
"""
from typing import List, Tuple
import numpy as np
from numpy import ndarray
from scipy.stats import norm
from .model import Model
class GaussianModel(Model):
param_names = ("mu",)
default_param_specs = {"mu": {"inv_link": "identity"}}
def nll(self, params: List[nda... |
import os, requests
import scipy
fname = "stringer_spontaneous.npy"
url = "https://osf.io/dpqaj/download"
if not os.path.isfile(fname):
try:
r = requests.get(url)
except requests.ConnectionError:
print("!!! Failed to download data !!!")
else:
if r.status_code != requests.codes.ok:
print("!!! ... |
<filename>vision/generate_tile_dataset.py<gh_stars>1-10
#!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
import cv2
import scipy.ndimage
from PIL import Image, ImageDraw, ImageFont
import time
import os
import pickle
import seaborn
import argparse
def arguments():
parser = argparse.Argume... |
<reponame>RPGroup-PBoC/chann_cap
#%%
import os
import glob
import numpy as np
import scipy as sp
import pandas as pd
import re
import git
# Import matplotlib stuff for plotting
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib as mpl
# Seaborn, useful for graphics
import seaborn as sns
# I... |
import os
from contextlib import contextmanager
def save_fig(basename, figpath='.'):
import datetime
filename = 'figures/{}-{}.pdf'.format(basename, datetime.datetime.now().isoformat().replace(':', '-'))
import matplotlib.pyplot as plt
if not os.path.isabs(filename):
filename = os.path.join(fig... |
# %%[markdown]
# Author: <NAME>
#
# Email: [<EMAIL>](mailto:<EMAIL>)
# %%[markdown]
# Content:
# * Load Wisconsin's `doc2vec` document embeddings (from `https://xdd.wisc.edu/app_output/xdd-covid-19-8Dec-doc2vec.zip`)
# * Check overlap with EMMAA Covid-19 corpus
# * Reduce dimensionality and cluster
# * Output node an... |
# MIT License
# Copyright (c) 2020 Dr. <NAME>
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, pub... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.