text
string
<filename>sysopt/symbolic/symbols.py """Functions and factories to create symbolic variables.""" import weakref from abc import ABCMeta, abstractmethod from collections import defaultdict from inspect import signature import numpy as np from scipy.sparse import dok_matrix, spmatrix from typing import Union, List, Call...
# -*- coding: utf-8 -*- """ Created on Tue Dec 10 14:26:54 2019 @author: Mnemosyne Functions to compute the features of the song """ import os import shutil import glob import sys import random import re import numpy as np import scipy as sp import scipy.io.wavfile as wav from scipy.fftpack import fft, rfft from sci...
<filename>lesson5_lin_regression.py import numpy as np import scipy.optimize def gradient_model(x, I_0, a, lam): if np.any(np.array(x) < 0): raise RuntimeError('x must be positive') if np.any(np.array([I_0, a, lam] < 0)): raise RuntimeError('all params must be positive') return a + I_0 * np...
<reponame>takaaki82/Java-Lessons<filename>AtCoder/CPSCO2019Session1/C.py import bisect import collections import copy import fractions import heapq import itertools import math import string import sys inf = float("inf") mod = 10 ** 9 + 7 d4 = [(1, 0), (0, -1), (-1, 0), (0, 1)] d8 = [(1, 0), (1, -1), (0, -1), (-1, -1)...
import numpy as np import pandas as pd from scipy.signal import butter, filtfilt, find_peaks def _butter_highpass(cutoff, fs, order=5): nyq = 0.5 * fs normal_cutoff = cutoff / nyq b, a = butter(order, normal_cutoff, btype='high', analog=False) return b, a def highpass_filter(data, cutoff, fs, order=5)...
<reponame>RINKESH0806/ga-learner-dsmp-repo<filename>ga-learner-dsmp-repo/code.py # -------------- # Import packages import numpy as np import pandas as pd from scipy.stats import mode bank=pd.read_csv(path) #print(bank) categorical_var=bank.select_dtypes(include='object') print(categorical_var) numerical_var=bank.sele...
import json import traceback from datetime import timedelta from urllib.parse import quote import numpy as np import pandas as pd import requests from django.core.cache import cache from django.utils import timezone from loguru import logger from pals.PLAGE import PLAGE from pals.common import DATABASE_REACTOME_CHEBI,...
import logging import numpy as np import scipy import numba import opt_einsum import pyfftw import mathx from .. import bvar from . import sa logger = logging.getLogger(__name__) fft = lambda Ar, axis=-1:pyfftw.interfaces.numpy_fft.fft(Ar, norm='ortho', axis=axis) ifft = lambda Ak, axis=-1:pyfftw.interfaces.numpy_fft...
############################################################################### # # PhenoPy is a Python 3.X library to process phenology indices derived from # EarthObservation data. # ############################################################################### # libraries included in Python 3.X from __future__ imp...
#!/usr/bin/env python """ This module is a Keras/Tensorflow based implementation of Pyramid Scene Parsing Networks. Original paper & code published by <NAME> et al. (2017) """ from __future__ import print_function from __future__ import division from os.path import splitext, join, isfile from os import environ from ma...
import json import random import os import time import cv2 import numpy as np from torch.utils.data import Dataset, DataLoader import torch from scipy import ndimage from Configs import Config, features_clustering from sklearn.metrics.cluster import normalized_mutual_info_score import glob from tqdm import tqdm # Tra...
<gh_stars>0 #Schrodinger 1D equation solved by finding eigenvectors of the hamiltonian import numpy as np import scipy import scipy.integrate import scipy.linalg import scipy.misc import scipy.special import pylab as plt l=10 N=1024 def v(x): return m*w*x*x/2 m=1 w=1 hbar=1 X, dx=np.linspace(-l, l, N, retstep=True) ...
<reponame>zhao-david/CDE-conformal import numpy as np import pandas as pd import scipy.stats import local_conformal as lc def test_difference_validity_and_efficiency_basic(): """ basic test for difference_validity_and_efficiency """ true_cde = np.ones((5,4)) predict_grid = np.arange(20).reshape(5,...
from IPython.display import display import numpy from scipy.optimize import linprog C=12 #numbers of RSUs S=100 '''%Utility computing''' '''W=randi([10 20],C);%average trip delay at intersection i after attack''' W_B = numpy.random.random((1, C)) #its ndArray #W = numpy.matrix(W_B)# it is matrix W=...
## Generates Figs 5, 6 & 7 of SEG 2016 ## ============================================================================ import matplotlib.pyplot as plt import numpy as np from scipy.integrate import quad from matplotlib.patches import Ellipse import flattened as fJ from scipy.optimize import curve_fit import seaborn as ...
#!/usr/bin/env python # -*- coding: UTF-8 -*- from six import string_types from scipy.spatial import distance from Bio.PDB import PDBParser from Bio.PDB import NeighborSearch RESIDUELIST = ['ALA', 'ARG', 'ASP', 'ASN', 'CYS', 'GLU', 'GLN', 'GLY', 'HIS', 'ILE', 'LEU', 'LYS', 'MET', 'PHE', 'PRO', 'SER', ...
<gh_stars>0 """ Run this after run_analysis.py """ import logging import numpy as np import sys import pickle import tqdm from collections import OrderedDict from astropy.io import fits from astropy.table import Table from scipy.special import logsumexp from scipy import stats import npm_utils as npm def lnprob(y...
<reponame>charliewen95/flowNetwork<filename>current_flow_allostery/betweenness.py """ This is the function that does the betweenness calculation """ try: import argparse except ImportError: raise ImportError("require argparse") #numerical / data packages try: import numpy as np np.set_printoptions(thre...
<filename>data/Imageset/image_split.py # -*- coding: utf-8 -*- """ Created on Wed Mar 15 19:31:34 2017 @author: justjay """ #LIVE2 split images randomly #Train: 17, Validation: 6, Test: 6 #Train: 23, Test: 6; train:test ~= 8:2 import numpy as np import scipy.io as sio names_mat = sio.loadmat('./refnames_all.mat')...
import argparse import functools import json import os import numpy as np import sys from collections import Counter, defaultdict from joblib import Parallel, delayed from scipy.stats import pearsonr, spearmanr, kendalltau sys.path.append('.') from sacrerouge.commands.correlate import load_metrics, filter_metrics, me...
<reponame>xa4a/unshred<filename>unshred/features/lines.py import math import cmath import cv2 import numpy from unshred import threshold from unshred.features import AbstractShredFeature DEBUG = False MEAN, MEDIAN = range(2) def _get_dominant_angle(lines, domination_type=MEDIAN): """Picks dominant angle of a...
"""A few utility function for the pruner.""" import copy import math import numpy as np import torch from scipy import optimize def _adapt_uniform_sample_size(probabilities, sample_size_target): """Do _adapt_sample_size for a uniform distribution (faster).""" idx = probabilities.nonzero() sample_size_tar...
<gh_stars>0 import pandas as pd from scipy.spatial.kdtree import KDTree class NeighborsFinder: def __init__(self,data): """Find neigbors Args: data (pd.DataFrame or dict): data with at columns id,pos,and eventually range """ if data is not None: sel...
<gh_stars>0 '''Main code with the analysis for the Methane project Check the performance of EC vs SR vs WAVELET vs Flux-Variance Also check flux variance relations for all runs ''' # load dataframes with results # and all stations import os import time import numpy as np import pandas as pd import matplotlib.pyplot as...
import random import numpy as np import scipy.optimize import scipy.special import math import yaml from enum import IntEnum #import UWBsim from UWBsim.utils import dataTypes class RangingType(IntEnum): NONE = 0 TWR = 1 TDOA = 2 class RangingSource(IntEnum): NONE = 0 LOG = 1 GENERATE_GAU...
<filename>spekpy/SpekPy.py # For compatibility with Python2 # from __future__ import print_function, division, absolute_import ################################## from . import __version__ import spekpy.SpekConstants as Const from spekpy.IO import find_file, path_file, read_spectrum_from_disk, \ get_script_path, is_...
#encoding: utf-8 """ grid.analysis.map_funcs -- A repository for standalone functions useful for performing various computations on spatial map arrays. Exported namespace: remap_quiver_plot, spatial_corr, linearize_spatial_corr, peak_vs_neighbors, input_vs_output_norms, haff_vs_r_peaks, field_comparison_...
# import numpy as np # import cv2 # from sympy import * # import matplotlib.pyplot as plt # image=plt.imread('1.jpeg') # def normalize(data): # _range = np.max(data) - np.min(data) # return (data - np.min(data)) / _range # # def GaussKernel(sig=5,m=0): # # if m == 0: # # m = int(sig * 2 * 3 + 1...
import os, time, random import numpy as np import scipy import tensorflow as tf import tensorlayer as tl from model import * from utils import * from config import * import cv2 import math import pdb #用于debug跟踪调试 oriImageName = "samples/test/test_origin.bmp" resImageName = "samples/test/test_out.bmp" if __name__ == ...
<filename>autumn/economics.py # external imports import scipy import numpy def get_cost_from_coverage(coverage, inflection_cost, saturation, unit_cost, popsize, alpha=1.): """ Estimate the raw cost associated with a given coverage for a specific intervention. Args: coverage: The intervention's c...
<gh_stars>0 import load_data import os import numpy as np import scipy.ndimage from sklearn import svm, preprocessing from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score from sklearn.model_selection import GridSearchCV from sklearn.metrics import classification_report def l...
<filename>trainer.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- # #【trainer】 # # 概要: IMDB 推論 学習用クラス # # 更新履歴: # 2019.03.31 新規作成 # import pathlib import tqdm import logging from statistics import mean import torch from torch import nn, optim from torch.utils.data import Dataset, DataLoader, TensorDataset fr...
<filename>external/AR/ltr/dataset/sbd.py from .base_image_dataset import BaseImageDataset from ltr.data.image_loader import jpeg4py_loader_w_failsafe import torch from collections import OrderedDict import os from scipy.io import loadmat from ltr.data.bounding_box_utils import masks_to_bboxes from ltr.admin.environmen...
<gh_stars>0 #!/usr/bin/env python3 import time import statistics import sys import gzip import string import argparse import re import itertools import yaml import regex from Bio import SeqIO from Bio import Seq, SeqRecord # TODO pass description to flags field, but this requires lots of warnings # and caveats to th...
<reponame>jasminwash/hostgal<filename>mask_objects.py #!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sat Sep 29 15:01:17 2018 @author: Dartoon """ import numpy as np import astropy.io.fits as pyfits import matplotlib.pyplot as plt from photutils import detect_threshold from astropy.convolution import Ga...
import os import warnings import matplotlib as mpl import seaborn as sb import numpy as np import matplotlib.pyplot as plt import statistics import pandas as pd import logging from df_creation import postprocess_vertex_df, get_users_map, get_file_tag from dataset_paths import get_postprocess_folder_general, get_common...
<filename>src/S1B_cc_pair_MPI.py import gc import sys import time import scipy import obspy import pyasdf import datetime import os, glob import numpy as np import pandas as pd import noise_module from mpi4py import MPI from scipy.fftpack.helper import next_fast_len import matplotlib.pyplot as plt
<filename>tests/test_transforms.py """ This module provides some tests of the transform, based on analytic transforms provided by Wikipedia. Note that most of the tests in here are mirrored in test_known_integrals, in which k is set to 1. There is a corresponding notebook in devel/ that runs each of these functions t...
<reponame>sweigart/pygama<filename>experiments/mj60/calibration.py #!/usr/bin/env python3 import argparse import numpy as np import pandas as pd import tinydb as db import matplotlib.pyplot as plt import itertools as it from scipy.stats import mode from pprint import pprint from pygama import DataSet from pygama.utils ...
# Copyright 2019 1QBit # # 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 ...
import argparse import collections import gzip import json import logging import math import os import statistics import time from typing import Dict, List, TypedDict from roaringbitmap import RoaringBitmap from sparklines import sparklines from tdigest import RawTDigest from engineering_notation import EngNumber log...
<reponame>atisor73/caulobacterpkg import numpy as np import pandas as pd import random import scipy.stats import bokeh import bokeh.palettes from bokeh.transform import linear_cmap import bokeh_catplot import bokeh.models import bebi103 import holoviews as hv hv.extension('bokeh') import bokeh.io bebi103.hv.set_defau...
""" Not using Download from https://raw.githubusercontent.com/EricYizhenWang/robust_nn_icml/master/robust_1nn.py """ from __future__ import division import numpy as np from sklearn.neighbors import NearestNeighbors, KNeighborsClassifier from scipy.spatial.distance import cdist from .eps_separation import find_eps_sep...
# -*- coding: utf-8 -*- """ other_algorithms.py: Baseline algorithms to compare against. """ import pdb import numpy as np from scipy.optimize import least_squares from pylocus.lateration import SRLS from coordinate_fitting import fit_trajectory from solvers import trajectory_recovery EPS = 1e-10 def error_meas...
# -*- coding: utf-8 -*- import ETCetera.data.nonlinear_systems_datastructure as data import sympy as sp def create_template(): template_data = data.InputDataStructureNonLinear() [template_data.hyperbox_states.append(list([i+0.2,i+3.4])) for i in range(1,4)] [template_data.hyperbox_disturbances.append(list...
from inspect import Traceback from pickle import NONE import pickle from random import random, shuffle from altair.vegalite.v4.api import value from altair.vegalite.v4.schema.channels import Column from numpy.core.fromnumeric import choose from numpy.lib.npyio import save import pandas,sys from scipy.sparse import data...
from scipy import stats from matplotlib import pyplot as plt from matplotlib.pyplot import figure import numpy as np import pandas as pd import os # Tries to load excel file from input folder def loadfile(): try: path = 'input/' + os.listdir('input')[0] data = pd.read_excel(path) except IndexEr...
<filename>python/lm_layers.py import sys sys.path.insert(0, '/home/chenweiliang/caffe-windows-ms/python') import caffe import numpy as np from PIL import Image import scipy.io as sio import os import random class LandmarkVisualLayer(caffe.Layer): """ Save images to file """ def setup(self, bottom, to...
<filename>dpm_sheet.py<gh_stars>1-10 import argparse from concurrent.futures import ProcessPoolExecutor from itertools import product from statistics.preset import get_preset_list from dpmModule.character.characterTemplate import get_template_generator from dpmModule.util.dpmgenerator import IndividualDPMGenerator tr...
<gh_stars>0 # Copyright (c) 2012, GPy authors (see AUTHORS.txt). # Licensed under the BSD 3-clause license (see LICENSE.txt) import numpy as np from scipy.special import cbrt from .config import * _lim_val = np.finfo(np.float64).max _lim_val_min = np.finfo(np.float64).min _lim_val_exp = np.log(_lim_val) _lim_val_squa...
""" Erase texture seams to prevent visible seams or tearing in various texture maps (color, normal, displacement, ambient occlusion, etc.) Written by <NAME> """ from __future__ import print_function import sys from multiprocessing import Process from recordclass import recordclass import scipy import numpy import...
from typing import List, Optional from dataclasses import dataclass from scipy.stats import median_abs_deviation, mode import numpy as np import seaborn as sb import matplotlib.pyplot as plt import matplotlib.ticker as ticker import tikzplotlib import pandas as pd @dataclass class TimeDelta: d: float h: float...
<filename>12.1.py import matplotlib.pyplot as plt import numpy as np from scipy.optimize import minimize_scalar def f(p): def ff(p): return 8 * np.exp(-(p/4.0)) + 6 * np.exp(-(p/2.0)) if (p < 0.96): return (ff(p)-10) + p*(14 - ff(p)) elif (p>=0.96 and p<1.27): return...
""" Utilities for sympy. *** SUffix conventions *Arr - numpy array *Mat - sympy.Matrix N X N *Vec - sympy.Matrix N X 1 *s - list Notes 1. By default, symbols are added to locals() of the caller. This can be changed by using the dct optional keyword. This means that all user callable functions must captu...
import numpy as np from scanorama import plt from scipy.sparse import csr_matrix from time import time from geosketch import * from utils import log if __name__ == '__main__': X_dimred = np.loadtxt('data/dimred/svd_zeisel.txt') X_dimred = X_dimred[:500000] sizes = [ 1000000, 2500000, 5000000, 100000...
# coding: utf-8 # # 2-Variables and Basic Types # # # Always run this statement first, when working with this book: # In[1]: from scipy import * from matplotlib.pyplot import * get_ipython().magic('matplotlib inline') from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivi...
<filename>passiveRadar/signal_utils.py import numpy as np import scipy.signal as signal def normalize(x): '''normalize ndarray to unit mean''' return x/np.mean(np.abs(x).flatten()) def decimate(x, q): '''decimate x by a factor of q''' return signal.decimate(x, q, n=255, ftype='fir', axis=0, zero_phase...
#!/usr/bin/env python # coding: utf-8 # # Scenario # # As an analyst for OilyGiant mining company our task is to find the best place for a new well. # # We will use several techniques, including machine learning and bootstrapping, to select the region with the highest profit margin. # # Machine learning prediction...
""" copyright (c) 2017 <NAME> this program is free software: you can redistribute it and/or modify it under the terms of the gnu general public license as published by the free software foundation, either version 3 of the license, or (at your option) any later version. you should have received a copy of the gnu genera...
import numpy as np from bananas.pipelines import mean_warszycki_logki from bananas.worlds import ( MolPrint2D, TanimotoMinMaxKernel, TanimotoMinMaxSimilarity, BalancedAgglomerativeClustering, CrossValidation, SubsetData, StorageWorld, Variable, DataDict, ) import crisper from herbiv...
<gh_stars>0 import numpy as np from scipy import stats from matplotlib import pyplot as plt import time import matplotlib.animation as animation from astropy import convolution as conv TIMESTEP = 0.1 def Gen_Static_Model(nmax=None): count = 0 X, Y = np.meshgrid(np.linspace(-5, 5, 100), np.linspace(-5, 5, 10...
# computes and graphs a PCA of a sample of light curves # for the purposes of dimensionality reduction import numpy as np import pyfits as pf import itertools from scipy.io.idl import readsav from scipy.spatial import distance import pylab as pl from sklearn import metrics from sklearn.ensemble import RandomForestClas...
<gh_stars>1-10 # -*- coding: utf-8 -*- # # halft_np.ones.py - Modules for halftone # # # Autor: <NAME> [<EMAIL>] # License: GPL V.2 # # see: http://www.sawp.com.br # # Sep 2011 # import halftones.compiled as _compiled import numpy as _np import scipy.misc as _spm def __get_ordered_threshold(type="clustered dot"): ...
import sys import scipy.misc from matplotlib import cm from PIL import Image #Parse command line arguments filename = sys.argv[1] basename = filename.split('.') #Read input image im = scipy.misc.imread(filename, flatten=True) #Read crosshair overlay overlay = Image.open("crosshair.png") overlaycolor = Image.open("...
<filename>asvgd/experiments.py import sys sys.path.append('../') import time import torch import torch.nn.functional as F from torch.distributions.normal import Normal import numpy as np from svgd.experiments import OneDimNormalMixture, generate100Dim from svgd.svgd import RBF_kernel from asvgd import asvgd from scipy....
<filename>kge_from_text/bridges/table_linking_bridge.py import pandas as pd import itertools from kge_from_text.utils import helpers from scipy.spatial.distance import cosine import numpy as np class TableLinkingBridge: """ This class handles bridging from word to entities """ def __init__(self, bri...
import scipy.misc from visdom import Visdom import numpy as np import argparse parser = argparse.ArgumentParser() parser.add_argument('--datafile', type=str, default='', help='Path to data file') args = parser.parse_args() # Image size of grid world grid_ims...
from __future__ import unicode_literals import numpy as np import json import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from scipy.stats import spearmanr, kendalltau, shapiro, kstest from sklearn.metrics import precision_score, recall_score def get_sorted(sortKey, idx, time_array, reverse=Fa...
<gh_stars>0 import pathlib _2020 = pathlib.Path('2020') try: latest_day = max(_2020.glob('day??.py')) new_day = int(latest_day.stem[-2:]) + 1 except ValueError: # No days yet new_day = 1 code = """\ import collections, datetime, decimal, difflib, fractions, functools, \\ itertools, math, oper...
# -*- coding: utf-8 -*- """ LTF_ML_Notchfilter_py.py ========================================== Kapitel "LTI-Systeme im Frequenzbereich" Musterloesung zur Aufgabe "Notchfilter" (c) 2014-Feb-04 <NAME> - Files zur Vorlesung "DSV auf FPGAs" ======================================================================...
<gh_stars>1-10 import pandas as pd import math from .bayesian.main import binomial_ab_test, gaussian_ab_test from scipy.stats.distributions import chi2 # Adjust metric stats to account for unconverted users def get_adjusted_stats(x, sx, c, n, ignore_nulls=False, type="binomial"): if type == "binomial": re...
import csv import math import scipy as sp import matplotlib import matplotlib.pyplot as plt import numpy as np import pandas as pd import datetime import networkx as nx import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap from modules import * #### databeses from NYC open city dataset T = pd.r...
# -*- coding: utf-8 -*- # Released under the MIT License; see LICENSE. import matplotlib.pyplot as plt import numpy as np from scipy.integrate import trapz from scipy.stats import norm from scipy.misc import logsumexp from sampler import slice_sample # Some sample distributions, add your own! def bimodal_normal():...
#imports-------------------------------------------------------------------------------------------------------------------- import os import glob import sys #import wget import time import subprocess import shlex import sys import warnings import random import pickle from Bio.SeqUtils import seq1 from Bio.PDB.PDBPars...
<gh_stars>0 #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Nov 22 16:34:02 2019 This is an example of a parallelised script that does: - Flatfield correction with SSIM - 4-distance CTF-reconstruction (incl. correction for shifts) - Stripe artifact reduction - Automatic rotation axis detection - Tomo-...
<reponame>trevorcampbell/ubvi import numpy as np from scipy.stats import norm, multivariate_normal import unittest from distributions import Gaussian class TestGaussian(unittest.TestCase): def setUp(self): self.g1f = Gaussian(1, False) self.g2f = Gaussian(2, False) self.g4t = Gaussian(...
<reponame>Dorebom/robot_pybullet import numpy as np import pybullet as p from scipy.spatial.transform import Rotation as R class InverseKinematics6(): def __init__(self, robot_id, link_param, tool_pose): self.robot_id = robot_id self.link_param = link_param self.tool_pose = tool_pose ...
<filename>Face_recognition_02.py<gh_stars>0 from scipy.spatial.distance import cosine import numpy as np import cv2 import mtcnn from keras.models import load_model from utils import get_face, plt_show, get_encode, load_pickle, l2_normalizer from sklearn.svm import SVC from sklearn.metrics import accuracy_score from sk...
<gh_stars>0 import numpy as np from scipy.integrate import fixed_quad I_exact = np.log(3) print(f"I_exact is {I_exact} (=ln(3))") n = 1 while True: I_approx = fixed_quad(lambda x : 1/(1-x), -1/2, 1/2, n=n)[0] n += 1 print(f"I_approx is {I_approx} with order of quadrature integration n={n}") if I_appro...
<reponame>kbefus/ca_gw_slr # -*- coding: utf-8 -*- """ Created on Wed May 11 13:53:40 2016 @author: kbefus """ from __future__ import print_function import os,sys,shutil from osgeo import osr, ogr import numpy as np import shapefile from shapely.geometry import Polygon,MultiPoint,LineString,MultiPolygon#,Mu...
<reponame>PatrickRatei/eVTOL # Functions for rotor noise prediction from __future__ import print_function import numpy as np import math pi = math.pi from scipy.special import jv from gpkit import Model, ureg from matplotlib import pyplot as plt from aircraft_models import OnDemandAircraft from mission_models import ...
<reponame>Sharpiless/GraphGallery import numpy as np import scipy.sparse as sp from graphgallery.transforms import Transform class SparseAdjToSparseEdges(Transform): def __call__(self, adj_matrix): return sparse_adj_to_sparse_edges(adj_matrix) def __repr__(self): return f"{self.__class__.__na...
# Copyright 2020 MIT Probabilistic Computing Project. # See LICENSE.txt from collections import OrderedDict from itertools import chain from itertools import combinations from math import isinf import numpy import sympy from sympy.core.relational import Relational from .sets import FiniteReal from .sets import Inte...
<gh_stars>1-10 from __future__ import print_function, division from matplotlib import pyplot as plt import scipy.integrate as integrate import numpy as np from getMags import quasarMag import scipy.stats import subprocess import sys import os import shutil import argparse import warnings import datetime import config...
"""Reconstruction routines.""" import numpy as truenp from prysm.mathops import np def prepare_Zmm(zernike_chops, flux_mode=None, shear_chops=None, mask=None): """Assemble Zmm from chop images. Parameters ---------- zernike_chops : `iterable` of numpy.ndarray set of zernike chops. Assumed ...
<filename>quantizer/pq.py from __future__ import division from __future__ import print_function import numpy as np from scipy.cluster.vq import vq, kmeans2 class PQ(object): def __init__(self, M, Ks, verbose=True): assert 0 < Ks <= 2 ** 32 self.M, self.Ks, self.verbose = M, Ks, verbose sel...
<gh_stars>1-10 import numpy as np from numpy.linalg import inv, svd from numpy.random import multivariate_normal, randn, rand from logistic import logit from optim_algo import (Newton_MR, Newton_CG, L_BFGS, Gauss_Newton, MomentumSGD, Adagrad, Adadelta, RMSprop, Adam, SGD) from loaddata import l...
<gh_stars>1-10 # Siamese Architecture for face recognition import random import numpy as np import time import tensorflow as tf import math import pdb import sys import scipy.io as sio from sklearn import * import matplotlib.pyplot as plt def Plot_PR_Fn(label,distance,phase): precision, recall, thresholds = metr...
<filename>testRegression.py # _*_coding: utf-8_*_ import hashlib import os import tarfile import matplotlib import matplotlib.pyplot as plt import numpy as np import pandas as pd import sklearn from six.moves import urllib DOWNLOAD_ROOT = 'https://raw.githubusercontent.com/ageron/handson-ml/master/' # print('currect...
# a number of utilities that can be used to store and analyze results of GLOFRIM import fiona import xarray as xr import numpy as np import rasterio import rasterio.features from scipy.signal import convolve2d def perpendicular(line, reverse=False): """ determines the direction of a perpendicular line inpu...
<reponame>cactuskid/Fourier2Struct<filename>notebooks/ProFET/ProFET/feat_extract/Model_Parameters_CV.py from __future__ import division from sklearn.ensemble import ExtraTreesClassifier, RandomForestClassifier, \ GradientBoostingClassifier import numpy as np from sklearn import metrics, cross_validation #, linear_...
<reponame>acrellin/cesium import numpy as np import scipy.stats as stats from ._lomb_scargle import lomb_scargle def lomb_scargle_model(time, signal, error, sys_err=0.05, nharm=8, nfreq=3, tone_control=5.0): """Simultaneous fit of a sum of sinusoids by weighted least squares: y(t) = Sum_k Ck*t^k + Sum_...
import pandas as pd import numpy as np from scipy.stats import binned_statistic from scipy.optimize import curve_fit, newton import pmesh #from halotools.mock_observables import tpcf #from halotools import mock_observables as mo from nbodykit.lab import * from astrild.utils import read_hdf5 class SubFind: def ...
""" Module containing functions to act on the Spatial Fourier Coefficients. `BEMA` Perform Bandwidth Extension for Microphone Arrays (BEMA) spatial anti-aliasing. `FFT` Perform real-valued Fast Fourier Transform (FFT). `iFFT` Perform inverse real-valued (Fast) Fourier Transform (iFFT). `spatFT` Per...
import matplotlib.pyplot as plt import seaborn as sns import pandas as pd from scipy import stats plt.switch_backend('agg') ### 两个数据的比率图 # f, ax = plt.subplots(figsize=(16, 8)) # fig = sns.boxplot(x=var, y="SalePrice", data=data) # fig.axis(ymin=0, ymax=800000) # plt.xticks(rotation=90) #### 画总体概览图 def f3(): #...
#!/usr/bin/python3.6 import json import pickle import sys import numpy as np import pandas as pd import matplotlib.pyplot as plt from PIL import Image from tqdm import tqdm from scipy.stats import describe from debug import dprint with open('imagenet1000.txt') as f: imagenet = eval(f.read()) categories = lis...
import gurobipy as gp from gurobipy import GRB import numpy as np import scipy.sparse as sp try: # 创建模型 m = gp.Model("model_name") # 创建变量 x1 = m.addVar(vtype=GRB.BINARY, name="x1") # 0,1变量 x2 = m.addVar(vtype=GRB.BINARY, name="x2") # 0,1变量 '''x3 = m.addMVar(shape=3, vtype=GRB.BINARY , name ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import pandas as pd import numpy as np from scipy import sparse data = pd.read_excel('curated_df_11_3.xlsx') SMILES = data['SMILES'] protein = data['Protein'] Ki = data['Ki'] SMILES_string_length = 100 protein_string_length = 1000 SMILES_n_encodings = 28 protein_n_encod...
#Importo librerias import pandas as pd import numpy as np import matplotlib.pyplot as plt import os from scipy.optimize import curve_fit import glob # Altura de las mediciones z=2.85 camino = 'D:\\Mediciones\\Filtrados\\*' # Para calcular los otros espectros cambiar aca direccion = glob.glob( camino + '\...
# -*- coding: utf-8 -*- import numpy as np from scipy.stats.distributions import norm, lognorm, rv_frozen class BrownianMotion: '''Brownian Motion (Wiener Process) with optional drift.''' def __init__(self, mu: float=0.0, sigma: float=1.0): self.mu = mu self.sigma = sigma def simulate(se...