arxiv_id
stringlengths
0
16
text
stringlengths
10
1.65M
#!/usr/bin/env python """ Copyright 2020 Johns Hopkins University (Author: Jesus Villalba) Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) """ import sys import os import argparse import time import logging import numpy as np import torch import torch.nn as nn from hyperion.hyp_defs import config_logger,...
"""classicML的核函数.""" import numpy as np __version__ = 'backend.python.kernels.0.10.b0' class Kernel(object): """核函数的基类. Attributes: name: str, default='kernel', 核函数名称. Raises: NotImplementedError: __call__方法需要用户实现. """ def __init__(self, name='kernel'): """ ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from . import Dataset import numpy as np class MiniBatches(Dataset): """ Convert data into mini-batches. """ def __init__(self, dataset, batch_size=20, cache=True): self.origin = dataset self.size = batch_size self._cached_train_s...
import os, sys import numpy as np import shutil from tqdm import tqdm from data_index import cat_id_to_desc, cat_desc_to_id, get_example_ids sys.path.append('..') from render_utils import render_obj_grid, render_obj_with_view def render_example(example_id, render_dir, input_dir, output_dir, texture_dir, csv_file, sh...
import unittest from cupy import _core from cupy import testing @testing.gpu class TestArrayOwndata(unittest.TestCase): def setUp(self): self.a = _core.ndarray(()) def test_original_array(self): assert self.a.flags.owndata is True def test_view_array(self): v = self.a.view() ...
import os os.system('pip install -q efficientnet --quiet') import tensorflow as tf import pandas as pd import numpy as np import cv2 import itertools from tensorflow.keras.applications.imagenet_utils import preprocess_input class DataGenerator(tf.keras.utils.Sequence): def __init__(self, dataset, batch_size,...
# -*- coding:UTF-8 -*- import torch import torch.nn as nn import torch.nn.functional as F from torchsummary import summary import numpy as np from math import floor from .spp import * from params import Args import sys import platform if platform.python_version().split('.')[0] == '2': sys.path.append('./') from...
#!/usr/bin/python3 import os import copy import mmh3 import numpy as np import math from random import shuffle from pathlib import Path import json from predictor.utility import msg2log class BF(): """ Bloom filter For simplicity, bit array is replaced by bool array """ def __init__(self, filt...
# Copyright 2021 cms.rendner (Daniel Schmidt) # # 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...
""" Tests for workspace module """ import os import shutil import tempfile from six import StringIO import numpy as np import pytest from fsl.data.image import Image from oxasl import Workspace, AslImage from oxasl.workspace import text_to_matrix def test_default_attr(): """ Check attributes are None by default...
# Copyright 2022 IBM Inc. All rights reserved # SPDX-License-Identifier: Apache2.0 # 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 ...
# SAve a file with 2*(n-1) columns contaning the (n-1) independent variables and the (n-1) gradients of the trained NN with respect these variables import matplotlib.pyplot as plt import numpy as np import copy import os import sys import torch import torch.nn as nn import torch.nn.functional as F is_cuda = torch.cuda...
import torch import numpy as np import random import collections from sklearn.cluster import KMeans from sklearn import metrics import argparse from toolbox import load_pickle, LR_classifier, shift_operator, eigenvalues, global_ratio from toolbox import sample_case, l2_norm, compute_confidence_interval, diffused def...
# -*- coding: utf-8 -*- """ @author: Adam Reinhold Von Fisher - https://www.linkedin.com/in/adamrvfisher/ """ #This is part of a multithreading tool to speed up brute force optimization #Import modules from numba import jit #Decorator @jit #Define function def multithreadADXStratOpt(): #Import modules impor...
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np import pandas as pd from datetime import timedelta from .geo import shoot, gc_distance # STORM TRACK LIBRARY # TODO descatalogar? def track_from_parameters( pmin, vmean, delta, gamma, x0, y0, x1, R, date_ini, hours, great_circle=Fals...
# -*- coding: utf-8 -*- """ Created on Wed Oct 24 08:20:07 2018 @author: Andrija Master """ import time import numpy as np import pandas as pd import warnings warnings.filterwarnings('ignore') from sklearn.metrics import roc_auc_score from sklearn.metrics import r2_score from sklearn.metrics import mean_squared_error...
import os import cv2 import tensorflow as tf slim = tf.contrib.slim import sys sys.path.append('slim') import matplotlib.pyplot as plt import numpy as np from nets import inception import tensorflow.contrib.slim.nets as nets from preprocessing import inception_preprocessing from lime import lime_image import time o...
"""""" """ Copyright (c) 2021 Olivier Sprangers as part of Airlab Amsterdam 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 ...
import os import random from typing import Optional import numpy import torch from scipy.stats import qmc def set_seed(seed: Optional[int] = None): # ref: https://www.kaggle.com/lars123/neural-tangent-kernel-2 if seed is None: return random.seed(seed) os.environ["PYTHONASSEED"] = str(seed) ...
import numpy as np import spams import sys, getopt import pandas as pd from dl_simulation import * from signature_genes import get_signature_genes, build_signature_model from analyze_predictions import * # from union_of_transforms import random_submatrix, double_sparse_nmf, smaf from union_of_transforms import random_...
""" Functions for evaluating forecasts. """ import numpy as np import xarray as xr #import properscoring as ps import xskillscore as xs import tqdm from tqdm import tqdm def load_test_data(path, var, years=slice('2017', '2018'), cmip=False): """ Args: path: Path to nc files var: variable. Geopo...
import torch import numpy as np from . import Kernel, Parameter, config class LinearKernel(Kernel): def __init__(self, input_dims=None, active_dims=None, name="Linear"): super().__init__(input_dims, active_dims, name) constant = torch.rand(1) self.constant = Parameter(constant, lower=0.0)...
import sys #sys.path.append('/export/zimmerman/khoidang/pyGSM') sys.path.insert(0,'/home/caldaz/module/pyGSM') from dlc import * from pytc import * from de_gsm import * import numpy as np states = [(1,0),(1,1)] charge=0 filepath1 = 'scratch/tw_pyr_meci.xyz' filepath2 = 'scratch/et_meci.xyz' nocc=7 nactive=2 mol1 = ...
from unittest import TestCase import numpy as np from aspire.utils.coor_trans import grid_2d, grid_3d from aspire.utils.matrix import roll_dim, unroll_dim, im_to_vec, vec_to_im, vol_to_vec, vec_to_vol, \ vecmat_to_volmat, volmat_to_vecmat, mat_to_vec, symmat_to_vec_iso, vec_to_symmat, vec_to_symmat_iso import os....
#!/usr/bin/env python # -*- coding: utf-8 -*- # # convert transitscore txt grid file - transit_score_israelyyyymmdd.txt - to an array of transitscore from 1-100 # then convert the array to a raster # output ts_rendered _israelyyyymmdd.png # print('----------------- generate raster from grid file----------------------...
import numpy as np import matplotlib.pyplot as plt from transforms3d.euler import mat2euler from scipy.linalg import expm def load_data(file_name): ''' function to read visual features, IMU measurements and calibration parameters Input: file_name: the input data file. Should look like "XXX_sync_KLT.npz" ...
from pymysql.converters import encoders as convertors import numpy as np """ Those methods extends pymysql convertor for numpy datatypes """ def convert_numpy_int(value, mapping=None): return str(value) def convert_numpy_float(value, mapping=None): s = repr(value) if s in ('inf', 'nan'): raise ...
import cv2,selectivesearch import numpy as np import Intersection as union candidates = set() while True: image = cv2.imread('image/dog.337.jpg') img_lbl, regions = selectivesearch.selective_search(image) for r in regions: candidates.add(r['rect']) for x,y,w,h in candidates: iou = unio...
#!/usr/bin/env python import argparse import os import scipy.constants as sc if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("dir", help="the file name to read") args = parser.parse_args() band_raw_dir = os.getenv("HOME") + "/mlp-Fe/input/Fe/band_data/raw_data/" ...
import numpy as np import codecs, json from json import JSONEncoder class Numpy2JSONEncoder(json.JSONEncoder): ''' This class is to convert the Numpy format Tensorflow Model Weights into JSON format to send it to the server for Federated Averaging ''' def default(self, obj): if isinstance(...
import numpy as N import os def edog_abc_ext2( p, channel_dim, patch_dim, x): xc = x % channel_dim px = xc % patch_dim py = xc / patch_dim '''params: 0: cmu_x 1: cmu_y 2: csigma_x 3: csigma_y 4: ctheta 5: ccdir_a 6: ccdir_b 7: ccdir_c 8: smu_x 9: smu_y 10: ssigma_x 11: ssigma_...
import numpy as np import numpy.random as npr def OPV(S0, K, r, T, option_type): M = 50 I = 10000 sigma = 0.25 def standard_normal_dist(M, I, anti_paths=True, mo_match=True): if anti_paths is True: sn = npr.standard_normal((M + 1, int(I / 2))) sn = np.concatenate((sn...
import os import sqlite3 import pandas as pd import numpy as np from matplotlib import pyplot as plt from flask import Flask from flask import render_template from flask import Response import io from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure con = sql...
""" Adapted from OpenAI Baselines https://github.com/openai/baselines/blob/master/baselines/common/atari_wrappers.py """ from collections import deque import numpy as np import gym import copy import cv2 cv2.ocl.setUseOpenCL(False) def make_env(env, stack_frames = True, episodic_life = True, clip_rewards = False, sca...
import pandas as pd import numpy as np from sklearn.model_selection import train_test_split df1=pd.read_csv('stopwords') b=[] def func(df1): for i in df1['words']: b.append(i) func(df1) import string df = pd.read_csv('emails.csv') def func(a): t=a.split(':')[1] t.lstrip() a=t return a...
################################ΔΗΛΩΣΕΙΣ ΒΙΒΛΙΟΘΗΚΩΝ##################################################################### import io import sys import time from typing import List import uvicorn from fastapi import FastAPI, File, HTTPException, UploadFile from PIL import Image # Κάθε μοντέλο μηχανικής μάθησης φορτώνετ...
from tflearn.data_augmentation import ImageAugmentation from tflearn.data_preprocessing import ImagePreprocessing # import glob # from sklearn import svm from sklearn.ensemble import BaggingClassifier from sklearn.multiclass import OneVsRestClassifier from sklearn.svm import SVC # from itertools import compress import ...
#!/usr/bin/env python # coding: utf-8 # In[1]: import os project_name = "reco-tut-mlh"; branch = "main"; account = "sparsh-ai" project_path = os.path.join('/content', project_name) # In[2]: if not os.path.exists(project_path): get_ipython().system(u'cp /content/drive/MyDrive/mykeys.py /content') import m...
import numpy as np ##from sklearn import hmm from scipy.stats import norm import nwalign as nw from collections import defaultdict import itertools import time from model_tools import get_stored_model, read_model_f5, read_model_tsv onemers = [''.join(e) for e in itertools.product("ACGT")] dimers = [''.join(e) for e in ...
# -*- coding: utf-8 -*- # Author: Tonio Teran <tonio@stateoftheart.ai> # Author: Hugo Ochoa <hugo@stateoftheart.ai> # Copyright: Stateoftheart AI PBC 2021. '''Unit testing the Keras wrapper.''' import os import unittest import numpy as np import inspect from tensorflow.python.keras.engine.functional import Functional ...
#!/usr/bin/python """ Skeleton code for k-means clustering mini-project. """ import pickle import numpy import matplotlib.pyplot as plt import sys sys.path.append("../tools/") from feature_format import featureFormat, targetFeatureSplit def Draw(pred, features, poi, mark_poi=False, name="image.png", f1_n...
""" Stores utilities for use with lg.py and methods.py """ import csv import numpy as np import random from tabulate import tabulate import matplotlib.pyplot as plt def testresultsfiletotable(testDataFile, transitionMatrixFile='', csvName=True): """ Takes a CSV file name as input and returns a usable Python di...
# MINLP written by GAMS Convert at 05/15/20 00:50:47 # # Equation counts # Total E G L N X C B # 43 7 8 28 0 0 0 0 # # Variable counts # x b i s1s s2s sc ...
import cv2 import numpy as np def preprocess(img, input_size, swap=(2, 0, 1)): if len(img.shape) == 3: padded_img = np.ones((input_size[0], input_size[1], 3), dtype=np.uint8) * 114 else: padded_img = np.ones(input_size, dtype=np.uint8) * 114 r = min(input_size[0] / img.shape[0], input_siz...
from camas_gym.envs.camas_zoo_masking import MOVES, CamasZooEnv import numpy as np def update_batch_pre(env, done): # buffer may not be the correct terminology """Creates pre transition buffer data Only one agent may act a time, other agents either carry out their current action again or choose N...
import os import argparse import cv2 import numpy as np import glob import math from objloader_simple import * dir_markers = os.path.join(os.pardir,'markers') dir_chess = os.path.join(os.pardir,'chessboards') dir_objects = os.path.join(os.pardir,'objects') MIN_MATCHES = 30 def capture_boards(): vd = cv2.VideoCap...
import neuromodulation.selection_functions as sf import numpy as np ''' Functions which are used to select the models which pass the criteria New functions can be added, the function should accept criteria, voltages and shoudl return a dictionary, which contain at least boolean key, which returns True or False pass ...
#!/usr/bin/env python # coding: utf-8 # In[ ]: # 安装pandas # pip install Pandas # 运行测试套件 # 运行前需要安装: hypothesis和pytest import pandas as pd # pd.test() # In[5]: # 对象创建 # 传入一些值的列表来创建一个Series,pandas会自动创建一个默认的整数索引. import pandas as pd import numpy as np import pprint s = pd.Series([1,3,5,np.nan,6,8]) print(s) pri...
from fitstools import manage_dtype, mask_fits, assign_header from astropy.io import fits import numpy as np import matplotlib.pyplot as plt import cosmics def calibrate(image, bias, fiber_mask=None, lacosmic=True): image = bias_correct(image, bias, fiber_mask) image = dark_correct(image) image = mask_badp...
import cv2 import os import numpy as np imgpath="./data_dir_crop_y/" outputpath="./data_dir_crop_x/" if not os.path.exists(outputpath): os.makedirs(outputpath) sum =1 for imgx in os.listdir(imgpath): a, b = os.path.splitext(imgx) img = cv2.imread(imgpath + a +b) img = cv2.resize(img, (50, 50), interpolation=c...
from typing import Dict, List import numpy as np from stl_rules.stl_rule import STLRule class ComfortLongitudinalJerk(STLRule): """ This rule implement a Comfort requirement on Longitudinal Jerk. It is based on formalization reported in 5.2.22 of [3: Westhofen et al., 2021]. """ @property ...
import os import sys import json import subprocess import numpy as np from PIL import Image, ImageDraw, ImageFont if __name__ == '__main__': result_json_path = sys.argv[1] video_root_path = sys.argv[2] dst_directory_path = sys.argv[3] if not os.path.exists(dst_directory_path): subprocess.call(...
#!/usr/bin/env python # Copyright 2014-2019 The PySCF Developers. 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 # # U...
import networkx as nx from py2neo import Graph, Node, Relationship import pandas as pd import random from neo4j import GraphDatabase, basic_auth import matplotlib graph = Graph("bolt://localhost:7687", auth=("neo4j", "Password")) driver = GraphDatabase.driver('bolt://localhost',auth=basic_auth("neo4j", "Password")) db...
import pandas as pd import seaborn as sb import numpy as np import matplotlib.pyplot as plt from IPython import embed ##################### ATTENTION WEIGHTS PLOTTING ####################### class AttentionPlotter(object): @classmethod def plot(cls, weights, srcseq=None, dstseq=None, cmap="Greys", scale=1.):...
import numpy from aydin.analysis.camera_simulation import simulate_camera_image from aydin.io.datasets import characters from aydin.it.transforms.variance_stabilisation import VarianceStabilisationTransform def demo_vst(): image = characters() image = image.astype(numpy.float32) * 0.1 noisy = simulate_c...
import numpy as np import quaternion from tbase.shader import Shader from tbase import utils from tbase.utils import Quaternion try: from pyglet.gl import * except: print("WARNING: pyglet cannot be imported but might be required for visualization.") VERTEX_SHADER = [''' varying vec3 normal, lightDir0, lightDi...
""" Line Chart with Points ---------------------- This chart shows a simple line chart with points marking each value. """ # category: line charts import altair as alt import numpy as np import pandas as pd x = np.arange(100) source = pd.DataFrame({ 'x': x, 'f(x)': np.sin(x / 5) }) alt.Chart(source).mark_line(poi...
"""Test file to visualize detected trail lines from videos""" # Usage --> python Trackviz.py 3 # 0 --> Amtala # 1 --> Bamoner # 2 --> Diamond # 3 --> Fotepore # 4 --> Gangasagar import cv2 import json import math import time import sys import matplotlib.pyplot as plt from matplotlib import style i...
import numpy as np import matplotlib.pyplot as plt import datetime import glob2 import xarray as xr import pandas as pd #plt.close("all") pd.options.display.max_columns = None pd.options.display.max_rows = None dircInput1 = 'C:/Users/Chenxi/OneDrive/phd/age_and_fire/data/02_semi_raw/07_ACE_FTS_with_AGEparams/' dircIn...
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from tqdm import tqdm from . import thops from . import modules from . import utils from models.transformer import BasicTransformerModelCausal def nan_throw(tensor, name="tensor"): stop = False if ((tensor!=tensor).an...
import numpy as np import os, errno, json, random import torch from rdkit import Chem, DataStructs from rdkit.DataStructs import * from katanaHLS.models import SimGNNConfig try: from descriptastorus.descriptors import rdDescriptors, rdNormalizedDescriptors except: raise ImportError("Please install pip install git+...
from sklearn.model_selection import KFold from code.classification.classifier import Classifier from code.classification.file import get_training_data from sklearn.metrics import accuracy_score from sklearn.metrics import recall_score from sklearn.metrics import precision_score from sklearn.metrics import f1_score from...
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import ctypes import numpy from nidaqmx._lib import ( lib_importer, wrapped_ndpointer, ctypes_byte_str, c_bool32) from nidaqmx.system.physical_channel import Physica...
# -*- coding: utf-8 -*- # tomolab # Michele Scipioni # Harvard University, Martinos Center for Biomedical Imaging # University of Pisa # Import an interfile volume as an Image3D and export. from ...Transformation.Transformations import Transform_Scale from ...DataSources.FileSources.interfile import load_interfile ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jun 4 20:39:07 2020 @author: JianyuanZhai """ import pyomo.environ as pe import numpy as np import time DOUBLE = np.float64 class DDCU_Nonuniform(): def __init__(self, intercept = True): self.intercept = intercept self.ddcu = DDCU_...
#!/usr/bin/env python # -*- coding: utf-8 -*- from datetime import datetime try: import numpy as np except ImportError as e: print("Failed to do 'from scipy.interpolate import interp1d', " "scipy may not been installed properly: %s" % e) try: from scipy.interpolate import interp1d except ImportE...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Aug 9 17:41:59 2020 @author: ullaheede """ import matplotlib.pyplot as plt import cartopy.crs as ccrs import numpy as np import xarray as xr import xesmf as xe import pandas as pd import glob as glob import os from pylab import * import matplotlib.gr...
''' ViZDoom wrapper ''' from __future__ import print_function import sys import os vizdoom_path = 'C://Users//Rzhang//Anaconda3//envs//recognition//Lib//site-packages//vizdoom' sys.path = [os.path.join(vizdoom_path,'bin/python3')] + sys.path import vizdoom print(vizdoom.__file__) import random import time import num...
import numpy as np from matplotlib import pyplot as plt from scipy.cluster.hierarchy import dendrogram, linkage from scipy.spatial.distance import pdist X=np.array([[1,2],[2,1],[3,4],[4,3]]) Z=linkage(X,'ward') dendrogram(Z) plt.show()
""" helper functions for Helmsman """ # system packages from __future__ import print_function import os import sys import warnings import itertools import collections import csv from joblib import Parallel, delayed from logging import StreamHandler, getLogger as realGetLogger, Formatter from colorama import Fore, Back...
#!/usr/bin/env python3 # Copyright 2018 Lael D. Barlow # # 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 ...
import pytest import numpy as np from deduplipy.string_metrics.string_metrics import (length_adjustment, adjusted_ratio, adjusted_token_sort_ratio, adjusted_token_set_ratio, adjusted_partial_ratio) def test_length_adjustment(): assert length_adjustment('', '')...
# coding: utf-8 # In[15]: from matplotlib import pyplot as plt import numpy as np #get_ipython().run_line_magic('matplotlib', 'inline') x_old, x_new, gamma, prec = 0, 6, 0.01, 0.00001 f = lambda x: x**4 - 3 * x**3 + 2 df = lambda x: 4*(x**3) - 9*(x**2) to_plot =[] i = 0 to_plot.append(x_new) while abs(x_new - x...
""" * Program to practice with OpenCV drawing methods. """ import skimage.io import numpy as np import random # create the black canvas image = np.zeros(shape=(600, 800, 3), dtype="uint8") # WRITE YOUR CODE TO DRAW ON THE IMAGE HERE # display the results skimage.io.imshow(image)
""" RegionFile class. Reads and writes chunks to *.mcr* (Minecraft Region) and *.mca* (Minecraft Anvil Region) files """ from __future__ import absolute_import, division import logging import os import struct import zlib import time import numpy from mceditlib import nbt from mceditlib.exceptions import ...
# Authors: Stephane Gaiffas <stephane.gaiffas@gmail.com> # License: BSD 3 clause """ Comparisons of decision functions ================================= This example allows to compare the decision functions of several random forest types of estimators. The following classifiers are used: - **AMF** stands for `AMFClas...
import numpy as np from numpy.random import default_rng, Generator from .metric import accuracy from ..classification import KNNClassifier from ml_utils import classification def k_fold_split(n_splits: int, n_instances: int, rng: Generator = default_rng()) -> list: """ Split n_instances into n mutually exclusive ...
""" DCG and NDCG. TODO: better docs """ import numpy as np from . import gains, Metric from six import moves _EPS = np.finfo(np.float64).eps range = moves.range class DCG(Metric): def __init__(self, k=10, gain_type='exp2'): super(DCG, self).__init__() self.k = k self.gain_type = gain_t...
"""The classes in this file are domain specific, and therefore include specifics about the design space and the model parameters. The main jobs of the model classes are: a) define priors over parameters - as scipy distribution objects b) implement the `predictive_y` method. You can add whatever useful helper functi...
import os import io import gzip import pickle import tarfile import logging import torch import numpy as np import utils from model import embedding def add_embed_arguments(parser, name=None): if name is None: prefix = "" else: prefix = f"{name}-" parser.add_argument(f"--{prefix}embed-ty...
import copy from typing import Union, List, Callable import numpy as np from interpreter import imageFunctions as imageWrapper from interpreter import lexer as lexer from interpreter import tokens as tokens from interpreter import movementFunctions as movement from interpreter import colors as colors from interpreter...
#!/usr/bin/env python # -*- coding: utf-8 -*- """"WRITEME""" import numpy as np import matplotlib.pyplot as plt import pygimli as pg def drawFirstPicks(ax, data, tt=None, plotva=False, marker='x-'): """Naming convention. drawFOO(ax, ... )""" return plotFirstPicks(ax=ax, data=data, tt=tt, ...
"""Utility functions for real-space grid properties """ import numpy as np import matplotlib import matplotlib.cm as cm import matplotlib.pyplot as plt import pandas as pd import struct from .conversions import * from scipy.interpolate import griddata rho = np.zeros(2) rho_val = np.zeros(2) unitcell = np.zeros(2) grid...
#Automatic_keyboard_recognition import numpy as np import math import statistics as stats import cv2 as cv2 class Keyboard_auto_find_and_transform: def __init__(self,initial_frame,target_dimensions): print("Finding Keyboard") self.target_dimensions = target_dimensions self.p_mat = Automatic_keyboard_r...
""" NLTK Word Frequency Summarization Modified : Shashank Original author: Akash P """ import nltk import hashlib import numpy as np from nltk.corpus import stopwords from nltk.stem import PorterStemmer from nltk.tokenize import word_tokenize, sent_tokenize from hashlib import sha224 from SummarizationInterface impo...
import numpy as np import torch import torch.nn as nn import torch.utils.data import torch.utils.data.distributed from numpy.core.fromnumeric import prod from .autoencoder import utils from .autoencoder.moco import builder from .autoencoder.moco import loader from .autoencoder.model_ae_moco import AutoEncoder from .d...
# -*- coding: utf-8 -*- """test_resultsreconstruction Tests that a single depletion step is carried out properly. The entire sequence from cross section generation to depletion execution is tested. Results are compared against pre-generated data using a different code. Created on Thu Oct 28 08:59:44 2021 @author: Mat...
#!/usr/bin/python import glob import math import os import shutil import struct import sys import csv import Queue import thread import subprocess from optparse import OptionParser from osgeo import gdalconst from osgeo import gdal from osgeo import osr from numpy import * import numpy as np import utilities def...
import os, sys import cv2 import numpy as np from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * from qgis.gui import QgsMapCanvas, QgsMapToolPan, QgsMapToolZoom, QgsMapToolIdentify from qgis.core import QgsProject, QgsApplication, QgsVectorLayer, QgsRasterLayer from Dlg_unsupervi...
import numpy as np from collections import defaultdict def pairwise_view(target_station, next_station, mismatch='error'): if target_station is None or next_station is None: return ValueError("The data is empty.") if target_station.shape != next_station.shape: return None # ValueError("Paired ...
# import the necessary packages from imutils.video import VideoStream from imutils import face_utils import imutils import time import dlib import cv2 import numpy as np import math import transformation import utils # custom imports import rotation_matrix_util as rmu import client def handle_drone_directions(img, r...
import random import cv2 import matplotlib.pyplot as plt import numpy as np from word_segmentation import extract_words_from_image def word_image_preprocess(img, imgSize=(128, 32), dataAugmentation=False): """put img into target img of size imgSize, transpose for TF and normalize gray-values""" # there are...
#!/usr/bin/env python3 import itertools import os.path import pickle from typing import Any, Generator, Hashable, Iterable, NamedTuple, Sequence, Tuple import numpy as np from rosplane_msgs.msg import State, Current_Path from rosbag_to_traces import process_bag_file, dist_trace_to_mode_seg_tuples, aggregate_by_mode...
import numpy as np np.random.seed(2591) class DAGANDataset(object): def __init__(self, batch_size, last_training_class_index, reverse_channels, num_of_gpus, gen_batches): """ :param batch_size: The batch size to use for the data loader :param last_training_class_index: The final index for ...
import unittest import neuralnetsim import networkx as nx class TestNetworkAnalysis(unittest.TestCase): def test_calc_mu(self): graph = nx.DiGraph() graph.add_node(1, com=1) graph.add_node(2, com=1) graph.add_node(4, com=2) graph.add_node(5, com=3) graph.add_edge(1,...
from dipsim import multiframe, util, detector, illuminator, microscope, util import numpy as np import matplotlib.pyplot as plt import os; import time; start = time.time(); print('Running...') # Main input parameters n_pts = 1000 ill_types = ['unpolarized', 'unpolarized', 'wide'] ill_pols = [0, np.pi/4, np.pi/2] det_...
from base import BaseDataSet, BaseDataLoader from utils import pallete import numpy as np import os import scipy import torch from PIL import Image import cv2 from torch.utils.data import Dataset from torchvision import transforms import json class CUS_Dataset(BaseDataSet): def __init__(self, **kwargs): se...
from sklearn.linear_model import Lasso import numpy as np def norm_entropy(p): n = p.shape[0] return -p.dot(np.log(p + 1e-12) / np.log(n + 1e-12)) def entropic_scores(r): r = np.abs(r) ps = r / np.sum(r, axis=0) hs = [1 - norm_entropy(p) for p in ps.T] return hs def nrmse(predicted, target...
# -------------------------------------------------------- # Written by Yufei Ye (https://github.com/JudyYe), modified by Zhiqiu Lin (zl279@cornell.edu) # -------------------------------------------------------- from __future__ import print_function import argparse import os import os.path as osp import numpy as np f...