text string |
|---|
<reponame>Strabes/helpers
import scipy.stats as ss
import numpy as np
from itertools import combinations_with_replacement
import pandas as pd
from scipy.sparse.csgraph import reverse_cuthill_mckee
from scipy.sparse import csr_matrix
def cramers_corrected_stat(confusion_matrix):
"""
Calculate Cramers V statisti... |
from collections import defaultdict
# from hdbscan import HDBSCAN
from scipy.sparse.csgraph import connected_components
from sklearn.cluster import AffinityPropagation, MeanShift, DBSCAN
from sklearn.decomposition import LatentDirichletAllocation
from sklearn.metrics.pairwise import *
import dask.dataframe as dd
from... |
#!/usr/bin/env python
#
# Author: <NAME> <<EMAIL>>
#
'''
Intrinsic Atomic Orbitals
ref. JCTC, 9, 4834
'''
from functools import reduce
import numpy
import scipy.linalg
from pyscf import gto
# Alternately, use ANO for minao
# orthogonalize iao by orth.lowdin(c.T*mol.intor(ovlp)*c)
def iao(mol, orbocc, minao='minao'... |
# <NAME>
# Trains PVQA Models on the provided features and saves the trained model
# Features must be extracted before running this file
# Author: <NAME>
# Last Modified: 14-12-2021
import json
from pathlib import Path
import joblib
import numpy
import pandas
import scipy.stats
from sklearn.decomposition import PCA
fr... |
<reponame>NelisW/RBF
import rbf.basis
import rbf.poly
import numpy as np
import sympy
import unittest
def test_positive_definite(phi, order=None, dim=2, ntests=100):
# generate a random vector to test if the RBF is (conditionally) positive
# definite
for _ in range(ntests):
x = np.random.uniform(0.... |
'''
Optimize function which does not change (too much)
with its every new evaluation
Initialization: with bounds. These can be real/integer interval or category
@author: iaroslav
'''
import random
import numpy as np
from scipy.spatial.distance import pdist, squareform
from scipy.optimize import minimize
import heap... |
#! /usr/bin/env python
import sys
import time
import random
import argparse
import itertools
import numpy as np
import baldor as br
import raveutils as ru
import robotsp as rtsp
import openravepy as orpy
from scipy.spatial import ConvexHull
from lenny_openrave.manager import EnvironmentManager
from lenny_openrave.sche... |
<filename>hhpy/ds.py<gh_stars>0
"""
hhpy.ds.py
~~~~~~~~~~
Contains DataScience functions extending on pandas and sklearn
"""
# ---- imports
# --- standard imports
import numpy as np
import pandas as pd
import warnings
import os
# --- third party imports
from copy import deepcopy
from scipy import stats, signal
from ... |
<reponame>XavierDingRotman/OptionsFutures
from math import sqrt, exp
from scipy.stats import norm
from opfu.bsm import N, bsm_price, d1, d2
def N_d(x):
return norm.pdf(x)
def delta(S0, K, r=0.01, sigma=0.1, T=1, ds=0, is_call=True):
if ds == 0:
# the theortical result
if is_call:
... |
<reponame>VectorInstitute/DANER<filename>backend/models/al_model.py<gh_stars>1-10
import os
import sys
import json
import datetime
import types
from collections import defaultdict
from copy import deepcopy, copy
import torch
import scipy
import numpy as np
from torch.utils.data.dataloader import DataLoader
from data... |
<reponame>induane/stomp.py3<gh_stars>0
import math
import random
import re
import socket
import sys
import threading
import time
import types
import xml.dom.minidom
import errno
try:
from cStringIO import StringIO
except ImportError:
from io import StringIO
protocols = frozenset([
'PROTOCOL_SSLv3',
'P... |
<gh_stars>0
import h5py
import logging
import lsd
import mahotas
import numpy as np
from scipy.ndimage.filters import gaussian_filter, maximum_filter
logging.basicConfig(level=logging.INFO)
logging.getLogger('lsd.agglomerate').setLevel(logging.DEBUG)
size = (1, 100, 100)
def create_random_segmentation(seed):
np... |
from __future__ import division, print_function
import math
import numpy as np
from scipy import linalg
from matplotlib.pyplot import plot, subplot, legend, figure
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
import example2sys as e2s
import analysis
def optionPricingScript():
N = 1000
... |
<filename>detectron2/tracking/hungarian_tracker.py<gh_stars>1-10
#!/usr/bin/env python3
# Copyright 2004-present Facebook. All Rights Reserved.
import copy
import numpy as np
from typing import Dict
import torch
from scipy.optimize import linear_sum_assignment
from detectron2.config import configurable
from detectron2... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 25 19:18:35 2020
@author: siddhesh
"""
from __future__ import print_function, division
import os
import sys
import time
import pandas as pd
import torch
import nibabel as nib
import tqdm
import numpy as np
from skimage.transform import resize
from ... |
<reponame>karthikbadam/facetnotes
import sys
import os
import shutil
import time
import traceback
import json
from datetime import datetime
from math import sqrt
import random
import pickle
## database and server
import pymongo
from flask import Flask
from flask import request, render_template, send_from_directory, j... |
<reponame>shawnxysun/DRL-ice-hockey<filename>td_three_prediction_lstm.py
import csv
import tensorflow as tf
import os
import scipy.io as sio
import numpy as np
from nn.td_prediction_lstm_V3 import td_prediction_lstm_V3
from nn.td_prediction_lstm_V4 import td_prediction_lstm_V4
from utils import handle_trace_length, get... |
import logging
import os
from typing import Dict, List, Optional, Tuple
import numpy.typing as npt
import matplotlib.pyplot as plt
import numpy as np
import scipy.fftpack as fp
from skimage.transform import resize
import nanotune as nt
logger = logging.getLogger(__name__)
NOISE_TYPES = ["white", "rnt", "one_over_f",... |
<gh_stars>1-10
from fractions import Fraction as F
from dex_open_solver.core.order import Order
max_nr_orders_constraint_examples = [
{
'b_orders': [
Order('T0', 'T1', 20019, F(3, 10))
],
's_orders': [
Order('T1', 'T0', 50096, F(51, 10)),
Order('T1', 'T0... |
<reponame>CrazySerGo/sv-manager
import time
import solana_rpc as rpc
from common import debug
from common import ValidatorConfig
import statistics
import numpy as np
import tds_info as tds
from common import measurement_from_fields
def load_data(config: ValidatorConfig):
identity_account_pubkey = rpc.load_identity... |
<reponame>chamathpali/clood
import sys
import os
import json
import copy
import requests
import time
from timeit import default_timer as timer
from elasticsearch import Elasticsearch, helpers, RequestsHttpConnection
from requests_aws4auth import AWS4Auth
# imports for hash - to test for unique records
import hashlib
fr... |
"""\
Animation and frame objects
"""
import numpy as np
from scipy.spatial.transform import Rotation as Rot
from model import Vertex, Normal, Model
class Animation(object):
def __init__(self, frames, groups):
self.groups = groups
self.frames = frames
class Frame(object):
def __init__(self, i... |
import numpy as np
from scipy.stats import norm
class UtilScore:
def __init__(self):
self.design_points = -1+np.arange(1, 401)/100
self.weight = norm.cdf((self.design_points-1.5)/0.4)
def twCRPS(self, prediction, true_observations):
observations = self.indicator(true_observations)
... |
<filename>slugdetection/Slug_Forecasting.py
# -*- coding: utf-8 -*-
"""
Part of slugdetection package
@author: <NAME>
github: dapolak
"""
import numpy as np
import matplotlib.pyplot as plt
import math
from sklearn.metrics import mean_squared_error, r2_score
from statsmodels.tsa.arima_model import ARIMA
from statsmo... |
### ©2020. Triad National Security, LLC. All rights reserved.
### This program was produced under U.S. Government contract 89233218CNA000001 for Los Alamos National Laboratory (LANL), which is operated by Triad National Security, LLC for the U.S. Department of Energy/National Nuclear Security Administration. All rights... |
<gh_stars>10-100
from scipy.stats import zscore
import numpy as np
# method to get expression data of all samples
def get_expression_data(data, sample_list,genes_by_signature, signatures_by_gene):
data_columns = []
# get column index of each sample
header_split = data[0].rstrip().split("\t")
for samp... |
<reponame>DBernardes/Macro-SPARC4-CCD-cameras<filename>Codigos_python/Graficos/FrequenciaAcq_Texp/FrequenciaAcq_x_Texp_AllModes.py<gh_stars>0
#!/usr/bin/env python
# coding: utf-8
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
#----------------- 0.1 MHz,... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Functions to support the creation of training and validation data.
A cell-synapse like outline to contain the points with the wider field of view.
@author: dave
"""
import numpy as np
import os
from shapely.geometry import Polygon, MultiPoint
from matplotlib.path i... |
# -*- coding: utf-8 -*-
# This work is part of the Core Imaging Library (CIL) developed by CCPi
# (Collaborative Computational Project in Tomographic Imaging), with
# substantial contributions by UKRI-STFC and University of Manchester.
# Licensed under the Apache License, Version 2.0 (the "License");
# you... |
from scipy.signal.windows import hamming
import numpy as np
from scipy.fft import rfft, rfftfreq
# Генератор, возвращает чанк из n элементов
def chunks(lst, n):
for i in range(0, len(lst), n):
yield lst[i:i + n]
def get_windowed_fft_result(data, frame_rate: int, window_size: int, window_func=hamming) -> ... |
##
# @file
# This file is part of SeisSol.
#
# @section LICENSE
# Copyright (c) SeisSol Group
# 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 mus... |
<filename>data_sim/libs/utils.py
import logging
import numpy as np
import pandas as pd
from scipy.interpolate import interp1d
def sigmoid(x):
return 1/(1 + np.exp(-x))
def Init_logging():
log = logging.getLogger()
log.setLevel(logging.INFO)
logFormatter = logging.Formatter('%(asctime)s ... |
import numpy as np
from scipy.special import factorial
'''
The range of indexes of the columns in the TiteSeq input CSV to use as
normalized counts.
'''
NORMALIZED_COUNT_COLUMN_RANGE = (33, 65)
'''
The range of indexes of the columns in the TiteSeq input CSV to use as raw counts.
'''
READ_COUNT_COLUMN_RANGE = (1, 33)... |
import numpy as np
from scipy.spatial.distance import squareform
from scipy.cluster.hierarchy import linkage, fcluster
from collections import Counter
class Normalizer:
"""
"""
def __init__(self, col_infos, max_distinct=1000):
"""
Initilizing normalizer class
:param col_infos: c... |
<gh_stars>0
#%%
# see also this version from leaderboards: https://www.kaggle.com/guocan/logistic-regression-with-words-and-char-n-g-13417e
import pandas as pd
import numpy as np
import os
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from scipy.sparse import l... |
<gh_stars>0
# ----------------------------------------------------------------------------
# Copyright (c) 2020, <NAME>.
#
# Distributed under the terms of the MIT License.
#
# The full license is in the file LICENSE, distributed with this software.
# --------------------------------------------------------------------... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import scipy.odr
import itertools
def computeModelDetails(frame):
""" Takes a dataframe and computes columns related to the dynamical frb model """
tauwerror_expr = lambda r: 1e3*r['time_res']*np.sqrt(r['max_sigma']**6*r['min_sigma_error']**2*np... |
import io
import time
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
from scipy.ndimage import convolve
# numpy representation of the RPi camera module v1 Bayer Filter
bayerGrid = np.zeros((1944, 2592, 3), dtype=np.uint8)
bayerGrid[1::2, fc00:db20:35b:7399::5, 0] = 1 # Red
bayerGrid[0::2, ... |
"""
Artificial Intelligence for Humans
Volume 2: Nature-Inspired Algorithms
Python Version
http://www.aifh.org
http://www.jeffheaton.com
Code repository:
https://github.com/jeffheaton/aifh
Copyright 2014 by <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
... |
<reponame>LyqSpace/ksvd
# coding:utf-8
from ksvd import ApproximateKSVD
from sklearn.decomposition import DictionaryLearning
from sklearn.utils.testing import assert_array_almost_equal
import numpy as np
import scipy as sp
from scipy.linalg import norm
def test_initialize_with_small_n_features():
N = 500
n_co... |
import numpy as np
from scipy import stats
from girth.unidimensional.polytomous import grm_mml_eap
__all__ = ["twopl_mml_eap"]
def twopl_mml_eap(dataset, options=None):
"""Estimate parameters for a two parameter logistic model.
Estimate the discrimination and difficulty parameters for
a two parameter ... |
<gh_stars>0
import numpy as np
import scipy.ndimage as ndimage
class RandomRotation(object):
def __init__(self, angle_list=[90,180,270], axis=0):
self.angles_idx_for_rotate = np.random.randint(0, len(angle_list))
self.angle_list =angle_list
self.axis = axis
def __call__(self, img_num... |
<filename>kidsdata/kids_plots.py
import warnings
from itertools import product
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
from scipy.signal import medfilt
from scipy.ndimage.filters import uniform_filter1d as smooth
import astropy.units as u
from astropy.stats import mad_... |
import sys
import time
from scipy.spatial.distance import cityblock
from obect_tracker import *
class ObjTracking:
def __init__(self):
self.id_counter = -1
self.obj_ids = dict()
def centroid(self, x1, y1, x2, y2):
return (((x1 + x2) // 2), ((y1 + y2) // 2))
def get_old_centroids(... |
<reponame>jmontgom10/Mimir_pyPol<filename>oldCode/03c_removeBadFilesInIndex.py
# Marks specific "bad" groups or files manually identified in the previous step
# as "unusable" in the file index.
import os
import sys
import numpy as np
from astropy.io import ascii
from astropy.table import Table as Table
from astropy.ta... |
<reponame>rtu715/NAS-Bench-360<gh_stars>1-10
"""Test architect helpers (that is, buffer, reward, store, manager)
"""
import os
import unittest
from parameterized import parameterized, parameterized_class
import tensorflow as tf
import numpy as np
import tempfile
import scipy.stats
from amber.utils import testing_utils... |
<reponame>Paoulus/noiseprint
# This code is the main of the noiseprint_blind
# python main_blind.py input.png output.mat
# python main_showout.py input.png output.mat
#
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#
# Copyright (c) 2019 Image Processing Research Group of University ... |
from . import Graph
from .graph.base import BaseGraph
from .utils import VertexType, EdgeType, FractionLike
from fractions import Fraction
from typing import List, Tuple
def cluster_state(m: int, n: int, inputs: List[Tuple[int,int]]=[]) -> BaseGraph:
"""Build a cluster state m qubits tall and n qubits wide. Opti... |
k= 8.617e-5 #eV/K Boltzmann
T= 30e-3 #temp of 1 mK
c=1
import numpy as np
from scipy.optimize import curve_fit
def gap(V, delta, Z, broadness, offset=0):
E = np.arange(1.5*min(V), 1.5*max(V), 1.5*k*T)
def u2(E, delta): #u0 squared, BCS coefficient
return .5 * (1+np.sqrt((E**2 - delta**2)/E**2))
d... |
import re
import os
import math
import logging
logger = logging.getLogger(__name__)
import numpy as np
from scipy.ndimage.filters import median_filter
import scipy.interpolate as intp
import scipy.signal as sg
import scipy.optimize as opt
import astropy.io.fits as fits
from astropy.table import Table
import matplotli... |
#!/usr/bin/env python3
"""Acquisition script for HP4194A Impedance Analyzer"""
import argparse
import configparser
import datetime
import os
import subprocess
import sys
import numpy
import pylab
import pyvisa
import scipy.io as scio
import matplotlib.pyplot as pyplot
DEBUG = False
FILE_EXT = '.mat'
def main(filen... |
"""
Loop object for holding field-aligned coordinates and quantities
"""
import numpy as np
from scipy.interpolate import splprep, splev, interp1d
import astropy.units as u
from astropy.coordinates import SkyCoord
from sunpy.coordinates import HeliographicStonyhurst
import sunpy.sun.constants as sun_const
import zarr
... |
<gh_stars>1-10
# coding: utf-8
# Consider the data in the files a100.csv, b100.csv, s057.csv. Try to determine the
# underlying probability distributions of each data set.
# In[3]:
# Using pandas library for CSV reading and table manipulation
import pandas
import matplotlib.pyplot as plt
# In[293]:
# Reading a1... |
<filename>dsbox-corex/corex_text.py
from sklearn import preprocessing
#import primitive
# Import corex_topic
import os
import sys
corex_path = os.path.dirname(
os.path.abspath(__file__)) + os.sep + "corex_topic"
sys.path.append(corex_path)
from corex_topic import Corex
from collections import defaultdict
from sci... |
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 10 09:49:17 2018
@author: Brendan
Usage:
python fftAvg.py --processed_dir DIR [--time_step 1] [--mmap_datacube True] [--num_segments 2]
To use mpi, use
mpiexec -n N python fftAvg.py ...
where N = number of processors
"""
desc = """
PSD segment and pixel box averagin... |
# coding=utf-8
# Copyright 2021 The OneFlow Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless require... |
#!/usr/bin/python
import numpy as np
from scipy import signal, misc
import matplotlib.pyplot as plt
from idealbattery import IdealBattery
from prismatic import PrismaticBattery
from custom_types import *
VSOC_CHARGE = '../data/vsoc_charge.txt'
VSOC_DISCHARGE = '../data/vsoc_discharge.txt'
bat = PrismaticBattery(20,... |
"""Defining hot carrier solar cell properties
Most attributes should be self explanetory.
If choose thermionic emission,
self.Jext = self.JextTherm
self.Uext = self.UextTherm
If choose tunneling
self.Jext = self.JextESC
self.Uext = self.UextESC
display_attributes(self) method in hcscAttribut... |
<reponame>teslakit/teslak
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# pip
from datetime import timedelta
import numpy as np
import xarray as xr
from scipy.stats import gumbel_l, genextreme
from .util.time_operations import date2datenum as d2d
def FitGEV_KMA_Frechet(bmus, n_clusters, var):
'''
Returns st... |
<reponame>def670/lfd
import numpy as np
import scipy.interpolate as si
def shortest_path(ncost_nk,ecost_nkk):
"""
ncost_nk: N x K
ecost_nkk (N-1) x K x K
"""
N,K = ncost_nk.shape
cost_nk = np.empty((N,K),dtype='float')
prev_nk = np.empty((N-1,K),dtype='int')
cost_nk[0] = ncost_nk[0]
... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import statsmodels
import math
import matplotlib.ticker as tkr
from numpy import median
species = pd.read_csv(r"Medical\\DataCleaning\\DataTransformation\\BiodiversityEndangeredAnimalsProject\\species_info.csv")
observatio... |
<reponame>IBM/regression-transformer
#!/usr/bin/env python3
"""
Language modeling adapted from Huggingface transformers.
"""
import json
import logging
import os
from dataclasses import dataclass, field
from typing import Dict, List, Optional, Tuple, Union
import numpy as np
import pandas as pd
import torch
import tor... |
<reponame>Hazematman/Ultrabrew2021
#!/usr/bin/env python3
import sys
import argparse
import os
import math
from PIL import Image
from scipy.spatial.transform import Rotation as scirot
description = "n64_mdl_parse"
S64_VERT_X = 0
S64_VERT_Y = 1
S64_VERT_Z = 2
S64_VERT_XN = 3
S64_VERT_YN = 4
S64_VERT_ZN = 5
S64_VERT_R ... |
<reponame>DanielMorales9/LinearRegression<gh_stars>0
from classification import LogisticRegression
from numpy import shape, dot, e, ones, log, sum, unique, \
power, zeros, reshape, concatenate, argmax, mean
from numpy.random import rand
from random import random
from scipy.optimize import fmin_l_bfgs_b
class FastN... |
import sys
import time
# pyStatReduce specific imports
import unittest
import numpy as np
import chaospy as cp
import copy
from pystatreduce.new_stochastic_collocation import StochasticCollocation2
from pystatreduce.stochastic_collocation import StochasticCollocation
from pystatreduce.monte_carlo import MonteCarlo
fro... |
<gh_stars>1-10
from pathlib import Path
from skimage.color import grey2rgb
from skimage.io import imread, imsave
from skimage.morphology import binary_dilation
from skimage import img_as_uint, img_as_float
import matplotlib.pyplot as plt
import numpy as np
import scipy.ndimage as ndi
from inpainting import Inpaint... |
from tkinter import *
from tkinter import filedialog, messagebox
from obspy import read
import matplotlib
matplotlib.use('TkAgg')
from matplotlib import pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAg... |
<gh_stars>0
import pytest
import numpy as np
from scipy import stats as spst
import scipy.ndimage as spim
import porespy as ps
import openpnm as op
from edt import edt
ws = op.Workspace()
ws.settings['loglevel'] = 50
ps.settings.tqdm['disable'] = True
class Snow2Test:
def setup_class(self):
self.spheres3D... |
<gh_stars>10-100
import numpy as np
from scipy.stats import multivariate_normal
class GMM:
def fit(self, X, n_clusters, epochs):
"""
Parameters
----------
X : shape (n_samples, n_features)
Training data
n_clusters : The number of clusters
epochs : The nu... |
<gh_stars>10-100
import os, sys, inspect
sys.path.insert(1, os.path.join(sys.path[0], '../../'))
import torch
import torchvision as tv
import argparse
import time
import numpy as np
from scipy.stats import binom
from PIL import Image
import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
import pickle as... |
import sqlite3
import sys
import logging
import ntpath
from statistics import mean
from collections import namedtuple
from collections import defaultdict
from bd_rate_calculator import BDrateCalculator
from analyze_encoding_results import apply_size_check
__author__ = "<NAME>"
__copyright__ = "Copyright 2019-2020, Net... |
#!/bin/python3
# author: <NAME>
from collections import defaultdict
import matplotlib.axes
import matplotlib.figure
from cihpc.cfg.config import global_configuration
from cihpc.common.utils.datautils import flatten
from cihpc.core.db import CIHPCMongo
import pandas as pd
import numpy as np
from scipy import stats
fro... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from mm.utils.mesh import generateFace
from mm.utils.transform import rotMat2angle
from mm.utils.io import importObj, speechProc
from mm.models import MeshModel
import os
import numpy as np
from sklearn.neighbors import NearestNeighbors
from sklearn.mixture import Gaussia... |
<gh_stars>10-100
from typing import Union, List, Tuple, Callable, Set
import colorcet
import holoviews as hv
import hvplot.pandas
import numpy as np
import pandas as pd
import scipy.sparse
from anndata import AnnData
from holoviews import dim
from holoviews.plotting.bokeh.callbacks import LinkCallback
from holoviews.p... |
import logging
import numpy as np
from scipy.optimize import linear_sum_assignment
from ...utils.time import timeit
from .track import DeepTrack
from .kalman import chi2inv95
from .utils import tlbr_to_xyah
logger = logging.getLogger(__name__)
class DeepTracker:
def __init__(self):
self._tracks = []
... |
<gh_stars>0
import GMatElastoPlasticFiniteStrainSimo.Cartesian3d as GMat
import numpy as np
import scipy.sparse.linalg as sp
import itertools
# turn of warning for zero division
# (which occurs in the linearization of the logarithmic strain)
np.seterr(divide='ignore', invalid='ignore')
# -----------------------------... |
import os
import cv2
import numpy as np
from datetime import datetime
import matplotlib.pyplot as plt
import scipy.stats as stats
from scipy.ndimage.morphology import generate_binary_structure, grey_erosion, grey_dilation
import consts
from common import utils, logger, ImageLocationUtility, PatchArray
class Visual... |
"""
expand_labels is derived from code that was
originally part of CellProfiler, code licensed under BSD license.
Website: http://www.cellprofiler.org
Copyright (c) 2020 Broad Institute
All rights reserved.
Original authors: CellProfiler team
"""
import numpy as np
from scipy.ndimage import distance_transform_edt
... |
<filename>symfit/core/support.py
# SPDX-FileCopyrightText: 2014-2020 <NAME>
#
# SPDX-License-Identifier: MIT
"""
This module contains support functions and convenience methods used
throughout symfit. Some are used predominantly internally, others are
designed for users.
"""
from __future__ import print_function
from c... |
<filename>pca.py
import pandas as pd
from scipy.sparse.construct import random
import sklearn
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.decomposition import IncrementalPCA
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
fro... |
<filename>SatGen/config.py
#########################################################################
#
# global variables
#
# import config as cfg in all related modules, and use a global variable
# x defined here in the other modules as cfg.x
# <NAME> 2017 Hebrew University
# <NAME> 2020 Yale University
# <NAME> 2021... |
#!/usr/bin/env python2
"""
Copyright (C) 2019 <NAME>, ETH Zurich
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 limitation
the rights to use, copy, modify,... |
<filename>lib_dsp/fft_bf/fft_bf/verif/fft_bf_ref_model.py<gh_stars>0
from pygears.typing import code
from scipy.fft import fft
def round_to_fixp(din, t):
rounded = din * (2**t.fract) // 1
if rounded == 2**(t.width - 1):
rounded -= 1
return code(int(rounded), cast_type=t)
def fft_bf_ref_model(inp... |
# Authors: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
#
# License: BSD (3-clause)
import numpy as np
from scipy import linalg
from .fiff.constants import FIFF
from .fiff.open import fiff_open
from .fiff.tree import dir_tree_find
from .fiff.tag import find_tag, read_tag
from .fiff.matrix import _read_named_matrix, _... |
import logging
from typing import List, Tuple
import matplotlib.pyplot as plt
import numpy
from scipy.optimize import linear_sum_assignment
from tifffile import imread
from hylfm.detect_beads import get_bead_pos
from hylfm.detect_beads import plot_matched_beads
logger = logging.getLogger(__name__)
def match_beads_... |
<filename>consumer/deploy/MUI.py
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from symbol.resnet import *
from symbol.config import config
from symbol.processing import bbox_pred, clip_boxes, nms
import face_embedding
import numpy as np
import cv2, os, js... |
# -*- coding: utf-8 -*-
# @Author: <NAME>
# @Email: <EMAIL>
# @Date: 2016-09-19 22:30:46
# @Last Modified by: <NAME>
# @Last Modified time: 2021-05-15 11:04:35
''' Definition of generic utility functions used in other modules '''
import sys
import itertools
import csv
from functools import wraps
import operator
i... |
from scipy import signal
from pygears_dsp.lib.iir import iir_df1dsos, iir_df2tsos
from pygears.sim import sim
from pygears_control.lib import scope
from pygears import config
from math import pi, sin
import pytest
from pygears.lib import check, drv
from pygears.typing import Fixp, Float
from pygears.sim import sim
@p... |
"""Challenge symmetries with the sklearn interface."""
import math
from dataclasses import dataclass
from typing import Optional, Callable
from numbers import Integral
import numpy
import scipy
@dataclass
class WhichIsReal:
"""Package a symmetry testing setup with methods to hook into sklearn."""
transform:... |
import unittest
from sdp_par_model.parameters.container import *
from sympy import Mul, Function
class ContainerTests(unittest.TestCase):
def test_bldep(self):
b = Symbol('_b')
b2 = Symbol('_b2')
bcount = Symbol('bcount')
self.assertEqual(BLDep(b, b)(1000), 1000)
self.a... |
from statistics import mode
def moda(muestras):
frecuencias = {}
for muestra in muestras:
if muestra not in frecuencias.keys():
frecuencias[muestra] = 1
else:
frecuencias[muestra] += 1
valores = []
frecuencia_maxima = max(frecuencias.values())
for clave in f... |
'''
Efficient representation of word embeddings
'''
import numpy as np
import heapq
import os
from scipy.sparse import dok_matrix, csr_matrix
class Embeddings:
def __init__(self, path, unk='<unk>', normalize=True, one_hot=False, stats_count=False):
'''
:param path: path where embeddings file .npy... |
<filename>code/sierpinski.py
"""File containing the daughter class of the base FractalLattice
class used to generate explicit types of the lattice."""
from typing import Tuple, List
import numpy as np
import scipy.spatial as spatial
from math import hypot
from sierpinski_base import FractalLattice
class LatticeT... |
<reponame>FilipKlaesson/cops
from itertools import product, combinations
import numpy as np
import scipy.sparse as sp
from cops.optimization_wrappers import Constraint
def generate_powerset_dynamic_constraints(problem):
# Define number of variables
if problem.num_vars == None:
problem.compute_num_v... |
import numpy as np
import scipy.optimize as op
def optimization(gp, t, y, **minimize_kwargs):
# Define the objective function (negative log-likelihood in this case).
def nll(p):
gp.set_parameter_vector(p)
ll = gp.log_likelihood(y, quiet=True)
return -ll if np.isfinite(ll) else 1e25
... |
<gh_stars>0
import pyglet
from pyglet import shapes, text, clock
from math import atan2, pi, cos, sin, tan, sqrt, atan
from cmath import exp
window_dimensions = (640,480)
window = pyglet.window.Window(*window_dimensions)
batch = pyglet.graphics.Batch()
vertex = (window_dimensions[0]/2,0)
parabola_width = window_dime... |
from scipy.stats import chi2
from numpy import log
from multiprocessing import cpu_count, Pool
#unfinished class which requires peptide level p-values are present
#these aren't produced by percolator output but if you were using
#psms from elsewhere then you might want to use this.
#def fishers_method(self, pn):
#
... |
<reponame>shangan23/similar-sentences
import numpy as np
import scipy.spatial
import logging
import json
import nltk
import zipfile
import os
import xlsxwriter
from sentence_transformers import SentenceTransformer, LoggingHandler
from .TrainSentences import TrainSentences
from sys import exit
from tqdm import tqdm
cla... |
from scipy import interpolate
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-5, 5, 2)
y = np.arange(-5, 5, 2)
xx, yy = np.meshgrid(x, y)
z = np.sin(xx**2+yy**2)
f = interpolate.interp2d(x, y, z, kind='cubic')
xnew = np.arange(-5, 5, 1)
ynew = np.arange(-5, 5, 1)
xxnew, yynew = np.meshgrid(xnew, yne... |
<filename>hw2/homework2.py
import os
import re
import math
import seaborn
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
from sklearn import metrics
from sklearn import linear_model
from scipy.stats import linregress
from sklearn.decomposition import PCA
from ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.