text string |
|---|
from scipy.optimize import linear_sum_assignment
from scipy.spatial.distance import cdist
import utils
class Matcher(object):
"""Matches detected objects to existing ids."""
def __init__(self):
self.available_id = 0
def create_new_tracker(self, frame, rect, label):
return utils.create_tracker(frame, r... |
<filename>demo_MiddleBury_slowmotion.py
import time
import os
import re
from torch.autograd import Variable
import torch
import random
import numpy as np
import numpy
import networks
from my_args import args
from scipy.misc import imread, imsave
from AverageMeter import *
import shutil
torch.backends.cudnn.benchmark... |
#!/usr/bin/env python
# coding: utf-8
#$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$#
#$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$... |
from __future__ import print_function, absolute_import, division
import math
from pyKratos import *
from numpy import *
from scipy import linalg
def Create(Id, prop, list_of_nodes):
geom = line2d.Line2D(list_of_nodes)
return TemperatureNeumannFaceCondition(Id, prop, geom)
class TemperatureNeuma... |
<gh_stars>1-10
# -*- coding: utf-8 -*-
from numpy import sin, cos
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
import scipy.integrate as integrate
from timeit import default_timer as timer
start_timer = timer()
'''
Pendulum
Functions and parameters to change the ... |
<reponame>silencehero/snorkel
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from builtins import *
import math
from numbskull.inference import FACTORS
from scipy import sparse
from snorkel.learning.gen_learning impor... |
import numpy
import scipy.signal
from generate import *
def generate():
def process(up_factor, down_factor, x):
x_interp = numpy.array([type(x[0])()] * (len(x) * up_factor))
for i in range(0, len(x)):
x_interp[i * up_factor] = up_factor * x[i]
b = scipy.signal.firwin(128, 1 / u... |
<gh_stars>100-1000
import dill
import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from matplotlib import cm
from matplotlib import rcParams
rcParams['text.usetex'] = True
rcParams['text.latex.preamble'] = r'\usepackage{amsfonts}'
plt.figure(figsize=(6... |
<gh_stars>1000+
# Copyright 2020 The Cirq Developers
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... |
<filename>scripts/preprocessing/bcdi_read_BCDI_scan.py
#!/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>, <EMAI... |
import time
import argparse
from functools import partial
from multiprocessing import Pool, cpu_count
import h5py
import numpy as np
from numpy.lib import recfunctions
import scipy.optimize as opti
from scipy.interpolate import interp1d
import wf_func as wff
psr = argparse.ArgumentParser()
psr.add_argument('-o', des... |
import matplotlib
matplotlib.use('Agg') # use a non-interactive backend
import CoolProp
import os.path
web_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
tar_fil = os.path.join(web_dir, '_static', 'CoolPropLogo.png')
tar_fil_long = os.path.join(web_dir, '_static', 'CoolPropLogoLong.png')
tar_fil... |
import pySALESetup as pss
import scipy.special as scsp
import numpy as np
from collections import Counter
import matplotlib.pyplot as plt
plt.rcParams['text.usetex']=True
def normalPDF(x,mu,sg):
pdf = np.exp(-0.5*((x-mu)/sg)**2.)/np.sqrt(2.*np.pi*sg**2.)
return pdf
def normalCDF(x,mu,sg):
cdf = .5*(1.+scsp... |
from lib import Simulation
import numpy as np
from numpy import mean, min, max, median, quantile, sqrt
from matplotlib import pyplot as plt
from scipy.stats import expon, norm, erlang
from time import time
from math import factorial as fact
def std(values):
return np.std(values, ddof=1)
def mean_confidence_asympto... |
<reponame>PhysicsTeacher13/Mathematics_Dataset<filename>mathematics_dataset/sample/arithmetic.py<gh_stars>1000+
# Copyright 2018 DeepMind Technologies Limited.
#
# 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 o... |
<gh_stars>0
"""
Evaluate average block sensitivity for WSC.
"""
import traceback
from fairseq.models.roberta import RobertaModel
from examples.roberta.wsc import wsc_utils # also loads WSC task and criterion
from examples.roberta.wsc import wsc_task
#roberta = RobertaModel.from_pretrained('checkpoints', 'checkpoint_b... |
"""
The following code is under the MIT License.
Author: <NAME>, Github: IsaacSheidlower, Email: <EMAIL>
Affiliation: Tufts University, AABL Lab
"""
from operator import truediv
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from torch.distributions.normal import Normal
from sci... |
# sw: script used to scrape travel time data from Google API.
# No need to run the script for replication.
# TBD: need to set up the global environment variables.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import geopandas as gpd
import geoplot
from pysal.lib import weights
import networkx ... |
<reponame>RRibeiro8/koniq-loggy
from kuti import model_helper as mh
from kuti import applications as apps
from kuti import tensor_ops as ops
from kuti import generic as gen
from kuti import image_utils as iu
import pandas as pd, numpy as np, os
from scipy.io import loadmat
from matplotlib import pyplot as plt
from mun... |
import numpy as np
import astropy.io.fits as pf
from configobj import ConfigObj
# import ipdb
import matplotlib.pyplot as plt
import medis.speckle_nulling.sn_hardware as hardware
import medis.speckle_nulling.sn_preprocessing as pre
import medis.speckle_nulling.sn_processing as pro
import scipy.ndimage as sciim
import m... |
<filename>python/oxford_asl/roi_stats.py
#!/usr/bin/env python
"""
Generates perfusion stats within various ROIs
"""
import os
import sys
import argparse
import csv
import glob
from fsl.data import atlases
from fsl.data.image import Image
import fsl.wrappers as fsl
import nibabel as nib
import numpy as np
import scip... |
"""Additional functions used within the CARSpy program."""
from functools import wraps
import pickle
import numpy as np
try:
import matplotlib.pyplot as plt
from scipy.signal import find_peaks
_HAS_SCIPY_PYPLOT = True
except Exception:
_HAS_SCIPY_PYPLOT = False
def _ensureModules(function):
if _... |
import os
import re
import json
import pickle
import subprocess
import scipy
import numpy as np
import pandas as pd
from tabulate import tabulate
from sklearn.metrics.pairwise import cosine_similarity
from text_processing.tokenizer import get_custom_tokenizer
## StackOverflow Base URL
base_url = 'https://stackoverfl... |
from statistics import mean
RESULTS_ROOT = "/project/data/europarl/"
SOURCE_TEST = open(RESULTS_ROOT + "Europarlrev.de-en.de" , 'r', encoding='utf-8')
TARGET_TEST = open(RESULTS_ROOT + "Europarlrev.de-en.en" , 'r', encoding='utf-8')
print("Starting to process source file...")
sourcelength = []
targetlength = []
for ... |
<reponame>EdwardDixon/facenet<filename>src/temp_featurizer.py
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import numpy as np
import argparse
import facenet
import lfw
import os
import sys
import math
from sklearn import metrics
fr... |
# Copyright(c) 2014, The LIMIX developers (<NAME>, <NAME>, <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
#
#Unless required by applica... |
import tempfile
import subprocess
import shlex
import os
import numpy as np
import scipy.io
script_dirname = os.path.abspath(os.path.dirname(__file__))
def get_windows(image_fnames, cmd='selective_search'):
"""
Run MATLAB Selective Search code on the given image filenames to
generate window proposals.
... |
<gh_stars>1000+
# -----------------------------------------------------------------------------
# Copyright (c) 2009-2016 <NAME>. All rights reserved.
# Distributed under the (new) BSD License.
# -----------------------------------------------------------------------------
import numpy as np
from scipy.special import s... |
import numpy as np
from scipy import optimize
def TLS_logL(v, X, dX):
"""Compute the total least squares log-likelihood
This uses Hogg et al eq. 29-32
Parameters
----------
v : ndarray
The normal vector to the linear best fit. shape=(D,).
Note that the magnitude |v| is a stand-i... |
from PyQt5.QtWidgets import QWidget, QGridLayout, QVBoxLayout, QComboBox, QLineEdit, QLabel, QPushButton, QDialog, QCheckBox
from PyQt5.QtCore import Qt, pyqtSignal
from PyQt5.QtGui import QDoubleValidator
from PyQt5 import QtWidgets
import matplotlib
matplotlib.use('Qt5Agg')
from matplotlib.backends.backend_qt5agg i... |
<reponame>josepablocam/janus-public
import numpy as np
import pandas as pd
import lightgbm as lgb
from sklearn.model_selection import StratifiedKFold, GroupKFold, KFold
import matplotlib.pyplot as plt
from sklearn.metrics import log_loss
import seaborn as sns
import sklearn.preprocessing as pp
from scipy import opti... |
#!/usr/bin/env python
'''
hdp_scripts.py
Author: <NAME>
Date: 20 April 2018
A collection of functions that define a Gibbs sampler for a sticky hierarchical Dirichlet process hidden Markov model (see Emily Fox 2008) and the adjusted models for autoregressive and state space model data (see Fox 2009).
'''
import scipy... |
import pandas as pd
import numpy as np
from PIL import Image
from PIL import ImageOps
import PIL
import torch, torchvision
from torch.utils.data import Dataset, DataLoader
import matplotlib.pyplot as plt
from matplotlib import figure
import matplotlib.gridspec as gridspec
from ansim_dataset_unconf import ansimDataset, ... |
<reponame>forgi86/pyMPC<gh_stars>10-100
import numpy as np
import scipy as sp
import scipy.sparse as sparse
import osqp
class MPCController:
""" This class implements an MPC controller
Attributes
----------
x0 : array_like
Initial system state.
Ad : matrix_like
Discrete-time syste... |
<reponame>ddavid/pyImSegm
"""
Attempt to detect egg centers in the segmented images from annotated data.
The output is list of potential center candidates
Sample usage::
python run_center_evaluation.py -list none \
-segs "data-images/drosophila_ovary_slice/segm/*.png" \
-imgs "data-images/drosophi... |
"""MovieLens dataset"""
import numpy as np
import os
import re
import pandas as pd
import scipy.sparse as sp
import torch as th
from scipy.sparse import coo_matrix
import dgl
from dgl.data.utils import download, extract_archive, get_download_dir
from utils import to_etype_name
import pickle as pkl
import h5py
import ... |
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 27 17:31:34 2015
@author: Sarunya
"""
import sys
import numpy as np
from PIL import Image
from matplotlib import pyplot as plt
import scipy.ndimage
#from scipy.ndimage import filters
#import time
sys.setrecursionlimit(10000)
bs = 200
wd = 8 # theta_range=wd*wd*2
clmax ... |
import pandas as pd
import numpy as np
import csv
import math
import nltk
import scipy as sp
from scipy import signal
from scipy.signal import butter, lfilter, freqz, firwin,kaiserord
import matplotlib.pyplot as plt
import re
import os
import sys
''' this is the most corrected version of code!!!!!!!!!!!!!! 7/31'''
de... |
<filename>src/nugas/f2e0d1a/trivialwave.py
'''Dispersion relation for the symmetry preserving case
Author: <NAME> (UNM)
Ref: arXiv:1901.01546
'''
import numpy as np
from scipy.integrate import quad
from scipy.optimize import root, root_scalar, minimize_scalar
def _DR_func(K, Omega, G, int_opts={}):
'''The functio... |
<gh_stars>1-10
"""
This script is an example of how to use the random gaussian noise generator
module. |br|
This is the simplest example, with only one signal generated.
After the generation, spectrum fo the signal is analyzed with an Welch analysis
and ploted.
*Author*:
<NAME>, Aalborg University, Denmark. <<E... |
<reponame>gregorseiler/NTTRU<gh_stars>1-10
import numpy as np
import time
import sympy as sp
from mod_sqrt import modular_sqrt
from cube_root import cuberoots
def mod_invert(a,p):
# modular inverse. if there is no inverse, should return 0
return pow(a,p-2,p)
def evaluate(a,r,p):
#a simple evaluation function a(... |
"""The function to be optimized by scipy.optimize.minimize should return a scalar value. Please see here.
That being said, you can implement a for-loop and solve stress for each strain value. Afterward, you can take the sum of the stress values and minimize the sum.
Before that, you need to first re-structure your VOCE... |
from detection import Detection
import numpy as np
from scipy.spatial import distance
from skimage.feature import hog
def get_distance(v1,v2):
if(len(v1)==len(v2)):
dist = distance.euclidean(np.array(v1),np.array(v2))
else:
dist = -1
if(dist>1000):
dist=30
return dist
def ge... |
import numpy as np
import scipy
from scipy.stats import t
from tqdm import tqdm
import torch
from sklearn import metrics
from sklearn.svm import SVC
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from .util import mlp_f... |
<gh_stars>0
import numpy as np
from sklearn.svm import SVR
import matplotlib.pyplot as plt
from scipy.stats import multivariate_normal
from mpl_toolkits.mplot3d import Axes3D
from PIL import Image
from PIL import ImageOps
m = 2 #dimension
mean = np.zeros(m)
sigma = np.eye(m)
N = 100
x1 = np.linspace(-5, 5, N)
x2 = np... |
<filename>model_code/simulation_variance-of-ranking-quality.py
"""
Script for running simulations to record the variance of the quality of the rankings determined by the payments from some mechanisms in the continuous effort, biased agents setting.
@author: <NAME> <<EMAIL>>
"""
from numpy import ones
from statistics ... |
<reponame>JulianoLagana/MT3
from scipy.io import loadmat
import matplotlib.pyplot as plt
a = loadmat('data_association_task-1000samples-seed0.mat')
measurements = a['measurements'][0]
ground_truths = a['ground_truths'][0]
n_samples = len(measurements)
for i in range(100):
# Deal with weird way that saving to .m... |
import numpy as np
from numpy import linalg as la, random as rnd, testing as np_testing
from scipy.linalg import expm, logm
from pymanopt.tools.multi import (multiexp, multieye, multilog, multiprod,
multisym, multitransp)
from ._test import TestCase
class TestMulti(TestCase):
de... |
<gh_stars>1-10
"""
Scrit to compute the 1D peusdo wigner distribution in an one-dimensional hologram
dataset.
"""
import os
import time
import logging
from datetime import datetime as dt
from pathlib import Path
import scipy.io
import numpy as np
import multiprocessing as mp
# File name
script_name = os.path.basenam... |
# -*- coding: utf-8 -*-
"""
@author: <NAME>
@python_version: 3.6.4
"""
from scipy import signal as scisig
import numpy as np
import scipy.fftpack as scifft
import math
# ARTIFACTS REMOVAL
def remove_current_pulse_artifacts(sig, markers, window, n_draws, return_artifacts=False):
"""Remove current pulse artifacts fr... |
<gh_stars>0
import timeit
import statistics
# local module
import thingtotest
def test1():
results = timeit.repeat (stmt="thingtotest.main()", number=100, globals=globals())
minresult = min (results)
maxresult = max (results)
meanresult = statistics.mean (results)
print ("RESULTS:", results)
p... |
<gh_stars>0
# reference_metric.py: Define all needed quantities
# for a reference metric.
# Given uniform (reference metric) coordinate
# (xx[0],xx[1],xx[2]), you must define:
# 1) xxmin[3],xxmax[3]: Valid ranges for each
# uniform coordinate xx0,xx1,xx2
# 2) xxSph[3]: Spherical coordinate (r,the... |
"""Utitlites to reproduce synthetically degraded segmentation mask
with n% missing masks (false negavices), under- and over-segmented objects."""
import os
from copy import copy
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from matplotlib import colors as mpl_colors
f... |
"""
The physcalc module contains the routine that calculates the ionic
fraction and the NEI X-ray spectrum based on the physical conditions
in an ASCII file.
V0.1 - <NAME>, May 22, 2019: initial release
V0.2 - <NAME>, May 28, 2019: separate the CIE and NEI case
V0.3 - <NAME>, Jun 01, 2019: standardize for github uploa... |
#!/usr/bin/env python
'''
avoid target script
- identifies target cf
- sends other cfs to random heights or to static formation
- loads path for targetCF (trajectory or teleop)
- loops to check current position of targetCF relative to other present CFs
- adjusts accordingly to avoid collisions
#movements are control... |
from typing import Iterable, Optional, List, Tuple
import copy
import numpy as np
from scipy.linalg import expm
def generate_permutations(n_orbitals: int,
no_truncation: Optional[bool] = False):
qubit_orderings = [list(range(n_orbitals))]
for _ in range(n_orbitals // 2):
qubi... |
<gh_stars>10-100
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import glob
import re
import sys
import urllib
import tarfile
import zipfile
import os.path as osp
from scipy.io import loadmat
import numpy as np
import h5py
from scipy.misc import i... |
#!/usr/bin/python3
# Halide tutorial lesson 7
# This lesson demonstrates how express multi-stage pipelines.
# This lesson can be built by invoking the command:
# make tutorial_lesson_07_multi_stage_pipelines
# in a shell with the current directory at the top of the halide source tree.
# Otherwise, see the platform-sp... |
"""
A library for working with B-series.
We use the coefficient normalization that appears in
HLW (1.23), and in CHV2010 on the middle of p. 411.
"""
indices = 'jklmpqrstuvwxyz'
import sympy
h = sympy.Symbol('h')
y = sympy.Symbol('y')
import numpy as np
class BSeries(object):
def __init__(self, coeffs=None, F... |
<filename>gender recognition.py
#Dataset can be downloaded from:
# https://www.kaggle.com/primaryobjects/voicegender
#Method 1 to import the file
#import csv
#f= open("voice.csv", "rb")
#reader = csv.reader(f)
#for row in reader:
# print row
... |
<filename>exec/9-3-1.py
# 多変量正規分布はベクトルが従う分布と考えることができる。
# そのためStanで扱う場合はベクトルとmatrixを使って表現する。
import numpy as np
import seaborn as sns
import pandas
import matplotlib.pyplot as plt
from matplotlib.figure import figaspect
from matplotlib.gridspec import GridSpec
import mcmc_tools
from scipy.stats import norm
import time
... |
<reponame>blueturtle1134/oba-war-bot
import json
import time
from math import sqrt, dist
from scipy.spatial import ConvexHull, QhullError
from matplotlib import Path
TIME_FACTOR = 600 # Seconds to fly one unit
FUEL_FACTOR = 1 # Fuel to fly one unit
TANK_SIZE = 10 # Maximum fueling level
planes = list()
fuels = dic... |
#! /usr/bin/env python
#
# Copyright 2020 California Institute of Technology
#
# EMIT Radiometric Calibration code
# Author: <NAME>, <EMAIL>
import scipy.linalg
import os, sys
import numpy as np
from spectral.io import envi
import json
import logging
import argparse
from fpa import FPA, frame_embed, frame_extract
de... |
<reponame>waveform80/lightwave<filename>tests/compat.py
# vim: set et sw=4 sts=4 fileencoding=utf-8:
#
# The colorzero color library
#
# Copyright (c) 2018 <NAME> <<EMAIL>>
#
# SPDX-License-Identifier: BSD-3-Clause
import cmath
# Back-ported from python 3.5; see
# github.com/PythonCHB/close_pep/blob/master/is_close.p... |
"""This module houses the ways to specify a metric, and sample solutions to compute it's value.
Metrics are a useful abstraction which given the state of the circuit compute some
classical value which we need to interpret or plot.
"""
import abc
import typing
import numpy as np
import sympy
import warnings
warnings... |
"""Tests for tools and arithmetics for monomials of distributed polynomials. """
from sympy.polys.monomials import (
itermonomials, monomial_count,
monomial_mul, monomial_div,
monomial_gcd, monomial_lcm,
monomial_max, monomial_min,
monomial_divides,
Monomial,
)
from sympy.polys.polyerrors impo... |
<reponame>schonkopf/clickdata_visualization<filename>data_processing.py
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
import matplotlib.pyplot as plt
from scipy.stats import entropy
from sklearn.neighbors import KernelDensity
import os
import copy
from soundscape_I... |
<filename>example/app.py
#!/usr/bin/env python
#from threading import Lock
from flask import Flask, render_template, session, request
from flask_socketio import SocketIO, emit, disconnect#, join_room, leave_room, close_room, rooms
import scipy.io.wavfile
import numpy as np
from collections import OrderedDict
import sy... |
<gh_stars>1-10
#!/usr/bin/env python
#-*- coding: utf-8 -*-
from decimal import Decimal
from statistics import mean, stdev
import sys
import os
ALS = ["jcall", "jmp", "iCi"]
FSCORE = False # True
OVERHEAD = False # True
IGNORE = []
IGNORE = ["SPEC2006", "SPEC2006_save"]
IGNORE = ["fp", "int", "overhead"]
OPTI_LVL = [... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Package: mesxr.calibration
Module: trimscan
Author: <NAME>
Affiliation: Department of Physics, University of Wisconsin-Madison
Last Updated: November 2018
Description:
This module is a significant overhaul to the overiginal ME-SXR calibration software. The
goal... |
import numpy as np
import re as re
from scipy import stats
import gnc
import netCDF4 as nc
import copy as pcopy
import pdb
import pb
import pandas as pa
def Dic_DataFrame_to_Excel(excel_file,dic_df,multisheet=False,keyname=True,na_rep='', cols=None, header=True, index=True, index_label=None):
"""
Write a dicti... |
import numba
import numpy as np
from scipy.ndimage import convolve1d
from immutabledict import immutabledict
import strax
import straxen
export, __all__ = strax.exporter()
@export
@strax.takes_config(
strax.Option('coincidence_level_recorder_nv', type=int, default=4,
help="Required coincidence l... |
"""
@author: <NAME>
Animation for understanding rotating phasors, negative frequency in DSP concepts
Add, remove, or modify signals in rotating_phasors
Script will animate the individual phasors and the combined output in both rectangular and polar plots
Press any keyboard key to pause the animation
"""
# @todo
# re... |
#!/usr/bin/python
#
#
# Copyright (c) 2013, Georgia Tech Research 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 copyrigh... |
import copy
import numpy as np
from .grid import Grid, CachedData
try:
from numpy.lib import NumpyVersion
numpy115 = NumpyVersion(np.__version__) >= "1.15.0"
except ImportError:
numpy115 = False
if not numpy115:
def flip_numpy115(m, axis=None):
"""Provide same behavior for np.flip since nump... |
<reponame>fmi-basel/zinneretal-methods
import itertools
import luigi
import numpy as np
import os
import matplotlib.pyplot as plt
from scipy.signal import convolve2d
from skimage.graph import route_through_array
from skimage.morphology import medial_axis
from scipy.ndimage.morphology import distance_transform_edt
from... |
# Copyright 2020 The Magenta 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 to in ... |
import numpy as np
import pytest
import sympy
from openfermion import QubitOperator
from scipy.linalg import fractional_matrix_power
from zquantum.core import circuits
from zquantum.core.circuits import XX, YY, ZZ, Circuit
from zquantum.core.evolution import (
_generate_circuit_sequence,
time_evolution,
tim... |
from __future__ import division
import logging
from itertools import combinations
from collections import namedtuple
import numpy as NP
import scipy.stats
logger = logging.getLogger('pyrsss.stats.linregress')
"""Linear regression assessment metrics""",
Assessment = namedtuple('Assessment',
... |
#!/usr/bin/env python
# coding: utf8
#
# Copyright (c) 2020 Centre National d'Etudes Spatiales (CNES).
#
# This file is part of CARS
# (see https://github.com/CNES/cars).
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obta... |
from cmath import log
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.font_manager as font_manager
import tqdm
######################################################################################################################################################
#Settings for plotting
#####... |
<reponame>fperignon/sandbox<gh_stars>0
# Mechanics IO
"""Run a pre-configured Siconos "mechanics" HDF5 file."""
from __future__ import print_function
import os
import sys
from math import cos, sin, asin, atan2
from scipy import constants
import numpy as np
import h5py
import bisect
import time
import numbers
import... |
import inflect
import numpy as np
from scipy.signal import argrelextrema
from scipy.ndimage.filters import gaussian_filter1d as gf
class Shld_state(object):
""" detect the shoulder state.
So far, we detect 1. shoulder rotate 2. shoulder up-and-down.
"""
def __init__(self):
self.ngcnt = 0... |
<filename>pmd_beamphysics/units.py
"""
Simple units functionality for the openPMD beamphysics records.
For more advanced units, use a package like Pint:
https://pint.readthedocs.io/
"""
import scipy.constants
m_e = scipy.constants.value('electron mass energy equivalent in MeV')*1e6
m_p = scipy.constants.value(... |
from __future__ import division, print_function
from typing import List
import numpy
import scipy
class LinearRegression:
def __init__(self, nb_features: int):
self.nb_features = nb_features
def train(self, features: List[List[float]], values: List[float]):
# creating f(x) = W0 + sum((Wd)(Xd... |
from vision import features
import Image
from scipy.io import savemat as savematlab
im = Image.open("/scratch/vatic/syn-bounce-level/0/0/0.jpg")
f = features.hog(im)
savematlab(open("features.mat", "w"), {"py": f})
|
"""This is the problem presented in section 7 of:
Betts, <NAME>. and Huffman, <NAME>. "Large Scale Parameter Estimation
Using Sparse Nonlinear Programming Methods". SIAM J. Optim., Vol 14, No. 1,
pp. 223-244, 2003.
"""
from collections import OrderedDict
import numpy as np
import sympy as sym
import matplotlib.pypl... |
"""HiGHS Linear Optimization Methods
Interface to HiGHS linear optimization software.
https://www.maths.ed.ac.uk/hall/HiGHS/
.. versionadded:: 1.5.0
References
----------
.. [1] <NAME> and <NAME>. "Parallelizing the dual revised simplex
method." Mathematical Programming Computation, 10 (1), 119-142,
... |
import numpy as np
from math import acos, sqrt
from scipy.stats import pearsonr
def calc_correlations(df):
correlations = df.groupby(['spec_id', 'ion'])[['target', 'prediction']].corr().iloc[::2]['prediction']
correlations.index = correlations.index.droplevel(2)
correlations = correlations.to_frame().reset_index()... |
import operator
from functools import reduce, singledispatch
from sympy.core.expr import Expr
from sympy.core.singleton import S
from sympy.matrices.expressions.hadamard import HadamardProduct
from sympy.matrices.expressions.inverse import Inverse
from sympy.matrices.expressions.matexpr import (MatrixExpr, MatrixSymbo... |
#
# Copyright (c) 2017, Massachusetts Institute 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 of source code must retain the above copyright notice, this
# list o... |
import cv2
import os
import numpy as np
from scipy import ndimage
DEBUG = False
def set_debug(debug):
global DEBUG
DEBUG = debug
def wider_than(contour, min_width):
""" Returns True if contour is wider than min_width."""
x, y, w, h = cv2.boundingRect(contour)
return w > min_width
def move_bo... |
#
# Log-likelihood functions
#
# This file is part of PINTS (https://github.com/pints-team/pints/) which is
# released under the BSD 3-clause license. See accompanying LICENSE.md for
# copyright notice and full license details.
#
from __future__ import absolute_import, division
from __future__ import print_function, un... |
import numpy as np
import PR_CON
import Plant
import Signal_Generator
import math
import matplotlib.pyplot as plt
import pysnooper
from scipy.fftpack import fft
class InverterEnv(object):
viewer = None
action_bound = [0.1,120,0.1,120,0.1,120,0.1,120,0.1,120]
goal = 220
state_dim = 5
action_dim = 10... |
from audio_reader import Audio_Reader
import sys
import numpy
import scipy
import pylab
def is_Prime(n):
"""
Check if a number is prime.
"""
# make sure n is a positive integer
n = abs(int(n))
# 0 and 1 are not primes
if n < 2:
return False
# 2 is the only even prime numbe... |
from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
import torchvision.transforms as transforms
import torchvision.models as models
import copy
import os
import t... |
import pytest
import scipy.optimize as sopt
import scipy.sparse as sp
import numpy as np
from numpy.testing import assert_array_almost_equal
from nnls import block_pivoting, lawson_hanson
def test_block_pivoting():
# design matrix size (square)
n = 100
# -------------------------------------------------... |
<reponame>EzzEddin/bayesloop
#!/usr/bin/env python
"""
Transition models refer to stochastic or deterministic models that describe how the time-varying parameter values of a
given time series model change from one time step to another. The transition model can thus be compared to the state
transition matrix of Hidden M... |
import copy
from aerosandbox.visualization import *
from aerosandbox.tools.miscellaneous import *
from aerosandbox.tools.casadi_tools import *
try:
from xfoil import XFoil
from xfoil import model as xfoil_model
except ModuleNotFoundError:
pass
class AeroSandboxObject:
def substitute_solution(self, ... |
<filename>definitions_exercises.py
# -*- coding: utf-8 -*-
"""
Created on Sat May 04 14:20:51 2013
@author: VHOEYS
"""
#Load packages for calculation and making plots
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
#IMPORT NORMAL DISTRIBUTION:
from scipy.stats impor... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.