text
string
# -*- coding: utf-8 -*- """ A script for generating initial conditions for an axisymmetric protoplanetary disc, assuming an isothermal equation of state and steady-state. Please note, as long as the previous steps have been completed, you can start at any step Look carefully at the settings saved in settings_file (by...
<filename>server.py import io import socket import struct from PIL import Image from datetime import datetime import scipy.ndimage as ndi def run_server(): # Start a socket listening for connections on 0.0.0.0:8000 (0.0.0.0 means # all interfaces) server_socket = socket.socket() server_socket.bind(('0...
import numpy as np import pydrake.solvers.mathematicalprogram as mp from scipy.sparse import csc_matrix from scipy.sparse.linalg import lsqr """ QP: min. 1 / 2 * z.dot(Q).dot(z) + b.dot(z) s.t. G.dot(z) <= e """ class QpDerivativesKktPinv: def __init__(self): self.n_z = 0 # number of decision variables....
from scipy.stats import pearsonr def calculate_corr(seq_i, seq_j): if len(seq_i)>=len(seq_j): longer_signal=seq_i shorter_signal=seq_j else: longer_signal=seq_j shorter_signal=seq_i LD=len(longer_signal) LK=len(shorter_signal) corr=[] for a in ran...
#coding:utf-8 from typing import Callable, Iterable, Iterator, Tuple, Union, Generic, TypeVar from numpy import ndarray from scipy.sparse.base import spmatrix T = TypeVar("T") # Alias for return types R = TypeVar("R", contravariant=True) newaxis = None NoneType = type(None) class SparseMatrix(Generic[T], spmatrix): ...
import torch from torch import nn from torch import optim from model.model_preprocessing import Preprocess from model.model_encoder import pulsar_encoder from model.model_tcn_multi import TemporalConvNet_multi from model.model_output import OutputLayer from model.model_multiclass import MultiClass try: from model.m...
''' This script creates json files which can be used to render QQ plots. ''' # TODO: share the list `variants` with Manhattan and top_{hits,loci}. # TODO: make gc_lambda for maf strata, and show them if they're >1.1? # TODO: copy changes from <https://github.com/statgen/encore/blob/master/plot-epacts-output/make_qq_j...
<gh_stars>10-100 import os import pickle import numpy as np import tmap as tm from annoy import AnnoyIndex from faerun import Faerun from scipy.spatial.distance import cosine as cosine_distance import matplotlib.pyplot as plt CFG_TMAP = tm.LayoutConfiguration() CFG_TMAP.k = 50 CFG_TMAP.kc = 50 CFG_TMAP.sl_scaling_min ...
r"""@package motsfinder.axisym.trackmots.optimize Functions to perform various MOTS optimizations during tracking. The main optimization performed here is the numerical search for close to optimal bipolar coordinate parameters. """ import numpy as np from scipy.interpolate import lagrange from ..curve import Bipola...
<reponame>IDKiro/dnd-submit-pytorch<gh_stars>1-10 import numpy as np import os import h5py import scipy.io import math import skimage import cv2 import random import time import matplotlib.pyplot as plt from scipy.ndimage.filters import convolve import pyximport; pyximport.install() from .tone_mapping_cython import CR...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from mm.models import MeshModel from mm.utils.opengl import Render from mm.optimize.camera import estimateCamMat, splitCamMat import mm.optimize.image as opt from mm.utils.mesh import calcNormals, generateFace, generateTexture, barycentricReconstruction from mm.utils.trans...
# -*- coding: utf-8 -*- from scipy.stats import rv_continuous from scipy.stats import rv_discrete from scipy.stats import _continuous_distns as crv_helper from scipy.stats import _discrete_distns as drv_helper import scipy.special as special import numpy as np import matplotlib.pyplot as plt def plothistogram(values...
<reponame>JPLMLIA/OWLS-Autonomy<filename>src/helm_dhm/simulator/utils.py """ Utility functions for HELM simulator """ import json import logging import os.path as op import numpy as np from scipy import stats VALID_CONFIG_DISTS = ['truncnorm'] VALID_CONFIG_SHAPES = ['gaussian', 'airy_disk'] def create_dist_objs(**k...
import torch.nn.functional as F import numpy as np from options.train_options import TrainOptions from utils.timer import Timer import os from data import CreateSrcDataLoader from data import CreateTrgDataLoader from model import CreateModel #import tensorboardX import torch.backends.cudnn as cudnn import torch from to...
<gh_stars>10-100 """ The algorithms used here can be found in: <NAME> and <NAME>, "The BOSARIS Toolkit: Theory, Algorithms and Code for Surviving the New DCF"", 2013, https://arxiv.org/abs/1304.2865 """ import numpy as np from scipy import stats from scipy.special import expit as sigmoid from .pav_ro...
import logging from typing import Any, Optional, Union, List, Collection, Dict, Tuple, Callable import itertools from copy import deepcopy import textwrap # these imports need to be here so that ask_for_eval works import numpy as np import scipy as sp from simulacra import units as u logger = logging.getLogger(__nam...
<reponame>kkkkv/tgnms #!/usr/bin/env python3 # Copyright 2004-present Facebook. All Rights Reserved. import dataclasses import json import logging from statistics import mean from typing import Dict, Optional from terragraph_thrift.Controller.ttypes import IperfTransportProtocol @dataclasses.dataclass class ParsedI...
<filename>fair_ssl/methods/lfvae.py import tensorflow as tf import numpy as np from tqdm import tqdm from tf_utils import logger import pickle as pkl import os # from .vfae import VariationalFairClassifier, VariationalFairAutoEncoder from .vae import VariationalAutoEncoder from utils import demographic_parity, equalize...
#!/usr/bin/env python3 """Extract cities from OSM. It required the xml extracts: for F in central-america-latest.osm.pbf australia-oceania-latest.osm.pbf south-america-latest.osm.pbf africa-latest.osm.pbf asia-latest.osm.pbf north-america-latest.osm.pbf europe-latest.osm.pbf; do osmosis --read-pbf ${F} --tf accept-no...
<filename>fruits/elderberries/benchmarks2018/figures.py from collections import Counter from itertools import groupby FONTSIZE = 15 import matplotlib matplotlib.use('Agg') matplotlib.rc('font', size=FONTSIZE) from matplotlib import pyplot as plt from matplotlib.ticker import MaxNLocator from numba import njit import ...
<reponame>jlehrer1/comparative-organoids import random import pathlib import os import argparse import ast from itertools import product import numpy as np from scipy.stats import loguniform def run_search( N: int, class_label: str, ) -> None: """ Runs hyperparameter search by scaling i GPU jobs...
<gh_stars>0 """ Import needed modules """ "-----------------------------------------------------------------------------" import numpy as np import cantera as ct from math import exp, pi from scipy.optimize import fsolve from Shared_Funcs.pem_pak import * from scipy.sparse import coo_matrix from Shared_Funcs.pe...
<reponame>clazaro/Kratos import KratosMultiphysics as KM import KratosMultiphysics.ShallowWaterApplication as SW import KratosMultiphysics.KratosUnittest as KratosUnittest from KratosMultiphysics.process_factory import KratosProcessFactory import os try: import numpy missing_numpy = False except ImportError: ...
<gh_stars>0 from __future__ import division import numpy as np import matplotlib.pyplot as plt import scipy.optimize as op # Hypothesis def Hypothesis(X,theta): a=np.dot(X,theta) sigmoid=1/(1+np.exp(-a)) return sigmoid # cost function def costFunction(theta,X,Y): hypothesis=Hypothesis(X,theta...
<filename>post_scripts/animate_saved_data.py # -*- coding: utf-8 -*- """ Created on Thu Feb 6 08:46:59 2020 @author: Tom """ import pybamm import openpnm as op import matplotlib.pyplot as plt import ecm import os from scipy import io import numpy as np plt.style.use('default') plt.close("all") pybamm.set_logging...
<gh_stars>1-10 # -*- coding: utf-8 -*- import sys; sys.path.insert(1,'../') from firefly import * from numpy.random import randint, normal import networkx as nx import numpy as np import csv from tqdm import trange, tqdm from scipy import stats, io import collections import math from kuramoto import * import pandas as ...
<gh_stars>1-10 # --- built in --- import os import sys import time import json import logging import unittest # --- 3rd party --- import numpy as np import tensorflow as tf from scipy import stats as sp_stats from parameterized import parameterized # --- my module --- from unstable_baselines.lib import prob from tes...
import argparse from typing import Text import struct import os import numpy as np import onnx import caffe2.python.onnx.backend as backend import magic from scipy.io.wavfile import read import imageio __author__ = "<NAME> (University of Tuebingen, Chair for Embedded Systems)" supported_file_types = ['audio/x-wav',...
<reponame>Koeng101/colony_picker<filename>colony_picker/utils.py<gh_stars>1-10 from typing import Any, Optional import textwrap from scipy.spatial.transform import Rotation import random import cv2 import numpy as np def print_describe(name: str, item: Any): """Print an item with a description, where the item is ...
<gh_stars>1-10 import numpy as np import scipy.optimize from .c_fastpixelint import pixelintegrate from .integrate import radintpix, azimintpix, radint_nsector from .. import misc from ..misc.basicfit import findpeak_asymmetric from ..misc.errorvalue import ErrorValue def findbeam_gravity(data, mask): """Find be...
<reponame>thomasarmstrong/sstcam-simulation<filename>sstcam_simulation/camera/tests/test_pulse.py from sstcam_simulation.camera.pulse import ReferencePulse, GenericPulse from sstcam_simulation.camera.constants import CONTINUOUS_READOUT_SAMPLE_WIDTH import numpy as np from scipy.stats import norm import pytest classes...
### electoral crime and performance paper # judicial decisions script # this script wrangles the judicial decisions downloaded from the tse # website. we use the textual info in the sentences to determine the # (class) allegations against individual candidates running for office # author: <NAME> # by <EMAIL> # impo...
<gh_stars>0 ##Exploring 2D GMM's (Multi-dimensional) ##not perfectly implemented - clusters don't seem to separate nicely import matplotlib.pyplot as plt from matplotlib import style import numpy as np from scipy.stats import norm from scipy.stats import multivariate_normal import argparse import pandas as pd import ra...
import datetime import pickle #import bz2 from statistics import mean def predict(cat, weeks): if cat == 0: # data = bz2.BZ2File("ads_app\data\model_baju.pbz2", 'rb') # model = pickle.load(data) model = pickle.load(open("ads_app\data\model_baju.sav","rb")) elif cat == 1: model = p...
<filename>statest/quantile/some_distributions.py from scipy.stats import norm, lognorm, expon, lomax, weibull_min, fisk import numpy as np def rvs_fn1(n): return norm.rvs(10, 1, size=n) def rvs_fn2(n): return lognorm.rvs(1, 0, size=n) def rvs_fn3(n): return np.random.exponential(size=n) def rvs_fn4(...
<filename>InputPipeline/ContourAwareDataset.py import os.path from InputPipeline.base_dataset import BaseDataset, get_params, get_transform, get_downscale_transform from InputPipeline.image_folder import make_dataset from PIL import Image import torchvision.transforms as transforms import numpy as np import torch impor...
# -*- coding: utf-8 -*- """ Evaluate intra-class correlation coefficients (ICC) for each radiomics feature by comparing extractions from each set of segmentations (e.g. normal, eroded, dilated segmentations). Not for clinical use. SPDX-FileCopyrightText: 2021 Medical Physics Unit, McGill University, Montreal, CA...
<filename>scripts/thickness_load_h5.py import os import h5py import matplotlib.pyplot as plt from pathlib import Path from time import time, strftime from glob import glob import pandas as pd import numpy as np import scipy.ndimage as ndi import argparse from rabbitccs.data.utilities import load, save, print_orthogon...
#!/usr/bin/env python """ radarData.py This file holds the RadarData class that hold the radar data and processes it. @author: <NAME> """ import ipdb import scipy as sp # My modules from isrutilities.physConstants import v_C_0, v_Boltz from SimISR import Path from SimISR.IonoContainer import IonoContainer from SimISR....
# Extra evaluation functions for additional ML tasks import pandas as pd import numpy as np import pickle import os from pathlib import Path from cvss import CVSS2 from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, precision_recall_curve, auc, matthews_corrcoef from xgboost import XGBC...
import medis.speckle_nulling.sn_preprocessing as pre import cv2 import os import matplotlib.pyplot as plt import astropy.io.fits as pf import ipdb import medis.speckle_nulling.sn_math as snm import numpy as np from configobj import ConfigObj import medis.speckle_nulling.sn_filehandling as flh import medis.speckle_nulli...
#!/usr/bin/env ipython import pandas as pd from scipy import signal def filter_signal(data, nSamples = 1000, frameSize = 40e-9): '''Butterworth filter of signal.''' fs = float(nSamples)/frameSize # sample rate (1000 samples in 40ns) nyq = fs*0.5 # Nyquist frequency high = 900e6/nyq # high frequency cut...
<reponame>webbjj/clustertools """ Generic recipes for making key calculations """ __author__ = "<NAME>" __all__ = [ 'nbinmaker', "binmaker", 'roaming_nbinmaker', "roaming_binmaker", "power_law_distribution_function", "dx_function", "tapered_dx_function", "x_hist", "mean_prof", "...
<reponame>Betterton-Lab/CyLaKS<filename>gradOpt_lattice_coop.py #!/usr/bin/python import os import numpy as np import scipy import logging import subprocess import matlab.engine from scipy.optimize import least_squares from subprocess import call from subprocess import Popen from math import sqrt MATLAB = matlab.engine...
<filename>doc/dustfm.py #!/bin/python ''' script for generating plots for the paper ''' import os import sys import h5py import numpy as np import corner as DFM from astrologs.astrologs import Astrologs # -- galpopfm -- from galpopfm.catalogs import Catalog from galpopfm import dustfm as dustFM from galpopfm i...
<reponame>ronaldosvieira/reinforced-greediness<filename>agent.py import json import pathlib import sys import time import numpy as np from scipy.special import softmax from sortedcontainers import SortedSet from src.engine import State, Action, ActionType base_path = str(pathlib.Path(__file__).parent.absolute()) PA...
<gh_stars>0 """ cnn_certify_ibp.py Certifies networks with IBP Copyright (C) 2021, <NAME> <<EMAIL>> <NAME> <<EMAIL>> <NAME> <<EMAIL>> <NAME> <<EMAIL>> <NAME> <<EMAIL>> <NAME> <<EMAIL>> """ import numpy as np from numb...
<filename>rsatoolbox/util/pooling.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Oct 20 23:58:28 2020 @author: heiko """ import numpy as np import scipy.sparse from scipy.stats import rankdata from rsatoolbox.rdm import RDMs from rsatoolbox.util.matrix import get_v def pool_rdm(rdms, method='c...
<gh_stars>1-10 from nipype.interfaces.ants import RegistrationSynQuick, ApplyTransforms import nibabel as nib from scipy import ndimage import numpy as np import os import shutil import argparse import glob def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("--case1", required=True) ...
<filename>colorpy/colorpy-0.1.0/thinfilm.py ''' thinfilm.py - Thin film interference colors. Description: Reflection from a thin film, as a function of wavelength, thickness, and index of refraction of materials. Note that film thicknesses are given in nm instead of m, as this is a more convenient unit in this case....
from datetime import timedelta import numpy as np import matplotlib.pyplot as plt from scipy.cluster.hierarchy import dendrogram, fcluster, linkage from scipy.cluster.vq import kmeans, vq from lagranto import trajectory from myscripts import datadir, plotdir styles = ['-bo', '-gx', '-rx', '-cx', '-mx', '-yx', ...
import numpy as np import matplotlib.pyplot as pl from scipy.io import netcdf def readResults(rootFile): # Read inverted profiles ff = netcdf.netcdf_file(rootFile+'.inversion', 'r') synthProf = ff.variables['map'][:] ff.close() # Read inverted parameters ff = netcdf.netcdf_file(rootFile+'.parameters', 'r') par...
<reponame>BigOto2/BlenderRenderDNS<filename>Render2018/lib/noncart_to_cart_test.py import numpy as np import scipy.interpolate #Temporary import mcubes import cgns_load_data def conv_noncart_to_cart(points, values, xrange, yrange, zrange): """ :param points: Data point locations (non-cartesian system) :pa...
import numpy as np import pandas as pd from scipy import interpolate import json from datetime import datetime, timedelta import requests import io print("RUNNING!") print(datetime.now()) def myconverter(o): if isinstance(o, datetime): return o.__str__() url = "https://coronavirus.data.gov.uk/downlo...
<reponame>andreamatt/DM-Count from typing import List from scipy.io import loadmat from PIL import Image import numpy as np import os from joblib import Parallel, delayed import shutil from preprocess.util import ImageInfo, cal_new_size, printStats, random_phase def generate_data(img_path, min_size, max_size): im...
<reponame>rokoatcoffee/py-pi<filename>pi.py #!/usr/bin/python3.7 import argparse from random import random from statistics import mean, stdev def pi() -> float: ''' pi function uses a million points to approximate the value of π. This is done by summing a circle's area. As points are randomly scattered inside...
# # Copyright © 2020 United States Government as represented by the Administrator # of the National Aeronautics and Space Administration. No copyright is claimed # in the United States under Title 17, U.S. Code. All Other Rights Reserved. # # SPDX-License-Identifier: NASA-1.3 # """Sky backgrounds.""" from importlib imp...
<reponame>RockWenJJ/ierg5350-assignment-2021 """ This file implements the some helper functions. Note that many codes in this file is not written by us. The credits go to the original writers. ----- *2021-2022 1st term, IERG 5350: Reinforcement Learning. Department of Information Engineering, The Chinese University ...
# -*- coding: utf-8 -*- """Header here.""" import numpy as np import scipy.stats as sps import sys import os import copy #the following imports are sloppy until a module is actually built... from balldroptestfuncs import balldropmodel_linear,\ balldropmodel_grav, balldroptrue SCRIPT_DIR = os.path.dirname(os.path.r...
<filename>energyPATHWAYS/util.py # -*- coding: utf-8 -*- """ Created on Wed Apr 08 10:12:52 2015 @author: <NAME> & <NAME> Contains unclassified global functions """ from energyPATHWAYS.error import ColumnNotFound import pandas as pd import os import numpy as np from collections import defaultdict, MutableSet import...
<filename>rnnhearer/visualization.py import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from scipy import interp from keras.callbacks import History from sklearn.metrics import auc, confusion_matrix, roc_curve from typing import Any, Dict, List, Union from .data_manipulation im...
# Authors: <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # # License: BSD (3-clause) import numpy as np from scipy import linalg from .fiff.constants import FIFF from .fiff.open import fiff_open from .fiff.tree import dir_tree_find from .fiff.tag import find_tag # # These fiff definitions are not needed elsewhere #...
<filename>backend/app/face_searcher.py<gh_stars>1-10 import pickle import json import numpy as np from scipy.spatial import distance class face_searcher: def __init__(self): with open("embeddings.pickle", "rb") as handle: self.d = pickle.load(handle) self.list_items = [] for it...
<gh_stars>100-1000 from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer from scipy.spatial import distance def finding_text_similarity_using_cosine_distance(s1, s2): # sentences to list allsentences = [s1, s2] # Using Count Vectorizer count_vectorizer = CountVectorize...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. """Script for data pre-processing.""" import tensorflow as tf import numpy as np import cv2 from PIL import Image import os from scipy.io import loadmat,savemat from renderer import face_decoder from training.networks_recon import R_Net from pr...
""" Classes for implementing prior probabilities in the context of Bayesian modelling and inference. """ # std libs import numbers import functools as ftl # third-party libs import numpy as np from scipy import stats from scipy.stats._distn_infrastructure import rv_frozen # local libs from obstools.modelling.utils i...
<filename>old/loaders/transform.py import abc import librosa import numpy as np import os import random import scipy.io.wavfile as sio import subprocess import tempfile import types from loaders.dataset import manager # replacement for os.tempnam def tempnam(): f = tempfile.NamedTemporaryFile(delete = False, dir ...
import math import numpy as np import json from scipy.spatial import distance import copy import os def term_freq (document): dict_tf = dict() total_word = 0 for word in document: if word.strip() != "": total_word += 1 if word not in dict_tf: dict_tf[wor...
<gh_stars>0 import numpy as np import pandas as pd import matplotlib as mpl import matplotlib.pyplot as plt import scipy.stats import matplotlib.gridspec as gridspec # mpl.use('TkAgg') # create base data np.random.seed(12345) df = pd.DataFrame([np.random.normal(32000,200000,3650), np.random.norma...
import numpy as np from scipy.sparse import csr_matrix, identity def div1D(k, m, dx): """ Computes a m+2 by m+1 one-dimensional mimetic divergence operator Arguments: k (int): Order of accuracy m (int): Number of cells dx (float): Grid step size Returns: :obj:`ndarray` co...
import numpy as np from SafePDP import SafePDP from SafePDP import PDP from JinEnv import JinEnv from casadi import * import scipy.io as sio import matplotlib.pyplot as plt import time import random # --------------------------- load environment ---------------------------------------- env = JinEnv.Rocket() Jx, Jy, J...
<filename>model.py import csv from scipy import ndimage from sklearn.model_selection import train_test_split from sklearn.utils import shuffle import cv2 import numpy as np import matplotlib.pyplot as plt from keras.models import Sequential from keras.layers import Flatten, Dense, Lambda, Cropping2D from keras.layers i...
import _benchmark import io import sys import os.path as path import math import subprocess import numpy as np import pandas as pd import scipy.stats from table import PairTable, SummaryTable thisdir = path.dirname(path.realpath(__file__)) tabledir = path.join(thisdir, '..', 'latex', 'report', 'tables') figuredir =...
<reponame>Jvanrhijn/tsp-local-search import numpy as np import scipy.linalg as linalg from util.sinkhorn_knopp import SinkhornKnopp np.random.seed(4554365) def generate_stochastic_matrix(n, iter_max=10): mat = np.random.rand(n, n) return mat/np.sum(mat, axis=0)[:, None] def sort_by_statistic_average(ma...
<filename>ianalysis.py """This is used to analyze the predictions when adding interventions. only return the gamma & eta score. only aggregrate by [subj, subj_intv] """ import sys import argparse import json import scipy from scipy import stats import numpy as np import itertools import collections import math # sys.p...
<gh_stars>1-10 import os import os.path as osp import sys import numpy as np import random import collections import torch import torchvision from scipy.ndimage import zoom import cv2 from torch.utils import data from cues_reader import CuesReader class VOCDataSet(data.Dataset): def __init__(self, ...
<filename>fracdiff/examples.py """ From <NAME>. 5 In practice, I suggest you experiment with the following transformation of your features: First, compute a cumulative sum of the time series. This guarantees that some order of differentiation is needed. Second, compute the FFD(d) series for var- ious d ∈ [0, 1]. Third...
<gh_stars>1-10 """ Data quality routines Data quality functions ====================== - :py:meth:`good_channels` Issues ====== Auxiliary functions are still lacking documentation. """ import numpy as np import ch_util.ephemeris as ch_eph from ch_util import andata from ch_util import tools from ch_util import ...
""" ============================================================== Curve fitting: temperature as a function of month of the year ============================================================== We have the min and max temperatures in Alaska for each months of the year. We would like to find a function to describe this y...
<gh_stars>1-10 import numpy as np from scipy.optimize import minimize, rosen class WF: def __init__(self): pass def f(self, opt, pos): return rosen(opt) wf = WF() opt = [1.3, 0.7, 0.8, 1.9, 1.2] pos = np.random.rand(10, 3) res = minimize(wf.f, opt, args=(pos,), method='Nelder-Mead', tol=1E...
<filename>Implementations/gama.py # Como executar: # $ python gama.py img_1.tif saida <gama> # <gama> é um número float, maior do que 0. import sys import numpy as np import matplotlib.pyplot as plt from scipy import misc from skimage import exposure def loadImg(arg): return misc.imread(arg) # Lê a imagem a part...
<gh_stars>0 """ Implements a Bot to play connect4. """ import random from copy import deepcopy from statistics import mean from . import c4 class Quatro: """Represents a Bot that can play connect4""" def __init__(self, difficulty): """Initializes the Bot Arguments: - board: handle t...
import glob import matplotlib.pylab as plt import numpy as np import math import sys import timeit import cv2 import scipy.spatial.distance import json import get_maps import preprocessing import filtering import descriptor import template import minutiae_AEC import show import enhancement_AEC import os from skimage im...
<reponame>enijkamp/CoopNets-1<filename>util/images.py<gh_stars>0 import math import numpy as np import scipy.misc def cell2img(cell_image, image_size=100, margin_syn=2): num_cols = cell_image.shape[1] // image_size num_rows = cell_image.shape[0] // image_size images = np.zeros((num_cols * num_rows, image...
<gh_stars>0 import torch import torch.nn.functional as F import scipy.optimize import seaborn as sn import matplotlib import matplotlib.pyplot as plt import numpy as np def per_sample_hungarian_loss(sample_np): row_idx, col_idx = scipy.optimize.linear_sum_assignment(sample_np) return row_idx, col_idx def hungar...
<gh_stars>0 import pandas as pd import numpy as np import scipy.stats as ss import scipy import pandas as pd import numpy as np import math def compute_drawdown(return_series: pd.Series): """ Takes a time series of asset returns Returns a DataFrame with columns for wealth index, peaks, and drawdons ...
"""Implementations of the IPFP algorithm to solve for equilibrium and do comparative statics in several variants of the `Choo and Siow 2006 <https://www.jstor.org/stable/10.1086/498585?seq=1>`_ model: * homoskedastic with singles (as in Choo and Siow 2006) * homoskedastic without singles * gender-heteroskedastic: w...
<reponame>modichirag/21cmhod<filename>code/plotting/plot_summary.py #!/usr/bin/env python3 # # Plots the power spectra and Fourier-space biases for the HI. # import numpy as np import sys, os import matplotlib.pyplot as plt from scipy.interpolate import LSQUnivariateSpline as Spline from scipy.interpolate import Interp...
# coding: utf-8 # In[1]: from skimage import segmentation, filters, measure from skimage.feature import canny from scipy import ndimage as ndi import matplotlib.pyplot as plt import cv2 import numpy as np import os plt.set_cmap(plt.gray()) # get_ipython().magic('matplotlib inline') # In[2]: # fp = '../data/Z3_I...
import tensorflow as tf import numpy as np import sys import logging as log class KernelND(object): '''Base class for kernels in ND. ndims : int the number of dimensions of input ''' def __init__(self,_hyperparams={},_hyperparams_bounds={},use_initializer=True,**kwargs): self.use_initia...
<filename>pydca.py # Copyright 2020 terminus data science, 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 app...
<filename>tests/create_reference_data.py # coding: utf-8 # /*########################################################################## # Copyright (C) 2017 European Synchrotron Radiation Facility # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated document...
import numpy as np import matplotlib.pyplot as plt from gym_flock.envs.spatial.utils import _get_pos_diff from scipy.spatial import Delaunay from pathlib import Path def in_obstacle(obstacles, px, py): """ Check if query point is within any of the rectangular obstacles :param obstacles: list of rectangula...
<reponame>evgenykurbatov/kb21-hotjup-migration-adv<gh_stars>0 # -*- coding: utf-8 -*- import sys import numpy as np from numpy import pi, sqrt, exp, sin, cos, tan, log, log10 import scipy as sp import scipy.integrate import ctypes import const from pringle import Pringle ## ## The model ## class Model(object): ...
<reponame>vntborgesjr/Python-Fundamentals<filename>Introduction-to-Python/03-Functions.py # --------------------------------------------------- # Introductio to Python - Functions # 18 set 2020 # VNTBJR # --------------------------------------------------- # # Load packages ---------------------------------------...
<filename>BM/4.Feature_and_Filter_Analysis/4.B.Filter_analysis.py<gh_stars>1-10 #!/usr/bin/python import glob import sys from scipy.stats import hmean #>>> hmean([1, 4]) tool = sys.argv[1] weight = float(sys.argv[2]) out = open("/data/project/MRS/5.Combined_Analysis/Filter/Fil_ana." + tool + ".txt", "w") types = ['mx'...
<filename>utils/rotation_utils.py import constants import functools from scipy.spatial.transform.rotation import Rotation from custom_types import * def quat_to_rot(q): shape = q.shape q = q.view(-1, 4) q_sq = 2 * q[:, :, None] * q[:, None, :] m00 = 1 - q_sq[:, 1, 1] - q_sq[:, 2, 2] m01 = q_sq[:, ...
<reponame>dpopadic/ml-res import numpy as np # ----- heights data x_heights = np.array([ 51.25, 53.75, 56.25, 58.75, 61.25, 63.75, 66.25, 68.75, 71.25, 73.75, 76.25, 78.75, 81.25, 83.75, 86.25, 88.75, 91.25, 93.75, 96.25, 98.75, 101.25...
# Statistical tests on ratios # # <EMAIL> import numpy as np import numba import copy import scipy.stats as stats def prodratio_eprop(A, B, sigmaA, sigmaB, sigmaAB=0, mode='ratio'): """ Error propagation (Taylor expansion) of product A*B or ratio A/B Args: A : Value A B : Value B sigmaA : 1 sigma uncerta...
<gh_stars>0 import numpy as np import pandas as pd import matplotlib import numpy.ma as ma from scipy import stats import matplotlib.pyplot as plt from matplotlib.ticker import (MultipleLocator, FormatStrFormatter, AutoMinorLocator) import cartopy.crs as ccrs import cartopy.util as cutil from matplotlib.ticker import (...