repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
Swivel-Finance/swivel-py
swivel/tests/market_place_test.py
import pytest from swivel.helpers import call, transact @pytest.fixture(scope='module') def swivel_address(): return '0x8e7bFA3106c0544b6468833c0EB41c350b50A5CA' @pytest.fixture(scope='module') def underlying(market_place): return market_place.vendor.instance.toChecksumAddress('0x5592ec0cfb4dbc12d3ab100b25715...
Swivel-Finance/swivel-py
swivel/abstracts/deployed.py
<reponame>Swivel-Finance/swivel-py<filename>swivel/abstracts/deployed.py from abc import ABC class Deployed(ABC): def at(self, a, opts=None): """Get a reference to the vendor specific contract instance deployed at a given address Parameters: a (string) the address of the deployed smart...
Swivel-Finance/swivel-py
swivel/contracts/swivel.py
<reponame>Swivel-Finance/swivel-py from py_eth_sig_utils.signing import signature_to_v_r_s from swivel.helpers import v_r_s_to_dict from swivel.abstracts import Swivel as base from .abi import SWIVEL class Swivel(base): def __init__(self, v): """ Parameters: v (W3) Instance of a vendor ...
Swivel-Finance/swivel-py
swivel/vendors/__init__.py
<gh_stars>0 from swivel.vendors.w3 import W3
Swivel-Finance/swivel-py
swivel/abstracts/swivel.py
from abc import abstractmethod from swivel.abstracts import Deployed class Swivel(Deployed): @abstractmethod def name(self, opts=None): """The stored name constant for this contract Returns: web3 callable, opts """ pass @abstractmethod def version(self, op...
Swivel-Finance/swivel-py
swivel/contracts/__init__.py
from swivel.contracts.vault_tracker import VaultTracker from swivel.contracts.market_place import MarketPlace from swivel.contracts.swivel import Swivel
Swivel-Finance/swivel-py
swivel/__init__.py
<gh_stars>0 name = 'swivel'
Swivel-Finance/swivel-py
swivel/vendors/signer.py
<gh_stars>0 from py_eth_sig_utils.signing import sign_typed_data, v_r_s_to_signature from swivel.constants import DOMAIN_NAME, DOMAIN_VERSION, HEX_PREFIX class Signer: def sign_order(self, o, i, a, k): """Sign an order, producing an EIP712 compliant signature Parameters: o (dict) Swive...
Swivel-Finance/swivel-py
swivel/abstracts/market_place.py
from abc import abstractmethod from swivel.abstracts import Deployed class MarketPlace(Deployed): @abstractmethod def admin(self, opts=None): """The stored admin address for this contract Returns: web3 callable, opts """ pass @abstractmethod def transfer_a...
Swivel-Finance/swivel-py
swivel/tests/vault_tracker_only_test.py
import pytest from swivel.contracts.bin import VAULT_TRACKER from swivel.helpers import call from swivel.contracts import VaultTracker from swivel.mocks.bin import CERC20 from swivel.mocks import CErc20 @pytest.fixture(scope='module') def c_token(vendor): cerc20 = CErc20(vendor) deployed = vendor.instance.eth....
Swivel-Finance/swivel-py
swivel/tests/helpers.py
class Caller: """A class used to mock the `.call` able objects returned from Web3 calls""" def call(o=None): pass class Transactor: """A class used to mock the `.transact` able objects returned from Web3 transaction calls""" def transact(o): pass
Swivel-Finance/swivel-py
setup.py
<reponame>Swivel-Finance/swivel-py from setuptools import setup, find_packages with open('README.md', 'r') as file: long_description = file.read() test_deps = [ 'pytest==6.2.5', 'eth-tester==0.5.0b4', 'web3==5.23.1', 'py-eth-sig-utils==0.4.0', ] extras = { 'test': test_deps, } setup( nam...
Swivel-Finance/swivel-py
swivel/tests/signer_test.py
<reponame>Swivel-Finance/swivel-py import pytest from py_eth_sig_utils.signing import recover_typed_data, signature_to_v_r_s from swivel.constants import DOMAIN_NAME, DOMAIN_VERSION, HEX_PREFIX @pytest.fixture(scope='module') def key(vendor): return vendor.instance.toBytes(hexstr='0xfb28b03032bbb105e1199e496b23a64...
Swivel-Finance/swivel-py
swivel/constants/__init__.py
DOMAIN_NAME = 'Swivel Finance' DOMAIN_VERSION = '2.0.0' HEX_PREFIX = '0x'
Swivel-Finance/swivel-py
swivel/contracts/vault_tracker.py
<filename>swivel/contracts/vault_tracker.py from swivel.abstracts import VaultTracker as base from .abi import VAULT_TRACKER class VaultTracker(base): def __init__(self, v): """ Parameters: v (W3) Instance of a vendor W3 class (no other vendors are supported as of now) """ ...
Swivel-Finance/swivel-py
swivel/abstracts/vault_tracker.py
from abc import abstractmethod from swivel.abstracts import Deployed class VaultTracker(Deployed): """Persists and curates Vault objects associated with users Note that a Vault is a Dict object in this form: { notional, redeemable, exchangerate } """ @abstractmethod def admin(self, opts=...
Swivel-Finance/swivel-py
swivel/helpers/__init__.py
from web3 import Web3 def call(args): return args[0].call(args[1]) def transact(args): """For unlocked accounts, we can simply call transact directly""" return args[0].transact(args[1]) # TODO **? def v_r_s_to_dict(t): """Transform the py-eth-sig-utils VRS tuple into a dict""" return {'v': t[0]...
Swivel-Finance/swivel-py
swivel/vendors/w3.py
<reponame>Swivel-Finance/swivel-py import os from web3 import Web3 from .signer import Signer class W3: def __init__(self, p, a=None): """ Parameters: p (Web3.Provider) Provider being used to connect a (address) An optional default account to use. Will default to .eth.accoun...
Ki-Seki/MATLAB
007/TOPSIS/topsis.py
<reponame>Ki-Seki/MATLAB """ TOPSIS法(优劣解距离法)介绍及 python3 实现 - Suranyi的文章 - 知乎 https://zhuanlan.zhihu.com/p/37738503 """ import pandas as pd import numpy as np # 以下三个函数均为数据正向化处理函数 def dataDirection_1(datas, offset=0): """ 极小型指标正向化 :param datas: 迭代器 :param offset: 防止出现除以 0 的错误 """ def normaliz...
jlliao/Decentralized-Energy-Blockchain
IoT/reset_pi_server.py
<gh_stars>1-10 import requests r = requests.put("", json=[]) # type your myjson api url print(r.status_code)
jlliao/Decentralized-Energy-Blockchain
IoT/simulate_pi.py
<filename>IoT/simulate_pi.py # simlate_pi.py - simulate action on raspberry pi import requests import random import time payload = [] SUN_ID = "ID000" CONSUMER_ID = "ID100" PROSUMER_ID = "ID101" MYJSON_URL = "" # type your myjson api url # create unit tests for i in range(10): random_pair = random.choice([[CONS...
jlliao/Decentralized-Energy-Blockchain
IoT/rasberry_pi.py
<reponame>jlliao/Decentralized-Energy-Blockchain import RPi.GPIO as GPIO import time import json from datetime import datetime import requests # Set up script to use the right pin configuration GPIO.setmode(GPIO.BCM) GPIO.setup(23, GPIO.IN) # set up your pin for prosumer GPIO.setup(18, GPIO.IN) # set up y...
jet86/plugin.video.netflix
resources/lib/NetflixHttpSubRessourceHandler.py
<reponame>jet86/plugin.video.netflix<gh_stars>10-100 #!/usr/bin/env python # -*- coding: utf-8 -*- # Module: NetflixHttpSubRessourceHandler # Created on: 07.03.2017 class NetflixHttpSubRessourceHandler: """ Represents the callable internal server routes & translates/executes them to requests for Netflix""" de...
jet86/plugin.video.netflix
resources/lib/Library.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Module: LibraryExporter # Created on: 13.01.2017 import os from shutil import rmtree from utils import noop try: import cPickle as pickle except: import pickle class Library: """Exports Netflix shows & movies to a local library folder""" series_label = 's...
jet86/plugin.video.netflix
resources/lib/utils.py
<filename>resources/lib/utils.py<gh_stars>10-100 #!/usr/bin/env python # -*- coding: utf-8 -*- # Module: utils # Created on: 13.01.2017 # Takes everything, does nothing, classic no operation function def noop (**kwargs): return True # log decorator def log(f, name=None): if name is None: name = f.func...
jet86/plugin.video.netflix
resources/lib/MSLHttpRequestHandler.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Module: MSLHttpRequestHandler # Created on: 26.01.2017 import BaseHTTPServer import base64 from urlparse import urlparse, parse_qs from MSL import MSL from KodiHelper import KodiHelper kodi_helper = KodiHelper() msl = MSL(kodi_helper) class MSLHttpRequestHandler(BaseH...
jet86/plugin.video.netflix
service.py
<gh_stars>10-100 #!/usr/bin/env python # -*- coding: utf-8 -*- # Module: service # Created on: 26.01.2017 import threading import SocketServer import socket from xbmc import Monitor from resources.lib.KodiHelper import KodiHelper from resources.lib.MSLHttpRequestHandler import MSLHttpRequestHandler from resources.lib....
jet86/plugin.video.netflix
addon.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Module: default # Created on: 13.01.2017 import sys from resources.lib.KodiHelper import KodiHelper from resources.lib.Navigation import Navigation from resources.lib.Library import Library # Setup plugin plugin_handle = int(sys.argv[1]) base_url = sys.argv[0] # init p...
jet86/plugin.video.netflix
resources/lib/NetflixSession.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Module: NetflixSession # Created on: 13.01.2017 import os import json from requests import session, cookies from urllib import quote, unquote from time import time from base64 import urlsafe_b64encode from bs4 import BeautifulSoup, SoupStrainer from utils import noop try...
jet86/plugin.video.netflix
resources/lib/pyjsparser/__init__.py
<reponame>jet86/plugin.video.netflix<filename>resources/lib/pyjsparser/__init__.py __all__ = ['PyJsParser', 'parse', 'JsSyntaxError'] __author__ = '<NAME>' __version__ = '2.2.0' from .parser import PyJsParser, parse, JsSyntaxError
jet86/plugin.video.netflix
resources/lib/NetflixHttpRequestHandler.py
<filename>resources/lib/NetflixHttpRequestHandler.py #!/usr/bin/env python # -*- coding: utf-8 -*- # Module: NetflixHttpRequestHandler # Created on: 07.03.2017 import BaseHTTPServer import json from types import FunctionType from urlparse import urlparse, parse_qs from resources.lib.KodiHelper import KodiHelper from r...
SAP/contextual-ai
setup.py
""" Setup """ import setuptools with open("README.md", "r", encoding='utf-8') as fh: long_description = fh.read() def get_version(): with open('version.txt') as ver_file: version_str = ver_file.readline().rstrip() return version_str setuptools.setup( name='contextual-ai', version=get_vers...
AnacondaRecipes/psycopg2-feedstock
recipe/fix_openssl_setup.py
# Perform the renaming of these things with open('setup.py', 'rb') as fo: content = fo.read() content = content.replace(b'ssleay32', b'libssl') content = content.replace(b'libeay32', b'libcrypto') with open('setup.py', 'wb') as fo: fo.write(content)
auchter/nifpga-python
nifpga/__init__.py
from .status import * from .statuscheckedlibrary import FunctionInfo, StatusCheckedLibrary from .nifpga import * from .session import Session from .bitfile import Bitfile
auchter/nifpga-python
nifpga/session.py
<filename>nifpga/session.py """ Session, a convenient wrapper around the low-level _NiFpga class. Copyright (c) 2017 National Instruments """ from .nifpga import (_SessionType, _IrqContextType, _NiFpga, DataType, OPEN_ATTRIBUTE_NO_RUN, RUN_ATTRIBUTE_WAIT_UNTIL_DONE, CLOSE_ATT...
auchter/nifpga-python
nifpga/statuscheckedlibrary.py
from .status import check_status import ctypes import ctypes.util StatusType = ctypes.c_int32 class FunctionInfo(object): def __init__(self, function, name, argument_names): """ A struct describing a function to be used in StatusCheckedFunctions. Args: function (str): the call...
auchter/nifpga-python
setup.py
<gh_stars>0 from setuptools import setup, find_packages import os # The VERSION file is codegned by the build. # setup.py needs to be in version control, but checking versions into that is problematic def get_version(): version = None script_dir = os.path.dirname(os.path.realpath(__file__)) script_dir = os...
auchter/nifpga-python
nifpga/nifpga.py
""" NiFpga, a thin wrapper around the FPGA Interface C API Copyright (c) 2015 National Instruments """ from .statuscheckedlibrary import (NamedArgtype, LibraryFunctionInfo, StatusCheckedLibrary, LibraryNotFoundErro...
auchter/nifpga-python
nifpga/status.py
""" An set of status exception classes to be used when an NiFpga function returns either a warning or error status. Use check_status() to raise an appropriate exception if necessary. Error and Warning exception class names are auto-generated from the strings in 'codeToString' in this file. For example, handle a fatal...
auchter/nifpga-python
nifpga/bitfile.py
import os import warnings from xml.etree.ElementTree import ElementTree from nifpga import DataType class Bitfile(object): """ Class that represents the contents of the .lvbitx file. Bitfile is a class that parses and contains the data from the XML based .lvbitx file. This class can be used to lookup re...
ulsdevteam/request_broker
process_request/helpers.py
<reponame>ulsdevteam/request_broker import re import inflect import shortuuid from request_broker import settings from asnake.utils import get_date_display, get_note_text, text_in_note, resolve_to_uri from ordered_set import OrderedSet CONFIDENCE_RATIO = 97 # Minimum confidence ratio to match against. OPEN_TEXT = ["...
ulsdevteam/request_broker
process_request/serializers.py
from rest_framework import serializers class LinkResolverSerializer(serializers.Serializer): ref_id = serializers.CharField()
ulsdevteam/request_broker
process_request/test_helpers.py
<filename>process_request/test_helpers.py import json import random import string from os.path import join from request_broker import settings FIXTURES_DIR = join(settings.BASE_DIR, "fixtures") def random_string(length=20): """Returns a random string of specified length.""" return "".join(random.choice(stri...
ulsdevteam/request_broker
process_request/views.py
<reponame>ulsdevteam/request_broker import csv from datetime import datetime from django.http import StreamingHttpResponse from django.shortcuts import redirect from request_broker import settings from asnake.aspace import ASpace from rest_framework.response import Response from rest_framework.views import APIView fr...
ulsdevteam/request_broker
process_request/migrations/0002_delete_machineuser.py
<filename>process_request/migrations/0002_delete_machineuser.py # Generated by Django 2.2.10 on 2020-08-30 23:44 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('process_request', '0001_initial'), ] operations = [ migrations.DeleteModel( ...
ulsdevteam/request_broker
request_broker/urls.py
"""request_broker URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Clas...
ulsdevteam/request_broker
process_request/apps.py
<filename>process_request/apps.py from django.apps import AppConfig class ProcessorConfig(AppConfig): name = 'process_request'
ulsdevteam/request_broker
process_request/models.py
from django.contrib.auth.models import AbstractUser class User(AbstractUser): archivist_group = [u"rac_archivists"] donor_group = [u"rac_donors"] researcher_group = [u"rac_researchers"] AbstractUser._meta.get_field("email").blank = False AbstractUser._meta.get_field("first_name").blank = False ...
ulsdevteam/request_broker
process_request/clients.py
<filename>process_request/clients.py<gh_stars>0 from request_broker import settings from requests import Session def http_meth_factory(meth): """Utility method for producing HTTP proxy methods. Urls are prefixed with the value of baseurl from the client's config. Arguments are passed unaltered to the mat...
zuzanaj/CASP-CAPRI-T70-tutorial
ana_scripts/cluster_fcc.py
#!/usr/bin/env python # -*- coding: UTF-8 -*- """ Asymmetric Taylor-Butina Disjoint Clustering Algorithm. Authors: <NAME> <NAME> <NAME> """ class Element(object): """Defines a 'clusterable' Element""" __slots__ = ['name', 'cluster', 'neighbors'] def __init__(self, name...
justinkwan1216/wave-to-128x128-classfication
train.py
<gh_stars>0 import keras from keras.layers import Activation, Dense, Dropout, Conv2D, \ Flatten, MaxPooling2D, GlobalMaxPooling2D, BatchNormalization from keras.models import Sequential from keras import optimizers import numpy as np import random import pickle import efficientnet.keras...
justinkwan1216/wave-to-128x128-classfication
sound.py
import keras from keras.layers import Activation, Dense, Dropout, Conv2D, \ Flatten, MaxPooling2D from keras.models import Sequential import librosa import librosa.display import numpy as np import pandas as pd import random import warnings warnings.filterwarnings('ignore') m...
ep12/qtile-telemetry-playground
identity.py
<reponame>ep12/qtile-telemetry-playground<filename>identity.py import re import os import sys import platform from pprint import pformat import hashlib class NoHash: def __init__(self, initial = None): self.hist = [] if initial is None else [initial] def update(self, value): self.hist.append(...
ep12/qtile-telemetry-playground
config_stats.py
import os import sys import ast import importlib from pprint import pprint import functools import astor cproperty = getattr(functools, 'cached_property', property) CONFIG_DIR = os.path.expanduser('~/.config/qtile') EXCLUDE_ATTRS = {'_attributes', '_fields', 'col_offset', 'end_col_offset', 'end_lineno', 'lineno'} ...
robogeekcanada/pybullet-tutorials
nao_get_link_names.py
<reponame>robogeekcanada/pybullet-tutorials import time import pybullet as p import pybullet_data from qibullet import NaoVirtual client = p.connect(p.GUI) p.setAdditionalSearchPath(pybullet_data.getDataPath()) p.loadURDF("plane.urdf") p.setRealTimeSimulation(1) p.setGravity(0, 0, -10) robot = NaoVirtual() robot....
robogeekcanada/pybullet-tutorials
nao_joints_control2.py
import time import pybullet as p import pybullet_data from qibullet import NaoVirtual client = p.connect(p.GUI) p.setAdditionalSearchPath(pybullet_data.getDataPath()) p.loadURDF("plane.urdf") p.setRealTimeSimulation(1) p.setGravity(0, 0, -10) robot = NaoVirtual() robot.loadRobot([0,0,0], [0,0,0,1]) time.sleep(2)...
robogeekcanada/pybullet-tutorials
nao_teleportation.py
<reponame>robogeekcanada/pybullet-tutorials<filename>nao_teleportation.py<gh_stars>0 import numpy as np import time #import matplotlib.pyplot as plt import pybullet as p from time import sleep import pybullet_data import time from datetime import datetime import cv2 from qibullet import SimulationManager from qibullet...
robogeekcanada/pybullet-tutorials
nao_motions.py
import numpy as np import os from pathlib import Path import time #import matplotlib.pyplot as plt import pybullet as p from time import sleep import pybullet_data import time from datetime import datetime import cv2 from qibullet import SimulationManager from qibullet import NaoVirtual from qibullet import Camera im...
robogeekcanada/pybullet-tutorials
nao_joints_control.py
<filename>nao_joints_control.py<gh_stars>0 import sys import time import pybullet as p from qibullet import SimulationManager from qibullet import PepperVirtual from qibullet import NaoVirtual from qibullet import RomeoVirtual simulation_manager = SimulationManager() client = simulation_manager.launchSimulation(gui=T...
robogeekcanada/pybullet-tutorials
nao_color_suits.py
import pybullet as p import pybullet_data import time import os from qibullet import NaoVirtual cwd = os.getcwd() os.chdir(cwd) client = p.connect(p.GUI) p.setAdditionalSearchPath(pybullet_data.getDataPath()) p.loadURDF("plane.urdf") p.setRealTimeSimulation(1) p.setGravity(0, 0, -10) robot1 = NaoVirtual() robot1....
robogeekcanada/pybullet-tutorials
nao_soccer_field.py
import pybullet as p import pybullet_data import time import math import os from pathlib import Path from qibullet import NaoVirtual client = p.connect(p.GUI) cwd = os.getcwd() data_folder = Path(cwd) field_folder = data_folder/"field" p.setAdditionalSearchPath(pybullet_data.getDataPath()) #p.loadURDF("plane.urd...
robogeekcanada/pybullet-tutorials
nao_player_label.py
<reponame>robogeekcanada/pybullet-tutorials import time import pybullet as p import pybullet_data from qibullet import NaoVirtual client = p.connect(p.GUI) p.setAdditionalSearchPath(pybullet_data.getDataPath()) p.loadURDF("plane.urdf") p.setRealTimeSimulation(1) p.setGravity(0, 0, -10) robot = NaoVirtual() robot....
marx-alex/Morphelia
morphelia/external/saphire.py
import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.collections as mcoll from matplotlib.ticker import MaxNLocator plt.style.use('seaborn-darkgrid') class BaseTraj: def __init__(self, model, X): self.model = model assert len(X.shape) == 2, f"X should be 2...
marx-alex/Morphelia
morphelia/plotting/pca_variance_ratio.py
<reponame>marx-alex/Morphelia # import internal libraries import os # import external libraries import matplotlib.pyplot as plt import seaborn as sns import numpy as np def pca_variance_ratio(adata, n_pcas=100, save=False, **kwargs): """Plots cumulative percentage variance explained by each principal component. ...
marx-alex/Morphelia
morphelia/features/outlier.py
import numpy as np import warnings def drop_outlier(adata, thresh=15, axis=0, drop=True, verbose=False): """Drop all features or cells with a min or max absolute value that is greater than a threshold. Expects normally distributed data. ...
marx-alex/Morphelia
morphelia/features/correlation.py
<gh_stars>0 import numpy as np from morphelia.plotting import plot_corr_matrix from morphelia.tools.utils import get_subsample def drop_highly_correlated(adata, thresh=0.95, show=False, save=False, subsample=Fa...
marx-alex/Morphelia
morphelia/plotting/cell_annotation.py
import matplotlib.pyplot as plt import matplotlib.patches as mpatches from skimage import io import numpy as np import pandas as pd from sklearn.preprocessing import OrdinalEncoder import os def annotate_cells(adata, ann_var, channel1_path, channel2_path=None, channel3_path=None...
marx-alex/Morphelia
morphelia/eval/distance.py
<filename>morphelia/eval/distance.py import pandas as pd import numpy as np from scipy.spatial.distance import pdist, squareform import seaborn as sns import matplotlib.pyplot as plt import matplotlib import os from dtaidistance import dtw_ndim, dtw from morphelia.time_series import HMMSimilarity from morphelia.tools....
marx-alex/Morphelia
morphelia/preprocessing/normalize.py
import numpy as np from sklearn.preprocessing import MinMaxScaler, StandardScaler, RobustScaler from morphelia.tools import RobustMAD from morphelia.preprocessing import drop_nan as drop_nan_feats def normalize(adata, by=("BatchNumber", "PlateNumber"), method="standard", pop_...
marx-alex/Morphelia
morphelia/cli/StoreAD.py
import argparse import yaml import os import re import anndata as ad from morphelia.tools.load_project import MorphData from morphelia.preprocessing import aggregate, subsample def run(inp, agg_name, ss_name, files, treatment, out, store): """Read and write CellProfiler output.""" if not os.path.exists(inp)...
marx-alex/Morphelia
morphelia/features/agglomeration.py
<filename>morphelia/features/agglomeration.py # external libraries from sklearn.cluster import FeatureAgglomeration from sklearn.metrics import silhouette_score import numpy as np import seaborn as sns import matplotlib.pyplot as plt from matplotlib.patches import Patch import anndata as ad import pandas as pd from tqd...
marx-alex/Morphelia
morphelia/tools/transformer.py
import numpy as np from sklearn.base import BaseEstimator, TransformerMixin from scipy.stats import median_abs_deviation as mad class RobustMAD(BaseEstimator, TransformerMixin): """ Class to perform a "Robust" normalization with respect to median and mad scaled = (x - median) / mad Class is adopt...
marx-alex/Morphelia
morphelia/features/variance.py
import numpy as np from tqdm import tqdm from scipy.stats import median_abs_deviation as mad def drop_near_zero_variance(adata, freq_thresh=0.05, unique_thresh=0.01, drop=True, verbose=False): """Drop f...
marx-alex/Morphelia
morphelia/preprocessing/positional_corr.py
<filename>morphelia/preprocessing/positional_corr.py import numpy as np from tqdm import tqdm from scipy.stats import median_absolute_deviation as mad from morphelia.tools import MedianPolish def correct_plate_eff(adata, row_var="Metadata_Row", col_var="Metadata_Col", ...
marx-alex/Morphelia
morphelia/preprocessing/__init__.py
<gh_stars>0 from .cellcycle import assign_cc from .debris import filter_debris from .basic import drop_nan, filter_thresh, filter_thresh, drop_duplicates, drop_invariant from .normalize import normalize from .pseudostitch import pseudostitch from .aggregate import aggregate, aggregate_chunks from .subsample import subs...
marx-alex/Morphelia
morphelia/plotting/feat_plot.py
# import external libraries import matplotlib.pyplot as plt import seaborn as sns __all__ = ["boxplot", "violin", "barplot"] def boxplot(adata, x, y, hue=None, y_label=None, x_label=None, **kwargs): """Plot one or more variables of single or aggregated cells for different time points. Args: adat...
marx-alex/Morphelia
morphelia/scripts/correct_bleach.py
<filename>morphelia/scripts/correct_bleach.py import argparse import os import logging import anndata as ad from morphelia.preprocessing import correct_bleaching logging.basicConfig(level=logging.INFO) logging.getLogger('numexpr').setLevel(logging.WARNING) def main(src, fname, channels): """Read and write CellP...
marx-alex/Morphelia
morphelia/preprocessing/debris.py
import numpy as np import matplotlib.pyplot as plt import seaborn as sns from skimage.filters import threshold_minimum import os def filter_debris(adata, nucl_area='Primarieswithoutborder_AreaShape_Area', cell_area='Cells_AreaShape_Area', max_quot=20, n=5000, show...
marx-alex/Morphelia
morphelia/plotting/eval.py
import os import numpy as np import seaborn as sns import matplotlib.pyplot as plt def plot_eval(adata, whisker_size=0.005, linewidth=4, vmin=0.5, vmax=1., c_repro='#C84B31', c_effect='#346751', show_outlier=False, ...
marx-alex/Morphelia
morphelia/tools/samples.py
<reponame>marx-alex/Morphelia # import internal libraries import os import re # import external libraries from tqdm import tqdm import numpy as np import pandas as pd from skimage import io from skimage import color from skimage import exposure from skimage.util import img_as_ubyte, img_as_float def group_samples(ad...
marx-alex/Morphelia
morphelia/preprocessing/basic.py
<reponame>marx-alex/Morphelia<filename>morphelia/preprocessing/basic.py # import external libraries import numpy as np def drop_nan(adata, drop_inf=True, drop_dtype_max=True, verbose=False): """Drop variables that contain invalid variables. Args: adata (anndata....
marx-alex/Morphelia
morphelia/tools/utils.py
import warnings import scanpy as sc import numpy as np from sklearn.preprocessing import LabelEncoder def choose_representation(adata, rep=None, n_pcs=None): """Get representation of multivariate data. Args: adata (anndata.AnnData): Multidimensional...
marx-alex/Morphelia
morphelia/features/deepfate.py
<reponame>marx-alex/Morphelia import torch from torch import nn from torch.utils.data import Dataset, DataLoader import torch.nn.functional as F from sklearn.model_selection import train_test_split, GroupShuffleSplit import pytorch_lightning as pl from typing import Optional import logging import numpy as np from mor...
marx-alex/Morphelia
morphelia/eval/__init__.py
from .distance import dist_matrix, dtw_dist_matrix, hmm_sim_matrix from .evaluate import reproducibility, effect, repro_effect, select_concentration
marx-alex/Morphelia
morphelia/features/__init__.py
<gh_stars>0 from .agglomeration import feature_agglo from .correlation import drop_highly_correlated from .variance import drop_low_variance, drop_low_cv, drop_near_zero_variance from .noise import drop_noise from .outlier import drop_outlier from .model_select import svm_rfe, lmm_feat_select from .deepfate import Deep...
marx-alex/Morphelia
morphelia/preprocessing/pseudostitch.py
<reponame>marx-alex/Morphelia # external libraries import numpy as np # internal libraries import warnings def pseudostitch(md, update_loc=False, tile_grid=(5, 5), img_size=(2048, 2048), img_overlap=0.2, trow_var="Metadata_TileRow", tcol_var="Metadata_TileCol", ...
marx-alex/Morphelia
morphelia/preprocessing/aggregate.py
<reponame>marx-alex/Morphelia # import internal libraries from collections import defaultdict # import external libraries import numpy as np import pandas as pd import anndata as ad from tqdm import tqdm def aggregate(adata, by=("BatchNumber", "PlateNumber", "Metadata_Well"), method='medi...
marx-alex/Morphelia
morphelia/tools/load_project.py
# import internal libraries import re import os import pathlib import warnings # import external libraries import pandas as pd import anndata as ad __all__ = ["MorphData", "LoadPlate"] class LoadPlate: def __init__(self, path, filenames=("Cells", "Primarieswithoutborder", "Cytoplasm"...
marx-alex/Morphelia
morphelia/cli/Embedding.py
import argparse import yaml import os import anndata as ad import scanpy as sc from morphelia.plotting import pca_variance_ratio def run(inp): """Calculate embeddings for morphological data.""" # where to save figures figdir = os.path.join(inp['output'], './figures/') # scanpy settings sc.setting...
marx-alex/Morphelia
morphelia/time_series/hmm_dist.py
import numpy as np from hmmlearn import hmm import warnings def bic(X, k, likelihood_func): """Bayesian information criterion. Args: X (np.ndarray): Data to fit on. k (int): Free parameters. likelihood_func (function): Likelihood function that takes X as input. """ return k * ...
marx-alex/Morphelia
morphelia/plotting/trace.py
<gh_stars>0 # import internal libraries import math import os # import external libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import networkx as nx from sklearn.decomposition import PCA def show_trace(adata, fields, dim='2d', ...
marx-alex/Morphelia
setup.py
from setuptools import find_packages, setup from pathlib import Path setup( name='morphelia', packages=find_packages(include=['morphelia', 'morphelia.*']), version='0.0.2', description='Exploratory data analysis for image-based morphological profiling.', author='<NAME>', license='MIT Licence', ...
marx-alex/Morphelia
morphelia/__init__.py
<gh_stars>0 # -*- coding: UTF-8 -*- """ morphelia ~~~~~~~~~~~~ Exploratory data analysis for image-based morphological profiling. :author: <NAME> :copyright: Copyright 2021 <NAME> and others. :license: MIT License, see LICENSE for details. """ from . import external as ext from . import preprocessing as pp from . impor...
marx-alex/Morphelia
morphelia/eval/evaluate.py
import numpy as np import pandas as pd from morphelia.eval import dist_matrix from scipy.stats import norm def repro_effect(adata, group_var="Metadata_Treatment", other_group_vars=None, method='pearson', control_id='ctrl', use_rep=No...
marx-alex/Morphelia
morphelia/cli/FeatureAgglo.py
<gh_stars>0 import argparse import yaml import os import anndata as ad from morphelia.features import feature_agglo def run(inp): """Preprocess morphological annotated data.""" # where to save figures figdir = os.path.join(inp['output'], './figures/') # load data inp_data = os.path.join(inp['outp...
marx-alex/Morphelia
morphelia/plotting/emb_traj.py
from collections import defaultdict import numpy as np import pandas as pd import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.collections as mcoll def plot_trajectory(adata, rep=None, time_var='Metadata_Time', treat_var='Metadata_Trea...
marx-alex/Morphelia
morphelia/clustering/__init__.py
<reponame>marx-alex/Morphelia<gh_stars>0 from .hierarchical import linkage_tree from .fate_cluster import FateCluster
marx-alex/Morphelia
morphelia/time_series/mm.py
<filename>morphelia/time_series/mm.py import scipy as sc from sklearn.metrics.pairwise import euclidean_distances import numpy as np class StateTransitionModel: """ Model for state transitions. """ def __init__(self, adata, state_var='leiden', time_va...
marx-alex/Morphelia
morphelia/time_series/temporal.py
<gh_stars>0 # import internal libraries import math import os # import external libraries import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import anndata as ad def temporal_reduction(md, trace_var="Metadata_Trace_Parent", time_var="Metadata_Time", sh...
marx-alex/Morphelia
morphelia/preprocessing/subsample.py
# import internal libraries from collections import defaultdict # import external libraries import numpy as np import pandas as pd import anndata as ad def subsample(adata, perc=0.1, by=("BatchNumber", "PlateNumber", "Metadata_Well"), seed=0): """Gives a subsample of the data by selecting objects f...