arxiv_id
stringlengths
0
16
text
stringlengths
10
1.65M
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Example of the thermal energy storage (TES) class. """ from __future__ import division import numpy as np import pycity_base.classes.supply.thermal_energy_storage as tes import pycity_base.classes.timer import pycity_base.classes.weather import pycity_base.classes.pr...
import os import numpy as np from datetime import datetime from tqdm import tqdm import random import torch import torch.optim as optim from .utils import register_algorithm, Algorithm, acc from src.data.utils import load_dataset from src.models.utils import get_model import numpy as np def load_data(args): "...
import math import numpy as np from .utilities import array2str from .BaseTokenizer import BaseTokenizer class VectorTokenizer(BaseTokenizer): def __init__(self, num_embeddings: int, vector_size: int, padding_idx: int=0, random_seed: int=0): ...
import os import albumentations as A import cv2 import numpy as np import pandas as pd import torch from pandas import DataFrame from torch.utils.data import Dataset, DataLoader from config import Config from constants import DEEPER_FORENSICS from training.datasets.transform import create_train_transform, create_val_...
import numpy as np import random import torch import torch.nn as nn import torch.nn.functional as F import math import copy import time import logging from torch.autograd import Variable import pdb from src.components.utils import * from src.components.encoder import * from src.components.decoder import * ...
""" Evaluate the model. """ import numpy as np import json import pickle import os from model import trainer from itertools import product from model.displacement import TARGETS, LAGS from model.displacement.model import Trainer from model.displacement.features import Generator PERIODS = [{'train_years': (1995, Y ...
import tensorflow as tf print('Using Tensorflow '+tf.__version__) import matplotlib.pyplot as plt import sys # sys.path.append('../') import os import csv import numpy as np from PIL import Image import time import cv2 import src.siamese as siam from src.visualization import show_frame, show_crops, show_scores width ...
from striped.client import CouchBaseBackend import numpy as np from numpy.lib.recfunctions import rec_append_fields import fitsio, healpy as hp from astropy.io.fits import Header from striped.common import Tracer T = Tracer() def dict_to_recarray(dct, keys=None): # cnmap : dct key -> column name in the resulting...
import os import numpy as np import chainer from chainer import Chain, Variable from mnist_cnn import CnnModel def predict(img): print("lets predict") model=CnnModel() chainer.serializers.load_npz(os.path.join('result','cnn_10.npz'),model) model.to_cpu() x=Variable(np.array([[img]])) result = ...
import numpy as np from astropy import units as u import pytest from ctapipe.image.cleaning import tailcuts_clean from ctapipe.image.hillas import hillas_parameters, HillasParameterizationError from ctapipe.io import event_source from ctapipe.reco.HillasReconstructor import HillasReconstructor, HillasPlane from ctapip...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 9/15/20 11:16 PM # @Author : anonymous # @File : pyquil-topo.py import networkx as nx from pyquil.api._quantum_computer import _get_qvm_with_topology from pyquil.device import NxDevice, gates_in_isa from pyquil import Program, get_qc from pyquil.gates impo...
""" Copyright (c) 2019-2022, Zihao Ding/Carnegie Mellon University All rights reserved. ******************************************************************** Project: eu2qu.py MODULE: util Author: Zihao Ding, Carnegie Mellon University Brief: ------------- Refer to source code in https://github.com/marcdegraef/3Drot...
from typing import Any import jax from jax import numpy as jnp import numpy as np from flax import struct @struct.dataclass class TargetState: done: jnp.ndarray reward: jnp.ndarray obs: jnp.ndarray class OneStepEnvironment(object): def __init__(self): self.action_size = 1 def reset(s...
# Ger Hanlon, 13.04.2018 # The describe function for the 2018 Iris Data-Set project import pandas as pd # Import the panda library and reference it is pd- his library is used for data manipulation and analysis import numpy as np # Import the numpy library and reference it is np- This library is useful for adding suppo...
# Copyright 2020 The Magenta Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
#!/usr/bin/python # Author: GMFTBY # Time: 2019.11.8 ''' Chat script, show the demo ''' import torch import torch.nn as nn import torch.nn.init as init import torch.nn.functional as F import numpy as np import math import argparse from utils import * from data_loader import * from model.seq2seq_attention import Se...
# -*- coding: utf-8 -*- """ Created on Wed Sep 5 14:27:35 2018 @author: ensur """ import os import numpy as np import pickle # generate all characters dict lines = open('cjkvi-ids/ids.txt',encoding='UTF-8').readlines()[2:] char_seq = {} char_seq['⿰'] = '⿰' char_seq['⿱'] = '⿱' char_seq['⿵'] = '⿵' ch...
from __future__ import print_function, division import unittest from hotspots.grid_extension import Grid, _GridEnsemble import numpy as np from glob import glob import os from os.path import join, exists import shutil class TestEnsembleSyntheticData(unittest.TestCase): @staticmethod def make_test_data(): ...
import numpy.random as rd import tensorflow as tf from toolbox.einsum_re_writter.einsum_re_written import einsum_bi_bij_to_bj a = rd.rand(2,3) b = rd.rand(2,3,4) tf_a = tf.constant(a) tf_b = tf.constant(b) prod1 = tf.einsum('bi,bij->bj',tf_a,tf_b) prod2 = einsum_bi_bij_to_bj(tf_a,tf_b) sess = tf.Session() np_prod...
#!/usr/bin/env python2 # -*- coding: utf8 -*- import sys sys.path.append("../imposm-parser") import time import math import yaml import pyproj import networkx as nx import premap_pb2 as pb import types_pb2 as pbtypes from utils import angle,int2deg,deg2int,distance, nodeWays, deleteAloneNodes from Map import Map fr...
from __future__ import division, print_function import numpy as np from .lightcurve import LightCurve __all__ = ['cdpp'] def cdpp(flux, **kwargs): """A convenience function which wraps LightCurve.cdpp(). For details on the algorithm used to compute the Combined Differential Photometric Precision (CDP...
#!/usr/bin/env python3 #Compute entropy over AnnData objects import argparse import numpy as np import pandas as pd import scanpy as sc import anndata import scipy from math import log def shannon_entropy (x, b_vec, N_b): tabled_values = b_vec[x > 0].value_counts()/ len(b_vec[x >0]) #class 'pandas.core.se...
import ctypes import glob import os import numpy as np from multiprocessing import cpu_count # Build the extension function (this should be negligible performance-wise) fl = glob.glob(os.path.join(os.path.dirname(__file__), "ctransforms*"))[0] def morlet_transform_c(data, nu, convergence_extent=10.0, fourier_b = 1,...
import numpy as np import matplotlib.pyplot as plt data = np.arange(10) plt.plot(data) fig = plt.figure() # create figure object ax1 = fig.add_subplot(2, 2, 1) # add 2 x 2 subplots to fig, initialize at pos 1 ax2 = fig.add_subplot(2, 2, 2) ax3 = fig.add_subplot(2, 2, 3) plt.plot([1.5, 3.5, -2, 1.6]) # draw on las...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may...
# author: GROUP 12 # date: 2021-11-19 '''This script downloads a data file in csv format. This script takes an unquoted data file path to a csv file, the name of the file type to write the file to (ex. csv), and the name of a file path to write locally (including the name of the file). Usage: data_download.py --...
from sympy import symbols, cos, sin from sympy.external import import_module from sympy.utilities.matchpy_connector import WildDot, WildPlus, WildStar matchpy = import_module("matchpy") x, y, z = symbols("x y z") def _get_first_match(expr, pattern): from matchpy import ManyToOneMatcher, Pattern matcher = M...
''' does a few things. First, it counts the total number of the 4 orientations of read pairs (left-most first, ++, +-, -+, --). This is Erez's in-in, in-out, out-in, out-out . Second, it counts the same for only reads that with distances less than 2000 bp, and prints out a file with the distances for the four types. ...
# -*- coding: utf-8 -*- import numpy as np import scipy.stats as st import scipy.signal as sig from collections import namedtuple from scipy.constants import c, physical_constants tup = namedtuple('tup','wl t data') def add_to_cls(cls): def function_enum(fn): setattr(cls, fn.__name__, staticm...
#!/usr/bin/python # This script parses the log file generated by the connected protocol FileLog logger # How to use : # python plot.py [file] [sampling] [first] [end] # [file] the file log # [sampling] frequency of logging in seconds # [first] offset of the first point to be displayed in graph # ...
from .star import BlackbodyStar import numpy as np import os from taurex.constants import MSOL import math class PhoenixStar(BlackbodyStar): """ A star that uses the `PHOENIX <https://www.aanda.org/articles/aa/abs/2013/05/aa19058-12/aa19058-12.html>`_ synthetic stellar atmosphere spectrums. These spe...
from collections import Counter from copy import copy import json import numpy as np import re import logging from stanza.models.common.utils import ud_scores, harmonic_mean from stanza.utils.conll import CoNLL from stanza.models.common.doc import * logger = logging.getLogger('stanza') def load_mwt_dict(filename): ...
import numpy as np import matplotlib.pyplot as plt import seaborn as sns from mpl_toolkits.mplot3d import Axes3D def matrix_scatter_plot(matrix, path, filename, dtype): coordinates = np.where(matrix == 1) x = coordinates[0] y = coordinates[1] t = coordinates[2] sns.set_style("whitegrid", {"axes.gr...
import argparse import inspect import json import logging import os import pickle import shutil import sys import time import numpy as np from nasbench_analysis.search_spaces.search_space_1 import SearchSpace1 from nasbench_analysis.search_spaces.search_space_2 import SearchSpace2 from nasbench_analysis.search_spaces...
# -*- coding: UTF-8 -*- import tkinter as tk from tkinter import * from PIL import ImageTk, Image from tkinter import filedialog import glob import os import csv import pandas as pd import subprocess from pygame import mixer from tkinter import messagebox import matplotlib.pyplot as plt from scipy import signal from sc...
from mpi4py import MPI comm = MPI.COMM_WORLD rank = comm.Get_rank() import numpy as np N = 10000 n_procs = comm.Get_size() print("This is process", rank) # Create an array x_part = np.random.uniform(-1, 1, int(N/n_procs)) y_part = np.random.uniform(-1, 1, int(N/n_procs)) hits_part = x_part**2 + y_part**2 < 1 hit...
import cdutil, pickle import numpy as np import scipy.stats as stats import matplotlib.pyplot as plt import matplotlib.patches ...
""" Cartpole Agent with Tensorflow 2 Reference: https://github.com/awjuliani/DeepRL-Agents/blob/master/Vanilla-Policy.ipynb """ import tensorflow as tf import numpy as np import gym # Load cartpole environment env = gym.make("CartPole-v0") GAMMA = 0.99 learning_rate = 0.01 state_size = 4 num_actions = 2 hidden_size...
import pandas as pd import numpy as np object = pd.read_pickle('adj_matrix.p') print(object) print(type(object)) print(object.shape[0])
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Feb 20 17:47:40 2018 @author: JSen """ import numpy as np import matplotlib.pyplot as plt from numpy import loadtxt, load import os from scipy import optimize from scipy.optimize import minimize from sklearn import linear_model import scipy.io as spio ...
from pathlib import Path from pandas import read_csv, to_datetime, DataFrame from pylab import arange, arcsin, array, cos, pi, sin, sqrt from scipy.interpolate import interp1d from warnings import warn # Last inn gpxpy kun dersom det er installert try: import gpxpy HAR_GPXPY = True except ImportError: HAR_G...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Dec 23 16:08:04 2020 @author: sariyanidi @description: This script takes a trained keras model, and converts it into a format that's recognizable by OpenCV """ from tensorflow.python.framework.convert_to_constants import convert_variab...
from checkers.game import Game import numpy as np import copy import operator import random def main(): game = Game() game.consecutive_noncapture_move_limit = 100 while (not game.is_over()): if game.whose_turn() == 1: human_move( game) # if you want the bot to play for ...
import re import torch from batchgenerators.dataloading import MultiThreadedAugmenter import numpy as np import os from batchgenerators.dataloading.data_loader import DataLoaderFromDataset from batchgenerators.datasets.cifar import HighPerformanceCIFARLoader, CifarDataset from batchgenerators.transforms.spatial_transfo...
import numpy as np from math import sqrt class PondingLoadCell2d: id = '' # Load cell ID xI = 0.0 # X coordinate of Node I yI = 0.0 # Y coordinate of Node I xJ = 0.0 # X coordinate of Node J yJ = 0.0 # Y coordinate of Node J dyI = 0.0 # Y defl...
################################################################################ # Copyright (C) 2011-2012,2014 Jaakko Luttinen # # This file is licensed under the MIT License. ################################################################################ """ Module for the categorical distribution node. """ import...
import numpy as np from ceRNA.Calculations import estimate_parameters, rmse_vector, percent_error_vector class Estimator: def __init__(self, real_vector: np.ndarray, tests: np.ndarray): self.real_vector = real_vector self.estimate_size = len(real_vector) self.tests = tests self.num...
from Model import BNInception_gsm import pandas as pd import numpy as np import torch from torch import nn import os import random import cv2 from Dataset import DataGenerator from sklearn.model_selection import train_test_split from torch.utils.data import DataLoader from torch import optim from torch.backends import ...
__author__ = "Tomasz Rybotycki" import abc from typing import List from numpy import ndarray class SimulationStrategyInterface(abc.ABC): @classmethod def __subclasshook__(cls, subclass): return (hasattr(subclass, "simulate") and callable(subclass.simulate)) @abc.abstractmethod ...
import tensorflow as tf import numpy as np from network_models.loss import l2_loss, l2_loss_masked class Policy_net: def __init__(self, name: str, env): """ :param name: string :param env: gym env """ ob_space = env.observation_space act_space = env.action_space ...
""" Classes that handle array indexing. """ import sys import numpy as np from numbers import Integral from itertools import zip_longest from openmdao.utils.general_utils import shape2tuple from openmdao.utils.om_warnings import issue_warning, OMDeprecationWarning def array2slice(arr): """ Try to convert an...
"""Whittaker filter V-curve optimization os S.""" from math import log, sqrt import numpy from numba import guvectorize from numba.core.types import float64, int16 from ._helper import lazycompile from .ws2d import ws2d @lazycompile( guvectorize( [(float64[:], float64, float64[:], int16[:], float64[:])]...
""" data_io - data_io.OutputReader is a class for reading the output simulated data. - data_io.MFHandler is a class for reading and writing the input to the network simulation (mossy fiber information). - repack_dict converts the spike time data in a dictionary form to a table in a pandas.DataFrame format. """ impor...
import os import subprocess import sys import numpy import argparse import pysam import vcf import pybedtools import logging from collections import defaultdict, OrderedDict from utils import makedirs def uint(value): if not value.isdigit(): raise argparse.ArgumentTypeError("%s is not digit-only" % value) ret = in...
import math import torch import cv2 import torch.nn as nn import numpy as np ''' Implement for Camera base shift. This Code is refer to released GeoNet code. Author: Guo Shi Time: 2019.09.18 ''' def pixel2cam(depth, pixel_coords, intrinsics, is_homogeneous=True): """Transforms coordinates in the pixel frame to ...
#!/usr/bin/env python import numpy as np import cv2 cv2.namedWindow('image', cv2.WINDOW_NORMAL) cv2.waitKey(0) cv2.destroyAllWindows()
#!/usr/bin/python3 import os #os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' import tensorflow as tf import numpy as np #import pandas as pd from random import randint import matplotlib.pyplot as plt keras = tf.keras from keras.models import Sequential, load_model from keras.layers.core import Dense, Dropout, Activation, ...
import numpy as np import os import matplotlib.pyplot as plt import skimage.io from mpl_toolkits.mplot3d import Axes3D np.set_printoptions(suppress=True) from matplotlib import cm from sklearn.neighbors import LocalOutlierFactor from imblearn.under_sampling import ClusterCentroids import warnings warnings.filterwarning...
import ba import numpy as np import time import matplotlib.pyplot as pl #import pandas power = 7 # Number of vertices - for each time t -> t + 1, add new vertex N_vertex = 10**power # Probability mode for adding edges prob = 1 # Pure preferential attachment # Number of edges added per vertex m = 6 ...
''' ''' import os import h5py import numpy as np # -- astropy -- from astropy import units as u # -- desi -- from desispec.io import read_spectra # -- feasibgs -- from feasibgs import util as UT from feasibgs import catalogs as Cat from feasibgs import forwardmodel as FM # -- plotting -- import matplotlib as mpl...
import numpy as np import tensorflow as tf import tensorflow.contrib.slim as slim from decoder.mlp import mlp_layer def deconv_layer(output_shape, filter_shape, activation, strides, name): W = tf.get_variable(shape=filter_shape, initializer=tf.contrib.layers.xavier_initializer(), name=name + '_W') # use output ...
#!/usr/bin/env python # encoding: utf-8 # The MIT License (MIT) # Copyright (c) 2018-2020 CNRS # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limita...
import sqlite3 import numpy as np from convlab2.policy.mdrg.multiwoz.utils.nlp import normalize # loading databases domains = ['restaurant', 'hotel', 'attraction', 'train', 'taxi', 'hospital']#, 'police'] dbs = {} for domain in domains: db = 'db/{}-dbase.db'.format(domain) conn = sqlite3.connect(db) c = ...
import pandas as pd import numpy as np import sklearn import matplotlib.pyplot as plt import json import os import time import logging font={ 'family':'STSONG' } plt.rc("font",**font) # plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False logging.basicConfig(level=logging.DEBU...
import numpy as np from torch import nn from torch.nn import functional as F from .global_config import HyperParam, update_hyperparams class SE_Block(nn.Module): """credits: https://github.com/moskomule/senet.pytorch/blob/master/senet/se_module.py""" def __init__(self, c, r=16): super().__init__() ...
# -*- coding: utf-8 -*- """ re-do streamlit with: a. Toes, SVL, Traplists b. Toes """ import pandas as pd import numpy as np import streamlit as st import itertools from itertools import chain def app(): st.write("""## Search by missing toes only""") #--- 1. Load data def load_file(filename...
# -*- coding: utf-8 -*- # tomolab # Michele Scipioni # Harvard University, Martinos Center for Biomedical Imaging # University of Pisa __all__ = ["load_motion_sensor_data"] from ...Transformation.Transformations import Transform_Affine from ...Transformation import transformations_operations as tr import numpy as np...
""" Script for observing something during the day. - Open / close dome. - Slew to target. - Focus cameras. - Take observations. - Verify safety at each step (solar distance, weather etc). NOTE: This script will be superceeded by scheduler when we can impose arbitrary horizon ranges for a given target. """ import argpa...
# Copyright 2008-2018 pydicom authors. See LICENSE file for details. """Unit tests for the JPEG-LS Pixel Data handler.""" import os import sys import pytest import pydicom from pydicom.filereader import dcmread from pydicom.data import get_testdata_file jpeg_ls_missing_message = ("jpeg_ls is not available " ...
# Test the exploration module import os import numpy as np import tempdir from activepapers.storage import ActivePaper from activepapers import library from activepapers.exploration import ActivePaper as ActivePaperExploration def make_local_paper(filename): paper = ActivePaper(filename, "w") paper.data.cre...
# /user/bin/python3 import numpy as np import cv2 # utility function to display image def imshow(filename, image): cv2.imshow(filename,image) cv2.waitKey(0) cv2.destroyAllWindows() img = np.zeros((256, 256, 1), np.uint8) intensity = 0 for i in range(256): img[i] = intensity intensity += 1 imshow('greyscale ra...
import numpy as np import torch # https://github.com/davisvideochallenge/davis/blob/master/python/lib/davis/measures/jaccard.py def eval_iou(annotation, segmentation): """ Compute region similarity as the Jaccard Index. Arguments: annotation (ndarray): binary annotation map. segmentation (...
import torch import random import numpy as np from time import sleep from copy import deepcopy from core.common import ParamDict from core.utilities import decide_device from torch.multiprocessing import Process, Pipe, Value, Lock # import interface class instead of its implementation from core.agent.agent import Agent...
import logging import numpy as np from pylops.basicoperators import Diagonal, BlockDiag, Restriction, \ HStack from pylops.utils.tapers import taper3d from pylops.signalprocessing.Sliding2D import _slidingsteps logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.WARNING) def Sliding3D(Op, dim...
import tensorflow as tf import numpy as np ''' Very simple feature extractor. Basically copying anything from MNIST classifier tutorial on tensorflow website, except that we only choose first several layers since we only need features generated in the middle of neural network and the final outputs are not needed. Ar...
import sys, string, re, os, commands, time from scipy import stats import scipy as sp import numpy as np ################## Class Env_var ###################### class Env_var: def __init__(self, v): self.std_env_list = [] self.env_list = [] v = v.replace('\r\n', '') v = ...
import os,sys import numpy as np import yaml import scipy.integrate as integrate import matplotlib.pyplot as plt import math """ ------------ Parameters """ with open('configure.yml','r') as conf_para: conf_para = yaml.load(conf_para,Loader=yaml.FullLoader) """ ------------ wavefront_initialize >> input pixelsi...
from tkinter import * root = Tk() root.withdraw() from sklearn import linear_model import numpy as np from matplotlib.backends.backend_tkagg import ( FigureCanvasTkAgg, NavigationToolbar2Tk) # Implement the default Matplotlib key bindings. import matplotlib.pyplot as plt import numpy as np class Custombox: ...
import numpy as np import os import geopandas as gpd import pandas as pd url_list = \ ['https://opendata.arcgis.com/datasets/7015d5d46a284f94ac05c2ea4358bcd7_0.geojson', # noqa: E501 'https://opendata.arcgis.com/datasets/5fc63b2a48474100b560a7d98b5097d7_1.geojson', # noqa: E501 'https://op...
# -*- coding: utf-8 -*- """HDF5 Dataset Generators The generator class is responsible for yielding batches of images and labels from our HDF5 database. Attributes: dataset_path (str): Path to the HDF5 database that stores our images and corresponding class labels. batch_size (int): Size of min...
#exec(open('templates\\algs_compare_regression.py').read()) # testing different classification algorithms import subprocess as sp import pandas as pd import sklearn.model_selection as ms import sklearn.linear_model as sl import sklearn.metrics as sm import sklearn.discriminant_analysis as da import sklearn.neighbors as...
#!/usr/bin/env python import rospy import numpy as np from std_msgs.msg import Float64 import math def talker(): pub_theta1 = rospy.Publisher('/robot_arm/theta1_controller/command', Float64, queue_size=10) pub_theta2 = rospy.Publisher('/robot_arm/theta2_controller/command', Float64, queue_size=10) pu...
import sys, os, math from ortools.constraint_solver import pywrapcp from ortools.constraint_solver import routing_enums_pb2 import matplotlib.pyplot as plt import numpy as np from six.moves import xrange #from urllib3.connectionpool import xrange def getopts(argv): opts = {} # Empty dictionary to store key-value ...
# coding=utf-8 # Copyright 2018 The TF-Agents Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law...
"""Object for storing experimental results. Matthew Alger The Australian National University 2016 """ import json import h5py import numpy class Results(object): """Stores experimental results.""" def __init__(self, path, methods, n_splits, n_examples, n_params, model): """ path: Path to t...
# Copyright (c) Facebook, Inc. and its affiliates. import itertools import json import logging import numpy as np import os from collections import OrderedDict import PIL.Image as Image import pycocotools.mask as mask_util import torch from detectron2.data import DatasetCatalog, MetadataCatalog from detectron2.utils.c...
# coding=utf-8 """ .. moduleauthor:: Torbjörn Klatt <t.klatt@fz-juelich.de> """ from copy import deepcopy import numpy as np from pypint.utilities import assert_is_instance, assert_condition, class_name class IDiagnosisValue(object): """Storage and handler of diagnosis values of iterative time solvers. Co...
""" ======================= Transform Concatenation ======================= In this example, we have a point p that is defined in a frame C, we know the transform C2B and B2A. We can construct a transform C2A to extract the position of p in frame A. """ print(__doc__) import numpy as np import matplotlib.pyplot as p...
import os import jsonlines import numpy as np import torch from torch.utils.data import Dataset class DatasetEL(Dataset): def __init__( self, tokenizer, data_path, max_length=32, max_length_span=15, test=False, ): super().__init__() self.tokeniz...
import glob import io import os import sys from pathlib import Path import pytest import numpy as np import torch from PIL import Image, __version__ as PILLOW_VERSION import torchvision.transforms.functional as F from common_utils import get_tmp_dir, needs_cuda, assert_equal from torchvision.io.image import ( dec...
from fastFM import als from scipy import sparse class FactorizationMachine(): ''' A wrapper around an implementation of Factorization Machines ''' def __init__(self): self.model = als.FMRegression(n_iter=1000, init_stdev=0.1, rank=2, l2_reg_w=0.1, l2_reg_V=0.5) def fit(self, features, target): self.model.fi...
"""Compute depth maps for images in the input folder. """ # import os # import glob import torch # from monodepth_net import MonoDepthNet # import utils # import matplotlib.pyplot as plt import numpy as np import cv2 # import imageio def run_depth(img, model_path, Net, utils, target_w=None,f=False): """Run MonoDe...
# -*- coding: utf-8 -*- import cv2 from DQLBrain import Brain import numpy as np from collections import deque import sqlite3 import pygame import time import game_setting import importlib SCREEN_X = 288 SCREEN_Y = 512 FPS = 60 class AI: def __init__(self, title,model_path,replay_memory,current_...
import math import fire import jax import jax.numpy as jnp import numpy as np import opax import pax import tensorflow as tf from PIL import Image from tqdm.auto import tqdm from data_loader import load_celeb_a from model import GaussianDiffusion, UNet def make_image_grid(images, padding=2): """Place images in ...
""" Mapping indices for complexes / multi-domain sequences to internal model numbering. Authors: Thomas A. Hopf Anna G. Green (MultiSegmentCouplingsModel) """ from collections import Iterable from copy import deepcopy from evcouplings.couplings.model import CouplingsModel import pandas as pd import numpy as np ...
#!/usr/bin/env python """ \example xep_sample_direct_path.py Latest examples is located at https://github.com/xethru/XeThru_ModuleConnector_Examples or https://dev.azure.com/xethru/XeThruApps/_git/XeThru_ModuleConnector_Examples. # Target module: # X4M200 # X4M300 # X4M03(XEP) # Introduction: This is an example show...
import datetime as dt from functools import lru_cache from pathlib import Path import numpy as np import pandas as pd import plotly.graph_objects as go from loguru import logger class CompoMapper(object): """ Class to map and plot the previously downloaded ETF composition. """ def __init__(self): ...
import math as m import numpy as np import matplotlib.pyplot as plt from coswindow import coswin print("---------------") print("INPUT PARAMETER") print("---------------") a = float(input("Taper Ratio \t\t:")) dt = float(input("Sampling Time \t\t:")) f = float(input("Signal Frequancey \t:")) if a == dt: print("Sam...
import os import json import numpy as np import dgl import torch as th from ogb.nodeproppred import DglNodePropPredDataset partitions_folder = 'outputs' graph_name = 'mag' with open('{}/{}.json'.format(partitions_folder, graph_name)) as json_file: metadata = json.load(json_file) num_parts = metadata['num_parts'] ...
#!/usr/bin/env python import luigi import os import numpy as np import subprocess import glob import pickle from astra.tasks import BaseTask from astra.tasks.io import ApPlanFile from sdss_access.path import path from apogee_drp.utils import apload,yanny from luigi.util import inherits # Inherit the parameters needed...