arxiv_id stringlengths 0 16 | text stringlengths 10 1.65M |
|---|---|
import dataio
from TensorFlowRecommender import TensorFlowRecommender
import numpy as np
np.random.seed(13575)
def get_data():
df = dataio.read_process("data/ml-1m/ratings.dat", sep="::")
rows = len(df)
df = df.iloc[np.random.permutation(rows)].reset_index(drop=True)
split_index = int(rows * 0.9)
... | |
import random
import numpy as np
class DefaultRandomGenerator:
def rand(self, size=None):
if size is None:
return random.random()
else:
n = size[0]
m = size[1]
val = np.zeros((n, m))
for i in range(n):
for j in range(m):
... | |
from styx_msgs.msg import TrafficLight
import rospy
import rospkg
import numpy as np
import os
import sys
import tensorflow as tf
from collections import defaultdict
from io import StringIO
from object_detection_classifier import ObjectDetectionClassifier
import time
UNKNOWN = 'UNKNOWN'
YELLOW = 'Yellow'
GREEN = 'Gree... | |
import numpy as np
from math import pi, sqrt
from sys import platform
if platform == "darwin": # MACOS
from openseespymac.opensees import *
else:
from openseespy.opensees import *
import os
''' FUNCTION: build_model ------------------------------------------------------
Generates OpenSeesPy model of an elasti... | |
# Copyright (c) 2017, Intel Research and Development Ireland Ltd.
#
# 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... | |
import torch
import numpy as np
def atomic_orbital_norm(basis):
"""Computes the norm of the atomic orbitals
Args:
basis (Namespace): basis object of the Molecule instance
Returns:
torch.tensor: Norm of the atomic orbitals
Examples::
>>> mol = Molecule('h2.xyz', basis='dzp', ... | |
# -*- encoding: utf-8 -*-
"""
GLM solver tests using Kaggle datasets.
:copyright: 2017 H2O.ai, Inc.
:license: Apache License Version 2.0 (see LICENSE for details)
"""
import time
import sys
import os
import numpy as np
import logging
import feather
print(sys.path)
from h2o4gpu.util.testing_utils import find_file, ... | |
import re
import numpy as np
import vcfpy
from hgvs import edit
from ncls import NCLS
class GenomePosition():
genome_pos_pattern = re.compile(r"(.+):(\d+)-(\d+)")
def __init__(self, chrom, start, end):
self.chrom = chrom
self.start = start
self.end = end
@classmethod
def fro... | |
### tensorflow==2.3.0
### https://ai.googleblog.com/2020/08/on-device-real-time-body-pose-tracking.html
### https://google.github.io/mediapipe/solutions/pose
### https://www.tensorflow.org/api_docs/python/tf/keras/Model
### https://www.tensorflow.org/lite/guide/ops_compatibility
### https://www.tensorflow.org/api_do... | |
# compute FOM sol for test values of parameters mu
import numpy as np
import os,setrun
mu_test = np.loadtxt("../_output/mu_test.txt") # parameters
ts_test = np.loadtxt("../_output/ts_test.txt") # no of time-steps
L = mu_test.shape[0]
r = 0
n = 14 + r
h = 10.0 / 2**n
nu = 0.5
dt = h*nu
for l in range(0,L):
p... | |
"""
Contains classes that convert from RGB to various other color spaces and back.
"""
import torch
import torch.nn as nn
from .mister_ed.utils import pytorch_utils as utils
from torch.autograd import Variable
import numpy as np
from recoloradv import norms
import math
class ColorSpace(object):
"""
Base clas... | |
import matplotlib.pyplot as plt
import numpy as np
"""
Plot RMS for x-/y-/z-signal vs 1/3 octave band frequencies and compare to VC curves.
"""
# rms_x_all = np.loadtxt("14208_betacampus_pos1_rms_x_all.txt")
# rms_y_all = np.loadtxt("14208_betacampus_pos1_rms_y_all.txt")
# rms_z_all = np.loadtxt("14208_betac... | |
# Author: aqeelanwar
# Created: 12 June,2020, 7:06 PM
# Email: aqeel.anwar@gatech.edu
# Trainer: Vinit Gore
# Edited: 17 Dec, 2021
# Email: vinitgore@gmail.com
from tkinter import * # Tkinter is the package for creating simple Graphical User Interfaces (GUIs)
import random # python package to generate random numb... | |
import os
import cv2
import numpy as np
from math import exp
import tensorflow as tf
from base64 import encodebytes
from PIL import Image, ImageFont, ImageDraw, ImageOps
from flask import Flask, flash, request, redirect, url_for, render_template,Response
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '0'
with open('labels.txt... | |
import pandas as pd
import os
import numpy as np
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
import cv2
import gc
from scipy import ndimage
import matplotlib.colors as colors
class ThicknessMapUtils():
def __init__(self, label_path, image_path, prediction_path):
self.labe... | |
#!/usr/bin/env python
# coding: utf-8
# ## Imports
# In[7]:
import pandas as pd
import numpy as np
import streamlit as st
from PIL import Image
import os
import pickle
#Open model created by the notebook
model = pickle.load(open('model/box_office_model.pkl','rb'))
#create main page
def main():
image = Image.o... | |
import math
import pandas as pd
import numpy as np
import os
from src.datasets import Dataset
from sklearn.metrics import roc_auc_score
"""
@author: Astha Garg 10/19
"""
class Wadi(Dataset):
def __init__(self, seed: int, remove_unique=False, entity=None, verbose=False, one_hot=False):
"""
:param ... | |
# -*- coding: utf-8 -*-
import tensorflow as tf
import librosa
import numpy as np
import os
from scipy.signal import butter, lfilter, freqz
import matplotlib.pyplot as plt
def conv_net(X,W,b,keepprob,mfcc_n,img_size):
input_img=tf.reshape(X,shape=[-1,mfcc_n,img_size,1])
# conv_net
layer1=tf.nn.relu(tf.add... | |
import os
import shutil
import json
import time
import numpy as np
from scipy.misc import imsave
#from Environment.env import Actions
from pathlib import Path
from datetime import datetime
class Logger:
root = Path('files')
modelsRoot = Path('models')
path_rewards = Path('files/rewards/')
path_losses ... | |
######################################################
# Christoph Aurnhammer, 2019 #
# Pertaining to Aurnhammer, Frank (2019) #
# Comparing gated and simple recurrent neural #
# networks as models of human sentence processing #
# ... | |
import numpy as np
import re
import itertools
from collections import Counter
from konlpy.tag import Mecab
def clean_str(string):
"""
Tokenization/string cleaning for all datasets except for SST.
Original taken from https://github.com/yoonkim/CNN_sentence/blob/master/process_data.py
"""
string = r... | |
#!/usr/bin/env python
import numpy as np
from sklearn.datasets import load_svmlight_file
from sklearn.metrics import average_precision_score, roc_auc_score
from sklearn.ensemble import IsolationForest
import sys
if __name__ == "__main__":
filename = sys.argv[1]
ap = []
auc = []
with open... | |
'''
Created on Jan 6, 2014
@author: jbq
'''
import numpy
from logger import vlog, tr
import copy
class Interpolator(object):
'''
Evaluate the structure factor at a particular phase point for any
value of the external parameters
'''
def __init__(self, fseries, signalseries, errorseries=None, running_regr_t... | |
#Copyright 2022 Nathan Harwood
#
#Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
#Unless required by applicable law or agreed to in writing, sof... | |
# %%
import numpy as np
import matplotlib.pyplot as plt
from skimage.measure import label
from skimage import data
from skimage import color
from skimage.morphology import extrema
from skimage import exposure
from PIL import Image
from skimage.feature import peak_local_max
# %%
img = Image.open('C:\\... | |
# Author: Vincent Zhang
# Mail: zhyx12@gmail.com
# ----------------------------------------------
import torch
from collections.abc import Sequence
from mmcv.runner import get_dist_info
from mmcv.parallel import MMDistributedDataParallel
import numpy as np
import random
import torch.distributed as dist
from mmcv.utils ... | |
import importlib
import os
import sys
import exputils
import imageio
import numpy as np
import torch
import autodisc as ad
from goalrepresent.datasets.image.imagedataset import LENIADataset
def collect_recon_loss_test_datasets(explorer):
statistic = dict()
test_dataset_idx = 0
for test_dataset... | |
import numpy as np
import pandas as pd
from ira.analysis import column_vector
from sklearn.base import BaseEstimator
from ira.analysis.timeseries import adx, atr
from ira.analysis.tools import ohlc_resample, rolling_sum
from qlearn import signal_generator
@signal_generator
class AdxFilter(BaseEstimator):
"""
... | |
#
# Copyright 2019 The FATE Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | |
"""Module otsun.outputs
Helper functions to format data for output
"""
import numpy as np
def spectrum_to_constant_step(file_in, wavelength_step, wavelength_min, wavelength_max):
data_array = np.loadtxt(file_in, usecols=(0, 1))
wl_spectrum = data_array[:, 0]
I_spectrum = data_array[:, 1]
array_inter ... | |
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import time
import os
import argparse
from copy import deepcopy
from kgcnn.utils.data import save_json_file, load_json_file
from kgcnn.utils.learning import LinearLearningRateScheduler
from sklearn.model_selection import KFold
from kgcnn.data.d... | |
# Multiple linear Regerssion
# <---------------- Importing data ------------------->
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('50_Startups.csv') # ----> Set the correct path
X = dataset.iloc[:, :-1].values ... | |
__copyright__ = "Copyright (c) 2020 Jina AI Limited. All rights reserved."
__license__ = "Apache-2.0"
from typing import Dict
import numpy as np
from jina.executors.rankers import Chunk2DocRanker
class TfIdfRanker(Chunk2DocRanker):
"""
:class:`TfIdfRanker` calculates the weighted score from the matched chun... | |
'''
Example of a spike generator (only outputs spikes)
In this example spikes are generated and sent through UDP packages. At the end of the simulation a raster plot of the
spikes is created.
'''
import brian_no_units # Speeds up Brian by ignoring the units
from brian import *
import numpy
from brian_multiprocess_... | |
'''
Integrates trajectory for many cycles
- tries to load previously computed cycles; starts from the last point available
- saved result in a separate file (e.g. phi_0_pt1.npy)
- finishes early if a trajectory almost converged to a fixed point
- IF integrated for many thousands of cycles - may want to uncomment `phi... | |
import numpy as np
##A script for creating tables for each cancer, with the data sorted
def compare(first,second):
if float(first[-2])>float(second[-2]):
return 1
elif float(first[-2])<float(second[-2]):
return -1
else:
return 0
import os
BASE_DIR = os.path.dirname(os.path.dirna... | |
from typing import List
import numpy as np
Tensor = List[float]
def single_output(xdata: List[Tensor], ydata: List[Tensor]) -> List[Tensor]:
xdata = np.asarray(xdata)
ydata = np.asarray(ydata) | |
# -*- coding: utf-8 -*-
import logging
import six
from six.moves import zip, map
import numpy as np
import vtool as vt
import utool as ut
from wbia.control import controller_inject
print, rrr, profile = ut.inject2(__name__)
logger = logging.getLogger('wbia')
# Create dectorator to inject functions in this module int... | |
import math
import numpy as np
def confidence(prediction):
"""
Metric to evaluate the confidence of a model's prediction of an image's class.
:param prediction: List[float] per-class probability of an image to belong to the class
:return: Difference between guessed class probability and the mean of ot... | |
'''Cell-cell variation measurements'''
import numpy as np
import pandas as pd
import scanpy.api as sc
import anndata
from typing import Union, Callable, Iterable
import matplotlib.pyplot as plt
def median_filter(x: np.ndarray,
k: int,
pad_ends: bool = True,) -> np.ndarray:
'''... | |
"""
@author: Timothy Brathwaite
@name: Bootstrap Sampler
@summary: This module provides functions that will perform the stratified
resampling needed for the bootstrapping procedure.
"""
from collections import OrderedDict
import numpy as np
import pandas as pd
def relate_obs_ids_to_chosen_alts(... | |
#Libraries to include; you can add more libraries to extend beyond the
# functionality in the tutorial
import numpy as np
import geneMLLib as ml #our custom library
from sklearn import metrics
from sklearn.cluster import KMeans
def main():
#load data, X is gene values, genes is names of genes, y are the labels
... | |
from __future__ import annotations
from typing import Any, Dict, Type, cast
import numpy as np
from tiro_fhir import CodeableConcept
import pandas as pd
from pandas._typing import DtypeObj
from pandas.core.dtypes.dtypes import PandasExtensionDtype, Ordered, Dtype
class CodeableConceptDtypeDtype(type):
pass
@pd.... | |
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import linear_sum_assignment
from scipy.spatial.distance import pdist, squareform
import seaborn as sns
from factored_reps.scripts.seriation import compute_serial_matrix
def shuffle_vars(A, seed=None):
n_vars = len(A)
indices = np.arange(n... | |
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 29 19:18:23 2016
@author: Pedro Leal
"""
# =============================================================================
# Standard Python modules
# =============================================================================
import os, sys, time
from scipy.optimize imp... | |
"""
@ Author: ryanreadbooks
@ Time: 9/7/2020, 19:18
@ File name: geometry_utils.py
@ File description: define a bunch of helper functions that are related to the object model and geometry
"""
import numpy as np
import cv2
from configs.configuration import regular_config
def get_model_corners(model_pts: np.ndarray) ... | |
import numpy as np
from PIL import Image
import cv2
from os.path import dirname as ospdn
from .file import may_make_dir
def make_im_grid(ims, n_rows, n_cols, space, pad_val):
"""Make a grid of images with space in between.
Args:
ims: a list of [3, im_h, im_w] images
n_rows: num of rows
n_col... | |
from Q50_config import *
import sys, os
from GPSReader import *
from GPSTransforms import *
from VideoReader import *
from LidarTransforms import *
from ColorMap import *
from transformations import euler_matrix
import numpy as np
import cv2
from ArgParser import *
from scipy.interpolate import griddata
import matplotl... | |
import cv2
import numpy as np
from xview.dataset import read_mask
import matplotlib.pyplot as plt
from xview.postprocessing import make_predictions_floodfill, make_predictions_dominant_v2
from xview.utils.inference_image_output import make_rgb_image
import pytest
@pytest.mark.parametrize(["actual", "expected"], [
... | |
## setup_mnist.py -- mnist data and model loading code
##
## Copyright (C) 2016, Nicholas Carlini <nicholas@carlini.com>.
##
## This program is licenced under the BSD 2-Clause licence,
## contained in the LICENCE file in this directory.
import tensorflow as tf
import numpy as np
import os
import pickle
import gzip
imp... | |
# coding: utf-8
# <h1>Table of Contents<span class="tocSkip"></span></h1>
# <div class="toc"><ul class="toc-item"><li><span><a href="#Use-pyresample-to-make-a-projected-image" data-toc-modified-id="Use-pyresample-to-make-a-projected-image-1"><span class="toc-item-num">1 </span>Use pyresample to make a proje... | |
from __future__ import print_function
import pickle
import numpy as np
from scipy.optimize import curve_fit
# Reference each pick to a station index
def getPickStaIdxs(pickSet,staNames):
pickStas,pickIdx=np.unique(pickSet[:,0],return_inverse=True)
pickStaIdxs=np.ones(len(pickIdx),dtype=int)*-1
for pos in ... | |
from PIL import Image
from pokescrapping import download_photo
import numpy
import json
def load_db(dex_db=None):
try:
db_file = open('dexdb.json')
data = json.load(db_file)
if dex_db is not None:
return data[dex_db]
else:
return data
except... | |
# -*- coding: UTF-8 -*-
"""StyleGAN architectures.
"""
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
from .base import StyleGAN
from _int import FMAP_SAMPLES, RES_INIT
from utils.latent_utils import gen_rand_latent_vars
from utils.custom_layers import Lambda, get_blur_op, Normalize... | |
# Lint as: python3
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# ... | |
# tts 推理引擎,支持流式与非流式
# 精简化使用
# 用 onnxruntime 进行推理
# 1. 下载对应的模型
# 2. 加载模型
# 3. 端到端推理
# 4. 流式推理
import base64
import numpy as np
from paddlespeech.server.utils.onnx_infer import get_sess
from paddlespeech.t2s.frontend.zh_frontend import Frontend
from paddlespeech.server.utils.util import denorm, get_chunks
from paddlesp... | |
###########################
# Latent ODEs for Irregularly-Sampled Time Series
# Author: Yulia Rubanova
###########################
import os
import numpy as np
import torch
import torch.nn as nn
import lib.utils as utils
from lib.diffeq_solver import DiffeqSolver
from generate_timeseries import Periodic_1d
from torc... | |
import geopandas as gpd
import numpy as np
import pandas as pd
import pytest
from pytest import approx
from shapely.geometry import LineString, Point, Polygon
import momepy as mm
from momepy import sw_high
from momepy.shape import _make_circle
class TestDimensions:
def setup_method(self):
test_file_path... | |
from collections import Counter
import numpy as np
import xmltodict
def parse_xml(fp_path):
with open(fp_path) as f:
xml_content = f.read()
return xmltodict.parse(xml_content)
def count_number_of_layers(xdict):
net = xdict['net'] # the first field is 'net'
print(f"Total number of layer entr... | |
from numpy import zeros, random, dot#, array, matrix
def sketch(M, k):
# matrix height and width
# M = matrix(M)
# change width and height
# w,h = M.shape
w = len(M)
h = len(M[0])
# generating k random directions simply use vectors of normally distributed random numbers
rd = random.ran... | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import tensorflow as tf
import numpy as np
import struct
import time
"""
train data can be find here http://yann.lecun.com/exdb/mnist/
"""
def get_image(num):
with open('train-images-idx3-ubyte', 'rb') as f:
buf = f.read(16)
magic = struct.unpack('>4i'... | |
from applications.parameter_optimization.optimized_nio_base import OptimizedNIOBase
from algorithms import WaterWaveOptimization
from numpy import array
import logging
logging.basicConfig()
logger = logging.getLogger('OptimizedWWOFunc')
logger.setLevel('INFO')
class OptimizedWWOFunc(OptimizedNIOBase):
def __ini... | |
# -*- coding: utf-8 -*-
"""Convolutional MoE layers. The code here is based on the implementation of the standard convolutional layers in Keras.
"""
import numpy as np
import tensorflow as tf
from tensorflow.keras import backend as K
from tensorflow.keras import activations, initializers, regularizers, constraints
from... | |
import pandas as pd
from statsmodels.tsa.holtwinters import Holt
import traceback
class EventHandler:
def __init__(self, return_func, config: dict):
self.return_func = return_func
self.temperatureData = pd.Series()
self.MIN_TRAIN_DATA = config.get("MIN_TRAIN_DATA") # TODO 100 ~60 sec
... | |
from typing import Union
import numpy as np
import pandas as pd
import hdbscan
from oolearning.model_wrappers.HyperParamsBase import HyperParamsBase
from oolearning.model_wrappers.ModelExceptions import MissingValueError
from oolearning.model_wrappers.ModelWrapperBase import ModelWrapperBase
class ClusteringHDBSCAN... | |
#!/usr/bin/env python
import numpy as np
from typing import Optional, Callable
from agents.common import PlayerAction, BoardPiece, SavedState, GenMove
from agents.agent_random import generate_move
from agents.agent_minimax import minimax_move
from agents.agent_mcts import mcts_move
from agents.agent_mcts_2 import mcts_... | |
"""Tests for normalization functions."""
from . import _unittest as unittest
from datatest._query.query import DictItems
from datatest._query.query import Result
from datatest.requirements import BaseRequirement
from datatest._utils import IterItems
from datatest._normalize import _normalize_lazy
from datatest._normal... | |
# -*- coding: utf-8 -*-
"""
The model class for Mesa framework.
Core Objects: Model
"""
import datetime as dt
import random
import numpy
class Model:
""" Base class for models. """
def __init__(self, seed=None):
""" Create a new model. Overload this method with the actual code to
start the m... | |
import os
import copy
import numpy as np
import pandas as pd
import torch
from sklearn.metrics import f1_score
from utils import load_model_dict
from models import init_model_dict
from train_test import prepare_trte_data, gen_trte_adj_mat, test_epoch
cuda = True if torch.cuda.is_available() else False
def cal_feat_i... | |
import torch
import torch.nn.functional as F
from utils.tensor import _transpose_and_gather_feat, _sigmoid
import numpy as np
class DetectionLoss(torch.nn.Module):
def __init__(
self, hm_weight, wh_weight, off_weight, kp_weight=None,
angle_weight=1.0, periodic=False, kp_indices=None,
... | |
import pytest
import numpy as np
from numpy.testing import assert_allclose
from tardis.plasma.properties import YgData
def test_exp1_times_exp():
x = np.array([499.0, 501.0, 710.0])
desired = np.array([0.00200000797, 0.0019920397, 0.0014064725])
actual = YgData.exp1_times_exp(x)
assert_allclose(actual... | |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright © Spyder Project Contributors
#
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
# ----------------------------------------------------------------------------
"""
Tes... | |
'''An implementation of the GLYMMR alogrithm using some of the pre-existing CCARL framework.
GLYMMR Algorithm (from Cholleti et al, 2012)
1. Initialize each unique node among all the binding glycans as a subtree of size 1.
Let this set be S.
2. For each subtree in S:
- Calculate the number of binding glycans conta... | |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import xlrd
#----------------funções auxiliares ------------------
def inverteDicionario(dicionario):
#função que recebe um dicionario e devolve um outro dicionario igual, mas com a ordem do elementos invertidos
#obs: nã... | |
#!/usr/bin/env python
import yaml
import numpy as np
from os.path import join
import matplotlib, os
try: os.environ['DISPLAY']
except KeyError: matplotlib.use('Agg')
from matplotlib import font_manager
import pylab as plt
from ugali.utils.shell import mkdir
import ugali.analysis.loglike
from ugali.utils... | |
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License.
# A copy of the License is located at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# or in the "license... | |
import os
import subprocess
import sys
import shutil
import pandas as pd
import argparse
import numpy as np
import boto3
from datetime import datetime
# from botocore.exceptions import ClientError
from botocore.config import Config
from boto3.dynamodb.conditions import Key
config = Config(
retries = {
'max_at... | |
import scipy.ndimage as ndimg
import numpy as np
from imagepy.core.engine import Filter, Simple
from geonumpy.pretreat import degap
class GapRepair(Simple):
title = 'Gap Repair'
note = ['all', 'preview']
para = {'wild':0, 'r':0, 'dark':True, 'every':True, 'slice':False}
view = [(float, 'wild', (-65536,... | |
import itertools,math
import numpy as np
from scipy.stats import binom_test
try:
from pybedtools import BedTool
except:
print("Pybedtools not imported")
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
def plot_styler():
ax = plt.subplot(111)
ax.spines['right'].set_visibl... | |
"""
created matt_dumont
on: 15/02/22
"""
import flopy
import numpy as np
from ci_framework import FlopyTestSetup, base_test_dir
import platform
base_dir = base_test_dir(__file__, rel_path="temp", verbose=True)
nrow = 3
ncol = 4
nlay = 2
nper = 1
l1_ibound = np.array([[[-1, -1, -1, -1],
[-1, 1, ... | |
import numpy as np
from scipy.optimize import minimize
import networkx as nx
from code.miscellaneous.utils import flatten_listlist
from scipy.sparse.csgraph import connected_components
from code.Modality.DensityEstKNN import DensityEstKNN
from code.NoiseRemoval.ClusterGMM import gmm_cut
from code.Graph.extract_neighbor... | |
#!/usr/bin/env python
u"""
MPI_reduce_ICESat2_ATL11_RGI.py
Written by Tyler Sutterley (10/2021)
Create masks for reducing ICESat-2 data to the Randolph Glacier Inventory
https://www.glims.org/RGI/rgi60_dl.html
COMMAND LINE OPTIONS:
-D X, --directory X: Working Data Directory
-R X, --region X: region of Ra... | |
import numpy as NP
from astropy.io import fits
from astropy.io import ascii
import scipy.constants as FCNST
import matplotlib.pyplot as PLT
import matplotlib.animation as MOV
import geometry as GEOM
import interferometry as RI
import catalog as CTLG
import constants as CNST
import my_DSP_modules as DSP
catalog_file ... | |
from joerd.util import BoundingBox
from joerd.region import RegionTile
from joerd.mkdir_p import mkdir_p
from osgeo import osr, gdal
import logging
import os
import os.path
import errno
import sys
import joerd.composite as composite
import joerd.mercator as mercator
import numpy
import math
from geographiclib.geodesic ... | |
# -*- coding: utf-8 -*-
import numpy as np
import scipy as sp
def moments_mvou(x_tnow, deltat_m, theta, mu, sig2):
"""For details, see here.
Parameters
----------
x_tnow : array, shape(n_, )
deltat_m : array, shape(m_, )
theta : array, shape(n_, n_)
mu : array, shape(n_, ... | |
import argparse
from scipy.optimize import differential_evolution
from sklearn.naive_bayes import MultinomialNB
from imblearn.metrics import geometric_mean_score
import numpy as np
import pickle
with open('../X_train.pickle', 'rb') as f:
X_train = pickle.load(f)
with open('../y_train.pickle', 'rb') as f:
y... | |
from tisane.family import SquarerootLink
from tisane.data import Dataset
from tisane.variable import AbstractVariable
from tisane.statistical_model import StatisticalModel
from tisane.random_effects import (
RandomIntercept,
RandomSlope,
CorrelatedRandomSlopeAndIntercept,
UncorrelatedRandomSlopeAndInter... | |
import cv2
import numpy as np
class Cartoonfy(object):
def __init__(self, image_path):
self.image_path = image_path
def cartoonfy(self):
image = cv2.imread(self.image_path)
image = cv2.resize(image, (int(image.shape[1] *.4), int(image.shape[0] * .4)))
imageGray = cv2.cvtColor(im... | |
# Utlity Imports
import pickle
import numpy as np
import pandas as pd
import os
import json
from tqdm import tqdm
from datetime import datetime, timedelta
import matplotlib.pyplot as plt
# %matplotlib inline
# Tensorflow and Keras imports
from tensorflow.keras.models import Sequential
from tensorflow.ke... | |
"""
==============================
Customizing dashed line styles
==============================
The dashing of a line is controlled via a dash sequence. It can be modified
using `.Line2D.set_dashes`.
The dash sequence is a series of on/off lengths in points, e.g.
``[3, 1]`` would be 3pt long lines separated by 1pt s... | |
"""Resistively and capacitively shunted junction (RCSJ) model.
For details, see Tinkham §6.3.
All units are SI unless explicitly stated otherwise.
The following notation is used:
Ic critical_current
R resistance
C capacitance
"""
import numpy as np
from scipy.constants import e, hbar
def plasma_fr... | |
import abc
from typing import List, Tuple, Optional, Generator
import numpy as np
import cv2
class _BaseDetector(abc.ABC):
@abc.abstractmethod
def _resize_image(self, image: np.ndarray):
pass
@abc.abstractmethod
def init_session(self):
pass
@abc.abstractmethod
def close_sess... | |
"""
Demonstrate the use of motmot.wxglvideo.simple_overlay.
"""
import pkg_resources
import numpy
import wx
import motmot.wxglvideo.demo as demo
import motmot.wxglvideo.simple_overlay as simple_overlay
SIZE=(240,320)
class DemoOverlapApp( demo.DemoApp ):
def OnAddDisplay(self,event):
if not hasattr(self,... | |
"""
Implementation of DDPG - Deep Deterministic Policy Gradient
Algorithm and hyperparameter details can be found here:
http://arxiv.org/pdf/1509.02971v2.pdf
The algorithm is tested on the Pendulum-v0 OpenAI gym task
and developed with tflearn + Tensorflow
Author: Patrick Emami
"""
import tensorflow as tf
imp... | |
# coding: utf8
def get_t1_freesurfer_custom_file():
import os
custom_file = os.path.join(
"@subject",
"@session",
"t1",
"freesurfer_cross_sectional",
"@subject_@session",
"surf",
"@hemi.thickness.fwhm@fwhm.fsaverage.mgh",
)
return custom_file
... | |
import numpy as np
from typing import Callable, List, Optional
from lab1.src.onedim.one_dim_search import dichotomy_method
from lab2.src.methods.conjugate_method import conjugate_direction_method
from lab2.src.methods.newton_step_strategy import ConstantStepStrategy
DEFAULT_EPS = 1e-6
DEFAULT_MAX_ITERS = 1000
def n... | |
'''Functions used in solver class
'''
import numpy as np
from state import State
def cosphi(m):
"""Get operator for x-component of dipole moment projection.
Parameters
----------
m : int
Maxium energy quantum number.
Returns
-------
cosphi : numpy.array, shape=(2m+1,2m+1)
... | |
import numpy as np
import matplotlib.pyplot as plt
def update_vorticity(g, w, lam, u, v, dt, dx, dy, kx, ky):
# Add the +g and +w for forward euler, then call this func instead of
# vorticity_rk4 for faster computation
gnew = dt*((2+lam)*g2_avg(g, dx, dy)- (1+lam)*g**2 - convect(g, u, v, kx, ky)) #+g
... | |
import networkx as nx
import pandas as pd
def import_csv(filename):
""" import csv file into a Pandas dataframe """
return pd.read_csv(filename)
def preprocessing(filename):
""" make Pandas dataframe easier to work with by:
- deleting timestamp column
- making the names column into the row... | |
import numpy as np
from typing import Union
from talib import SMA
try:
from numba import njit
except ImportError:
njit = lambda a: a
from jesse.helpers import get_candle_source, slice_candles
def rma(candles: np.ndarray, length: int = 14, source_type="close", sequential=False) -> \
Union[float, np.n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.