text
string
# This file shows some example usage of Python functions to read an OCT file. # To use exectute this test reader, scroll to the bottom and pass an OCT file to the function unzip_OCTFile. # Find the comment #Example usage. # # Additional modules to be installed should be 'xmltodict', 'shutil', and 'gdown'. # Tested in P...
#!/usr/bin/env python import os,sys,pdb,scipy,glob from pylab import * import urllib, urllib2 import xml.dom.minidom import datetime def ADS(): thisMirror = 'http://adsabs.harvard.edu/' print 'Retrieving from ',thisMirror baseUrl = thisMirror + 'cgi-bin/nph-abs_connect?' return baseUrl def get_text(...
<filename>src/fftIfftTests.py import subprocess as sp import scikits.audiolab import numpy as np from scipy.fftpack import fft, ifft from scipy.io import wavfile #--CONVERT MP3 TO WAV------------------------------------------ song_path = '/home/gris/Music/vblandr/test_small/punk/07 Alkaline Trio - Only Love.mp3' comm...
<gh_stars>0 import numpy as np import h5py import keras import keras.backend as K from glob import glob import json import math, scipy from scipy.optimize import linear_sum_assignment import time from collections import OrderedDict import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import kera...
<reponame>ppik/loxodon<filename>prep_cars_data.py #!/usr/bin/env python import os from os.path import basename, dirname, exists from glob import glob from random import seed, sample from math import ceil import shutil from scipy.io import loadmat DATA_PATH = 'data/' VALID_RATIO = 0.2 seed(20171111) info = loadmat(...
<reponame>YuzhongHuangCS/journal-citation-cartels<filename>notebooks/construct-network/construct_network.py import numpy as np import pandas as pd import py2neo import pickle import os,sys from scipy import sparse def edges2adj(edges, raw_edges, year, pcount): # Uniqify edges def uniqify_edges(edges, pcount):...
<filename>chaospy/distributions/collection/gompertz.py """Gompertz distribution.""" import numpy from scipy import special from ..baseclass import SimpleDistribution, ShiftScaleDistribution class gompertz(SimpleDistribution): """Gompertz distribution.""" def __init__(self, c): super(gompertz, self)....
<filename>TFQ/barren_plateaus/bp_tfq.py import tensorflow as tf import tensorflow_quantum as tfq import cirq import sympy import numpy as np import matplotlib.pyplot as plt # https://www.tensorflow.org/quantum/tutorials/barren_plateaus#2_generating_random_circuits def generate_circuit(qubits, depth, param): circui...
<filename>IRIS_data_download/IRIS_download_support/obspy/signal/tests/test_filter.py #!/usr/bin/env python # -*- coding: utf-8 -*- """ The Filter test suite. """ from __future__ import (absolute_import, division, print_function, unicode_literals) from future.builtins import * # NOQA import gzi...
# -*- coding: utf-8 -*- """ price calculations ~~~~~~~~~ WARNING: This is specific to US income data. If this needs to be changed, you will need to update the BINS values and some of the regex expressions. :copyright: (c) 2015 by <NAME>, Santa Fe Institute. :license: MIT """ import numpy a...
<reponame>cyhsu/leaflet-velocity import os, sys, json import numpy as np import xarray as xr from glob import glob from datetime import datetime from netCDF4 import Dataset, num2date, date2num from scipy.interpolate import griddata #- HYCOM GLBv0.08/latest (daily-mean) present + forecast #- Detail info: https://www.h...
"""Compute rank correlations between word vector cosine similarities and human ratings of semantic similarity.""" import numpy as np import pandas as pd import argparse import os import scipy.spatial.distance import scipy.stats from .vecs import Vectors from .utensils import log_timer import logging logging.b...
""" Calculates distance of some (bpp, metric) point (for some metric) to some codec on some dataset. """ import os import numpy as np import scipy.interpolate from utils import other_codecs import constants from utils import logdir_helpers from collections import defaultdict from fjcommon import functools_ext as ft f...
<reponame>awwong1/topic-traceability #!/usr/bin/env python3 """Calculate distances using the topic models on the course material/discussion posts feature vectors. """ import os import numpy as np from datetime import datetime from numpy import ravel from pickle import load from json import dump from scipy.spatial.dista...
<filename>InjectionTools.py import numpy as np import urllib from lxml import etree import batman import ldtk from scipy.interpolate import interp1d # from joblib import Parallel, delayed import random import matplotlib.pyplot as plt from scipy.spatial.qhull import QhullError import multiprocessing import logging impor...
import numpy as np import scipy import scipy.io import pickle from scipy.special import lpmv, spherical_jn, spherical_yn class Directivity: def __init__(self, data_path, rho0, c0, freq_vec, simulated_ir_duration, measurement_radius, sh_order, type, sample_rate=44100, **kwargs): ''...
<gh_stars>100-1000 # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import os import sys import torch import numpy as np import scipy.misc as m import matplotlib.pyplot as plt import matplotlib.image as imgs from PIL import Image import random import scipy.io as io from tqdm import tqdm from s...
from scipy.integrate import solve_ivp import numpy as np import matplotlib.pyplot as plt from sklearn.metrics import mean_squared_error from hyperopt import hp, fmin, tpe from typing import Tuple def SIR(t, y, N, kappa, tau, nu): """ Expresses SIR model in initial value ODE format, including time, ...
<gh_stars>1-10 import numpy as np import collections try: from scipy.stats import scoreatpercentile except: # in case no scipy scoreatpercentile = False def _confidence_interval_1d(A, alpha=.05, metric=np.mean, numResamples=10000, interpolate=True): """Calculates bootstrap confidence interval along one...
# <NAME> # <EMAIL> import numpy as np from scipy.interpolate import interp2d import copy class GrismApCorr: """ GrismApCorr is a class containing tables for aperture correction (i.e., apcorr = f(wavelength, apsize)) in aXe reduction. These tables are from ISRs. Interpolaton model is also prepared. - Avail...
# -*- encoding: utf-8 -*- ''' @File : lr_1d.py.py @Modify Time @Author @Desciption ------------ ------- ----------- 2021/7/5 22:51 Jonas None ''' import numpy as np import math import matplotlib.pyplot as plt from scipy.stats import norm train_data = np.loadtxt("lin_reg_tr...
<reponame>Wisc-HCI/CoFrame<filename>evd_ros_backend/evd_ros_core/src/evd_sim/pose_interpolator.py from geometry_msgs.msg import Pose from scipy.interpolate import interp1d from pyquaternion import Quaternion class PoseInterpolator: def __init__(self, poseStart, poseEnd, velocity, minTime=1): ''' ...
<gh_stars>1-10 import pysam import pandas as pd import mappy as mp from itertools import chain from statistics import median from collections import Counter from scipy.stats import entropy MINLEN=50 MAXLEN=50000 def summary(splitter,caller): try: minsig = splitter.minSignal minfrac = splitter._...
<gh_stars>1-10 # LICENSE # Copyright (c) 2013-2016, <NAME> (<EMAIL>) # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice,...
#! -*- coding: utf-8 -*- # Keras implement of Glow # Glow模型的Keras版 # https://blog.openai.com/glow/ from keras.layers import * from keras.models import Model from keras.datasets import cifar10 from keras.callbacks import Callback from keras.optimizers import Adam from flow_layers import * import imageio import numpy as...
<reponame>tsmonteiro/fmri_proc #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jan 17 09:39:23 2020 @author: u0101486 """ #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Dec 5 12:26:49 2019 @author: u0101486 """ # Aggregate QC measures import os import sys import numpy as np im...
<gh_stars>0 import numpy as np import networkx as nx import sympy as sp import matplotlib.pyplot as plt import matplotlib as mpl from sys import exit from scipy.optimize import curve_fit from scipy.integrate import odeint class Model(nx.DiGraph): """ Base class for compartmental models. See also: -...
import pickle import numpy as np import matplotlib.pyplot as plt import scipy.stats as scp_stats import pandas as pd import f_rate_t_by_type_functions as frtbt N_trials = 15 # Decide which systems we are doing analysis for. sys_dict = {} sys_dict['all_mice'] = { 'cells_file': '../build/ll1.csv', 'f_1': '/data/mat...
<gh_stars>0 import logging from itertools import cycle from typing import Dict, List, Optional, Tuple, Union import matplotlib.cm as cm import matplotlib.pyplot as plt import numpy as np import pandas as pd from matplotlib.axes import Axes from matplotlib.figure import Figure from matplotlib.ticker import ScalarFormat...
""" Implementation of the hierarchical poisson glm model, with a precinct-specific term, an ethnicity specific term, and an offset term. The data are tuples of (ethnicity, precinct, num_stops, total_arrests), where the count variables num_stops and total_arrests refer to the number of stops and total arrests of an eth...
"""Contains the n dimensional inverted pendulum environment.""" import warnings from typing import Optional import matplotlib.pyplot as plt import numpy as np from numpy import ndarray from polytope import polytope from scipy.integrate import ode from scipy.spatial.qhull import ConvexHull from ..utils import assert_s...
import contextlib import unittest from test import support from itertools import permutations, product from random import randrange, sample, choice import warnings import sys, array, io from decimal import Decimal from fractions import Fraction try: from _testbuffer import * except ImportError: ndarray = None t...
<reponame>andsteing/being<filename>tests/test_serialization.py import unittest import enum from typing import NamedTuple import numpy as np from numpy.testing import assert_equal from scipy.interpolate import PPoly, CubicSpline, BPoly from being.serialization import ( ENUM_LOOKUP, EOT, NAMED_TUPLE_LOOKUP, FlyByDe...
"""/** * @author [<NAME>] * @email [<EMAIL>] * @create date 2020-05-21 11:55:58 * @modify date 2020-06-16 23:33:58 * @desc [ SC_Difficulty class with methods to set speed challenge difficulty: - Ask for difficulties - Acknowledge difficulty message. ] */ """ ########## # Imports ########## from sta...
<filename>Python_Projects/Global_Model/Working/calculation.py #!/usr/bin/env python # coding: utf-8 import xs import numpy as np from scipy.integrate import odeint from math import isclose from constants import * class Global_model: def __init__(self, p, input_power, duty, period, time_resolution=1e-8): ...
<reponame>knuu/competitive-programming from heapq import heapify, heappush, heappop from collections import Counter, defaultdict, deque, OrderedDict from sys import setrecursionlimit, maxsize from bisect import bisect_left, bisect, insort_left, insort from math import ceil, log, factorial, hypot, pi from fractions impo...
<gh_stars>1-10 #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Aug 20 21:29:32 2021 @author: qcao Analysis code for example_topop_tb_v3.py Parses and cleans load-driven phantoms. Computes Radiomic signatures. Compares with BvTv. Compare with ROIs """ # FEA and BoneBox Imports import os import sy...
""" PURPOSE: Run feature selection mettestd available from sci-kit learn on a given dataframe Must set path to Miniconda in HPC: export PATH=/mnt/testme/azodichr/miniconda3/bin:$PATH INPUT: -df Feature file for ML. If class/Y values are in a separate file use -df for features and -df2 for class/Y -alg ...
<gh_stars>1-10 import numpy as np from scipy.fft import ifft def generate_waveforms(data: np.ndarray) -> np.ndarray: """ Generate waveforms from frequency domains :param data: frequency domains (where first n/2 examples consist of real values and the rest consists of imaginary values) :return: nu...
#!/usr/bin/env python # # NSC_INSTCAL_SEXDAOPHOT.PY -- Run SExtractor and DAOPHOT on an exposure # from __future__ import print_function __authors__ = '<NAME> <<EMAIL>>' __version__ = '20180819' # yyyymmdd import os import sys import numpy as np import warnings from astropy.io import fits from astropy.wcs import WC...
from datetime import datetime, timedelta import matplotlib.dates as mdates import matplotlib.pyplot as plt import numpy as np import pandas as pd import scipy.optimize as opt def area_chart(ds, dateFmt): # create a subplot fig, ax = plt.subplots() # set figure size and dpi fig.set_size_inches(10, 5) ...
<filename>bin/NormalizeReadCounts.py #!/usr/bin/env python # -*- coding: utf-8 -*- """ Created on Mon Feb 13 09:23:51 2017 @author: philipp """ # Analyze count distribution # ======================================================================= # Imports from __future__ import division # floating point division by d...
<reponame>twiecki/edward<filename>examples/convolutional_vae.py #!/usr/bin/env python """ Convolutional variational auto-encoder for MNIST data. The model is written in TensorFlow, with neural networks using Pretty Tensor. Probability model Prior: Normal Likelihood: Bernoulli parameterized by convolutional NN ...
<filename>sparkdq/models/dbscan/DBSCAN.py from operator import add import numpy as np from pyspark.sql.types import StructField, StructType, IntegerType from scipy.spatial.distance import euclidean import sklearn.cluster as skc from sparkdq.conf.Context import Context from sparkdq.models.CommonUtils import DEFAULT_CL...
<gh_stars>0 # Licensed under a 3-clause BSD style license - see LICENSE.rst """Functions to compute TS images.""" import functools import logging import warnings import numpy as np import scipy.optimize from astropy.coordinates import Angle from gammapy.datasets.map import MapEvaluator from gammapy.maps import Map, Wcs...
<reponame>eugeniu1994/Stereo-Camera-LiDAR-calibration<gh_stars>1-10 ''' CONFIDENTIAL Copyright (c) 2021 <NAME>, Department of Remote Sensing and Photogrammetry, Finnish Geospatial Research Institute (FGI), National Land Survey of Finland (NLS) PERMISSION IS HEREBY LIMITED TO FGI'S INTERNAL USE ON...
from deduplication import simhash, lsimhash from pathlib import Path from scipy.spatial.distance import hamming import numpy as np import textwrap def test_main(): with open(Path(__file__).resolve().parent / 'data' / 'wiki_nlp.txt', 'r') as f: content = f.read() hval = lsimhash.lsimhash(content) ...
<filename>ocr-server/ocr_server/lines.py from typing import List import numpy as np import cv2 import scipy.signal def find_line(image: np.ndarray, window_size: int = 30) -> np.ndarray: """Extracts a single line from the image""" image_inverted = cv2.bitwise_not(image) image_as_column = np.sum(image_inve...
<filename>utils.py # Description: A library of common utilities # Author: <NAME> import numpy as np import cv2 from scipy.signal import convolve2d import matplotlib.pyplot as plt def imagify(fft): ''' 2D ffts usually have real and imaginary components, and they also usually have way too much dynamic range...
import numpy as np from scipy.optimize import line_search import locale locale.setlocale(locale.LC_ALL, '') class cd_res(object): def __init__(self, x, fun): self.x = x self.fun = fun print_stop_iteration = 1 def cdl_step(score, guess, jac, val = Non...
import numpy as np from numpy import * import pandas as pd from pandas import DataFrame, Series from numpy.random import randn import tensorflow as tf import matplotlib.pyplot as plt from PIL import Image import re from skimage.io import imread, imshow from termcolor import colored import keras import h5py ...
import functools import itertools import operator import re import numpy as np import pandas as pd from pandas.api.types import is_numeric_dtype import toolz from genopandas import plotting as gplot from genopandas.util.pandas_ import DfWrapper from .frame import GenomicDataFrame, GenomicSlice RANGED_REGEX = r'(?P<...
<reponame>CarlGriffinsteed/UVM-ME144-Heat-Transfer<gh_stars>1-10 """ Object name: HorizontalCylinder Functions: Gr(g,beta,DT,D,nu) gives the Grashoff number based on: gravity g, thermal expansion coefficient beta, Temperature difference DT, length scale D, viscosity nu Ra(g,beta,DT,...
"""Modules for graph embedding methods.""" import logging import gensim import networkx as nx import numpy as np import pandas as pd # For GCN import stellargraph as sg import tensorflow as tf from graph_embeddings import samplers, utils from scipy import sparse from sklearn import model_selection from stellargraph....
import numpy as np import matplotlib.pyplot as plt import math from scipy.io.wavfile import read as read_wav from scipy.io.wavfile import write as write_wav from scipy.fftpack import fft, fftshift from scipy.signal import lfilter, firwin def filt(sig, Fc=0.5, NFIR=101): fir_taps = firwin(NFIR, Fc, window=('blackma...
""" Core module. Normally, do not add new construction methods here, do this in scene.py instead. """ from enum import Enum, auto, unique import itertools import re import sympy as sp from typing import List from .figure import Figure from .reason import Reason from .util import LazyComment, Comment, divide class Co...
<reponame>arminnh/ma2-computer-vision import numpy as np import scipy.spatial.distance from scipy import linalg import procrustes_analysis import util from Landmark import Landmark from models.CenterInitializationModel import CenterInitializationModel class ToothModel: def __init__(self, name, landmarks, pcaComp...
from simba import transfer_function_to_graph, tf2rss from sympy import symbols # passive realisation (g = 0) s = symbols('s') gamma_f, omega_s = symbols('gamma_f omega_s', real=True, positive=True) tf = (s**2 + s * gamma_f + omega_s**2) / (s**2 - s * gamma_f + omega_s**2) h_int = tf2rss(tf).to_slh().split().interac...
# Erstelle aus gegebnen Daten eine Ausgleichskurve # Und Plotte diese Kurve + die Daten # wechsle die Working Directory zum Versuchsordner, damit das Python-Script von überall ausgeführt werden kann import os,pathlib project_path = pathlib.Path(__file__).absolute().parent.parent os.chdir(project_path) # benutze die ma...
<filename>waveform_analysis/tests/test_ITU_R_468_weighting.py import pytest from scipy import signal from scipy.interpolate import interp1d import numpy as np from numpy import pi # This package must first be installed with `pip install -e .` or similar from waveform_analysis import (ITU_R_468_weighting_analog, ...
<gh_stars>10-100 import scipy.interpolate import scipy.signal from builtins import staticmethod import numpy as np from scripts.utils.ArrayUtils import ArrayUtils class MatlabUtils: @staticmethod def max(array: np.ndarray): if len(array) > 1: return np.amax(array, axis=0) else: ...
import h5py import pandas as pd import numpy as np import json import scipy as sp import nibabel as nib from glob import glob import fnmatch import os run_name_dict = { "REST1": "REST1_7T_PA", "REST2": "REST2_7T_AP", "REST3": "REST3_7T_PA", "REST4": "REST4_7T_AP", "MOVIE1": 'MOVIE1_CC1', "MOV...
<filename>jabble/dataset.py import numpy as np # import matplotlib.pyplot as plt import astropy.table as at import astropy.units as u import astropy.coordinates as coord import astropy.constants as const import astropy.time as atime import scipy.ndimage as ndimage import numpy.polynomial as polynomial # import jabble...
<reponame>McCoyGroup/Coordinerds """ Redoes what was originally PyDVR but in the _right_ way using proper subclassing and abstract properties """ import abc, numpy as np, scipy.sparse as sp, scipy.interpolate as interp from McUtils.Data import UnitsData __all__ = ["BaseDVR", "DVRResults", "DVRException"] class Base...
# Code from Chapter 18 of Machine Learning: An Algorithmic Perspective (2nd Edition) # by <NAME> (http://stephenmonika.net) # You are free to use, change, or redistribute the code in any way you wish for # non-commercial purposes, but please maintain the name of the original author. # This code comes with no warranty ...
import pandas as pd import numpy as np import matplotlib.pyplot as plt import xarray as xr from scipy import signal import timeit from numba import jit import datashader as ds import xarray as xr from datashader import transfer_functions as tf #1. Define the boundary conditions # Needed: surface temperature forcing (s...
<reponame>parkerwray/tmm """ Import relevant modules """ from __future__ import division, print_function, absolute_import #from tmm.tmm_core import (coh_tmm, unpolarized_RT, ellips, # position_resolved, find_in_structure_with_inf) from wptherml.wptherml.datalib import datalib import tmm.tmm_cor...
<reponame>AleFeli/momepy #!/usr/bin/env python # -*- coding: utf-8 -*- # dimension.py # definitions of dimension characters import math import numpy as np import pandas as pd import scipy as sp from shapely.geometry import LineString, Point, Polygon from tqdm import tqdm from .shape import _make_circle __all__ = [...
<reponame>saberzuko/MachineLearningAlgorithms<filename>KMeansClustering/clustering.py<gh_stars>0 import numpy as np from scipy.spatial import distance import random def mu_generator(X, K): # Function to initialize the cluster centers # The input is the training data X and the number of cluster centers mu =...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Apr 18 09:08:20 2022 A script to plot mean daily cores for intercomparison of features as a function of time through a season. @author: michaeltown """ #libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt import os import...
# imports from .ball import Pallino from .throw import Throw from .cv.ballfinder import BallFinder from scipy.spatial import distance as dist # for now, these are "pixels" (not "inches" or "cm") TOO_CLOSE_MARGIN = 5 class Frame: def __init__(self, frameNumber, throwingEnd, pallinoThrowingTeam, teamHome, ...
"""I3D feature extration using a tensorflow model. Copyright 2018 Mitsubishi Electric Research Labs """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import h5py import numpy as np import tensorflow as tf import time import os import scipy.io as sio im...
# -*- coding: utf-8 -*- from __future__ import division, print_function __all__ = ["prepare_characterization"] import kplr import transit import numpy as np from scipy.stats import beta import matplotlib.pyplot as pl import george from george import kernels from ..prepare import Prepare from ..download import Down...
#!/bin/python from deap import tools from copy import deepcopy import random from deap import algorithms import promoterz import statistics from .. import evolutionHooks def checkPopulation(population, message): if not (len(population)): print(message) def standard_loop(World, locale): # --assertion...
<gh_stars>0 import numpy as np import scipy.sparse as ss import logging import time import warnings from .feature_selection import get_significant_genes from .feature_selection import calculate_minmax warnings.simplefilter("ignore") logging.basicConfig(format='%(process)d - %(levelname)s : %(asctime)s - %(message)s'...
#!/usr/bin/env python2 import numpy as np import os import scipy VIS_DIR = "vis" class Visualizer: def __init__(self): self.active = False def begin(self, dest, max_entries): self.lines = [] self.active = True self.max_entries = max_entries self.next_entry = 0 ...
<reponame>mattpitkin/GraWIToNStatisticsLectures #!/usr/bin/env python """ Make plots of the Student's t-distribution for different degrees of freedom """ import matplotlib.pyplot as pl from scipy.stats import norm from scipy.stats import t import numpy as np mu = 0. # the mean, mu nus = [1., 2., 5, 10, 100] # standa...
import logging import time from contextlib import contextmanager import numpy as np import pandas as pd import scipy.stats from openml import datasets, runs from sklearn.model_selection import train_test_split logger = logging.getLogger("dashboard") logger.setLevel(logging.DEBUG) def get_run_df(run_id: int): ru...
#%% import numpy as np from itertools import repeat from itertools import starmap from scipy.stats import norm class ABCer: def __init__(self, iterations, particles, observations): self.iterations = iterations self.particles = particles self.observations = observations def initialize_...
<gh_stars>10-100 #from scikits.talkbox.features import mfcc import scipy.io.wavfile import numpy as np import sys import os import glob from utils1 import GENRE_DIR, GENRE_LIST from python_speech_features import mfcc #from librosa.feature import mfcc # Given a wavfile, computes mfcc and saves mfcc data def create_ce...
from typing import ( Any, Callable, List, NamedTuple, Optional, Tuple, Type, Union, overload, ) import numpy as np from scipy import special Array = Union[np.ndarray] Numeric = Union[int, float] # Lists = Union[Numeric, List['Lists']] Tuplist = Union[Tuple[int, ...], List[int]] Dim...
<filename>FigureGeneration/makeFigure1.py import matplotlib.pyplot as plt from scipy.optimize import root import matplotlib import numpy as np def makeFigure1(): def fun(x): return [(x[0]**qq)/(1+x[0]**qq) - bb*x[0]] b = [0.4,0.3,0.2,0.1] q = [2.5,3,3.5,4] x = np.arang...
import torch import torch.nn as nn import torch.nn.functional as F from config import _C as C from models.layers.GNN_dmwater import GraphNet from scipy import spatial import numpy as np import utils class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.node_dim_in = C.NET.NODE...
"""Export data""" from scipy.io import savemat def mat(filename, mdict): """Export dictionary to .mat file for MATLAB""" savemat(filename, mdict)
<filename>wouldyouci_database/recommendation/contents_based_filtering.py<gh_stars>1-10 import os import time import pymysql import pandas as pd from decouple import config from datetime import datetime from sklearn.linear_model import Lasso from sklearn.linear_model import LinearRegression from sklearn.model_selection ...
#a2.t4 #This program is to create a function to check carbondioxide content in air #taking advantage of python statistics library import statistics def check_air_quality(carbondioxide_data): if statistics.median(carbondioxide_data) >= 400 and statistics.median(carbondioxide_data) < 700: return "EXCELLENT" ...
# speaker_2_sound.py # 한 스피커로 녹음해서 정위상, 역위상 wav를 생성한 다음 정위상은 왼쪽, 역위상은 오른쪽 스피커에서 재생시키는 소스코드 # (정위상, 역위상 파일을 하나의 스테레오 wav로 만듦) # 음성(소음) 녹음, 재생 하는 패키지(wav파일) import pyaudio import wave # 위상 반전, 파장 결합(Merge), 소리 재생 하는 패키지 from pydub import AudioSegment from pydub.playback import play from scipy.io import wavfile import...
<reponame>isabellewei/deephealth<gh_stars>0 from time import time from sklearn.preprocessing import StandardScaler from sklearn import model_selection from sklearn.model_selection import train_test_split, KFold, cross_val_score from sklearn.metrics import classification_report,confusion_matrix,accuracy_score from ...
from dolfyn.tests import test_read_adp as tr from dolfyn.tests import base from dolfyn.rotate.api import rotate2 from numpy.testing import assert_allclose import numpy as np import scipy.io as sio """ Testing against velocity and bottom-track velocity data in Nortek mat files exported from SignatureDeployment. inst2...
<reponame>morales-gregorio/NetworkUnit import numpy as np from scipy.stats import entropy import matplotlib.pyplot as plt import matplotlib.colors as colors import seaborn as sns import sciunit class kl_divergence(sciunit.Score): """ Kullback-Leibner Divergence D_KL(P||Q) Calculates the difference of two...
# Cálculo da razão áurea (phi) import sympy d = 20 phi = sympy.symbols('phi', nonnegative=True) eqn = sympy.Eq(1/phi, phi - 1) sol = sympy.solve(eqn) sympy.pprint(sol) phiAprox = sympy.N(sol[0], d) print('Para ', d, ' dígitos significativos, ϕ = ', phiAprox)
<gh_stars>0 """multipy: Python library for multicomponent mass transfer""" __author__ = "<NAME>, <NAME>" __copyright__ = "Copyright (c) 2022, <NAME>, <NAME>" __license__ = "MIT" __version__ = "1.0.0" __maintainer__ = ["<NAME>"] __email__ = ["<EMAIL>"] __status__ = "Production" import numpy as np import pandas as pd i...
<filename>create_dataset.py import os import lmdb # install lmdb by "pip install lmdb" import cv2 import numpy as np from tool.xml_parser import page_images from glob import glob import re import sys import io import argparse from scipy.spatial import distance encoding = 'utf-8' stdout = sys.stdout reload(sys) sys.s...
<filename>dl/cifar_python_data_layer.py # imports import caffe import numpy as np from random import shuffle import cPickle as cp import scipy.io as sio class PythonDataLayer(caffe.Layer): """ This is a simple syncronous datalayer for training a multilabel model on CIFAR. """ def setup(self, b...
# Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import absolute_import, division, print_function, unicode_literals import numpy as np from numpy.testing import assert_allclose from astropy.io import fits from astropy.units import Quantity from astropy.coordinates.angles import Angle from...
import networkx as nx import numpy as np import scipy import graph import itertools from collections import defaultdict def calculate_persistence(crystal, other, minimum_value, G, function_vals): minimums = [] min_vertices = [] other = set(other) for vertex in crystal: neighbors = set(G.neighbo...
<gh_stars>0 # Example illustrating the application of MBAR to compute a 1D PMF from an umbrella sampling simulation. # # The data represents an umbrella sampling simulation for the magnetization of the Ising model # Adapted from one of the pymbar example scripts for 1D PMFs import numpy as np # numerical array library...
<gh_stars>1-10 # encoding=utf-8 import os import fire import numpy as np from scipy.sparse.csr import csr_matrix from sklearn.base import BaseEstimator from sklearn.model_selection import cross_validate from sklearn.preprocessing import normalize from sklearn.feature_extraction.text import CountVectorizer, TfidfTrans...
<gh_stars>1-10 import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from collections import OrderedDict from collections import deque from sklearn.neighbors import KernelDensity from scipy.stats import entropy as scientropy import random class NoveltyMemory: def __init__(self,...
from .prepare import make_train_test import os import tempfile import scipy.io as sio from hashlib import sha256 try: import urllib.request as urllib_request # for Python 3 except ImportError: import urllib2 as urllib_request # for Python 2 urls = { "chembl-IC50-346targets.mm" : ( ...