filename
stringlengths 13
19
| text
stringlengths 134
1.04M
|
---|---|
the-stack_0_8472 | """Customized dataloader for general video classification tasks."""
import os
import warnings
import numpy as np
try:
from decord import VideoReader, cpu
except ImportError:
VideoReader = None
cpu = None
import torch
from torch.utils.data import Dataset
from ..transforms.videotransforms import video_transforms, volume_transforms
from .multigrid_helper import multiGridHelper, MultiGridBatchSampler
__all__ = ['VideoClsDataset', 'build_dataloader', 'build_dataloader_test']
class VideoClsDataset(Dataset):
"""Load your own video classification dataset."""
def __init__(self, anno_path, data_path, mode='train', clip_len=8,
frame_sample_rate=2, crop_size=224, short_side_size=256,
new_height=256, new_width=340, keep_aspect_ratio=False,
num_segment=1, num_crop=1, test_num_segment=10, test_num_crop=3,
use_multigrid=False):
self.anno_path = anno_path
self.data_path = data_path
self.mode = mode
self.clip_len = clip_len
self.frame_sample_rate = frame_sample_rate
self.crop_size = crop_size
self.short_side_size = short_side_size
self.new_height = new_height
self.new_width = new_width
self.keep_aspect_ratio = keep_aspect_ratio
self.num_segment = num_segment
self.test_num_segment = test_num_segment
self.num_crop = num_crop
self.test_num_crop = test_num_crop
self.use_multigrid = use_multigrid and (mode == 'train')
if VideoReader is None:
raise ImportError("Unable to import `decord` which is required to read videos.")
import pandas as pd
cleaned = pd.read_csv(self.anno_path, header=None, delimiter=' ')
self.dataset_samples = list(cleaned.values[:, 0])
self.label_array = list(cleaned.values[:, 2])
if (mode == 'train'):
if self.use_multigrid:
self.mg_helper = multiGridHelper()
self.data_transform = []
for alpha in range(self.mg_helper.mod_long):
tmp = []
for beta in range(self.mg_helper.mod_short):
info = self.mg_helper.get_resize(alpha, beta)
scale_s = info[1]
tmp.append(video_transforms.Compose([
video_transforms.Resize(int(self.short_side_size / scale_s),
interpolation='bilinear'),
# TODO: multiscale corner cropping
video_transforms.RandomResize(ratio=(1, 1.25),
interpolation='bilinear'),
video_transforms.RandomCrop(size=(int(self.crop_size / scale_s),
int(self.crop_size / scale_s)))]))
self.data_transform.append(tmp)
else:
self.data_transform = video_transforms.Compose([
video_transforms.Resize(int(self.short_side_size),
interpolation='bilinear'),
video_transforms.RandomResize(ratio=(1, 1.25),
interpolation='bilinear'),
video_transforms.RandomCrop(size=(int(self.crop_size),
int(self.crop_size)))])
self.data_transform_after = video_transforms.Compose([
video_transforms.RandomHorizontalFlip(),
volume_transforms.ClipToTensor(),
video_transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
])
elif (mode == 'validation'):
self.data_transform = video_transforms.Compose([
video_transforms.Resize(self.short_side_size, interpolation='bilinear'),
video_transforms.CenterCrop(size=(self.crop_size, self.crop_size)),
volume_transforms.ClipToTensor(),
video_transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
])
elif mode == 'test':
self.data_resize = video_transforms.Compose([
video_transforms.Resize(size=(short_side_size), interpolation='bilinear')
])
self.data_transform = video_transforms.Compose([
volume_transforms.ClipToTensor(),
video_transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
])
self.test_seg = []
self.test_dataset = []
self.test_label_array = []
for ck in range(self.test_num_segment):
for cp in range(self.test_num_crop):
for idx in range(len(self.label_array)):
sample_label = self.label_array[idx]
self.test_label_array.append(sample_label)
self.test_dataset.append(self.dataset_samples[idx])
self.test_seg.append((ck, cp))
def __getitem__(self, index):
if self.mode == 'train':
if self.use_multigrid is True:
index, alpha, beta = index
info = self.mg_helper.get_resize(alpha, beta)
scale_t = info[0]
data_transform_func = self.data_transform[alpha][beta]
else:
scale_t = 1
data_transform_func = self.data_transform
sample = self.dataset_samples[index]
buffer = self.loadvideo_decord(sample, sample_rate_scale=scale_t)
if len(buffer) == 0:
while len(buffer) == 0:
warnings.warn("video {} not correctly loaded during training".format(sample))
index = np.random.randint(self.__len__())
sample = self.dataset_samples[index]
buffer = self.loadvideo_decord(sample, sample_rate_scale=scale_t)
buffer = data_transform_func(buffer)
buffer = self.data_transform_after(buffer)
return buffer, self.label_array[index], sample.split("/")[-1].split(".")[0]
elif self.mode == 'validation':
sample = self.dataset_samples[index]
buffer = self.loadvideo_decord(sample)
if len(buffer) == 0:
while len(buffer) == 0:
warnings.warn("video {} not correctly loaded during validation".format(sample))
index = np.random.randint(self.__len__())
sample = self.dataset_samples[index]
buffer = self.loadvideo_decord(sample)
buffer = self.data_transform(buffer)
return buffer, self.label_array[index], sample.split("/")[-1].split(".")[0]
elif self.mode == 'test':
sample = self.test_dataset[index]
chunk_nb, split_nb = self.test_seg[index]
buffer = self.loadvideo_decord(sample)
while len(buffer) == 0:
warnings.warn("video {}, temporal {}, spatial {} not found during testing".format(\
str(self.test_dataset[index]), chunk_nb, split_nb))
index = np.random.randint(self.__len__())
sample = self.test_dataset[index]
chunk_nb, split_nb = self.test_seg[index]
buffer = self.loadvideo_decord(sample)
buffer = self.data_resize(buffer)
if isinstance(buffer, list):
buffer = np.stack(buffer, 0)
spatial_step = 1.0 * (max(buffer.shape[1], buffer.shape[2]) - self.short_side_size) \
/ (self.test_num_crop - 1)
temporal_step = max(1.0 * (buffer.shape[0] - self.clip_len) \
/ (self.test_num_segment - 1), 0)
temporal_start = int(chunk_nb * temporal_step)
spatial_start = int(split_nb * spatial_step)
if buffer.shape[1] >= buffer.shape[2]:
buffer = buffer[temporal_start:temporal_start + self.clip_len, \
spatial_start:spatial_start + self.short_side_size, :, :]
else:
buffer = buffer[temporal_start:temporal_start + self.clip_len, \
:, spatial_start:spatial_start + self.short_side_size, :]
buffer = self.data_transform(buffer)
return buffer, self.test_label_array[index], sample.split("/")[-1].split(".")[0], \
chunk_nb, split_nb
else:
raise NameError('mode {} unkown'.format(self.mode))
def loadvideo_decord(self, sample, sample_rate_scale=1):
"""Load video content using Decord"""
# pylint: disable=line-too-long, bare-except, unnecessary-comprehension
fname = self.data_path + sample
if not (os.path.exists(fname)):
return []
# avoid hanging issue
if os.path.getsize(fname) < 1 * 1024:
print('SKIP: ', fname, " - ", os.path.getsize(fname))
return []
try:
if self.keep_aspect_ratio:
vr = VideoReader(fname, num_threads=1, ctx=cpu(0))
else:
vr = VideoReader(fname, width=self.new_width, height=self.new_height,
num_threads=1, ctx=cpu(0))
except:
print("video cannot be loaded by decord: ", fname)
return []
if self.mode == 'test':
all_index = [x for x in range(0, len(vr), self.frame_sample_rate)]
while len(all_index) < self.clip_len:
all_index.append(all_index[-1])
vr.seek(0)
buffer = vr.get_batch(all_index).asnumpy()
return buffer
# handle temporal segments
converted_len = int(self.clip_len * self.frame_sample_rate)
seg_len = len(vr) // self.num_segment
all_index = []
for i in range(self.num_segment):
if seg_len <= converted_len:
index = np.linspace(0, seg_len, num=seg_len // self.frame_sample_rate)
index = np.concatenate((index, np.ones(self.clip_len - seg_len // self.frame_sample_rate) * seg_len))
index = np.clip(index, 0, seg_len - 1).astype(np.int64)
else:
end_idx = np.random.randint(converted_len, seg_len)
str_idx = end_idx - converted_len
index = np.linspace(str_idx, end_idx, num=self.clip_len)
index = np.clip(index, str_idx, end_idx - 1).astype(np.int64)
index = index + i*seg_len
all_index.extend(list(index))
all_index = all_index[::int(sample_rate_scale)]
vr.seek(0)
buffer = vr.get_batch(all_index).asnumpy()
return buffer
def __len__(self):
if self.mode != 'test':
return len(self.dataset_samples)
else:
return len(self.test_dataset)
def build_dataloader(cfg):
"""Build dataloader for training/validation"""
train_dataset = VideoClsDataset(anno_path=cfg.CONFIG.DATA.TRAIN_ANNO_PATH,
data_path=cfg.CONFIG.DATA.TRAIN_DATA_PATH,
mode='train',
use_multigrid=cfg.CONFIG.TRAIN.MULTIGRID.USE_SHORT_CYCLE \
or cfg.CONFIG.TRAIN.MULTIGRID.USE_LONG_CYCLE,
clip_len=cfg.CONFIG.DATA.CLIP_LEN,
frame_sample_rate=cfg.CONFIG.DATA.FRAME_RATE,
num_segment=cfg.CONFIG.DATA.NUM_SEGMENT,
num_crop=cfg.CONFIG.DATA.NUM_CROP,
keep_aspect_ratio=cfg.CONFIG.DATA.KEEP_ASPECT_RATIO,
crop_size=cfg.CONFIG.DATA.CROP_SIZE,
short_side_size=cfg.CONFIG.DATA.SHORT_SIDE_SIZE,
new_height=cfg.CONFIG.DATA.NEW_HEIGHT,
new_width=cfg.CONFIG.DATA.NEW_WIDTH)
val_dataset = VideoClsDataset(anno_path=cfg.CONFIG.DATA.VAL_ANNO_PATH,
data_path=cfg.CONFIG.DATA.VAL_DATA_PATH,
mode='validation',
use_multigrid=False,
clip_len=cfg.CONFIG.DATA.CLIP_LEN,
frame_sample_rate=cfg.CONFIG.DATA.FRAME_RATE,
num_segment=cfg.CONFIG.DATA.NUM_SEGMENT,
num_crop=cfg.CONFIG.DATA.NUM_CROP,
keep_aspect_ratio=cfg.CONFIG.DATA.KEEP_ASPECT_RATIO,
crop_size=cfg.CONFIG.DATA.CROP_SIZE,
short_side_size=cfg.CONFIG.DATA.SHORT_SIDE_SIZE,
new_height=cfg.CONFIG.DATA.NEW_HEIGHT,
new_width=cfg.CONFIG.DATA.NEW_WIDTH)
if cfg.DDP_CONFIG.DISTRIBUTED:
train_sampler = torch.utils.data.distributed.DistributedSampler(train_dataset)
val_sampler = torch.utils.data.distributed.DistributedSampler(val_dataset)
else:
train_sampler = None
val_sampler = None
mg_sampler = None
if cfg.CONFIG.TRAIN.MULTIGRID.USE_LONG_CYCLE or cfg.CONFIG.TRAIN.MULTIGRID.USE_SHORT_CYCLE:
mg_sampler = MultiGridBatchSampler(train_sampler, batch_size=cfg.CONFIG.TRAIN.BATCH_SIZE,
drop_last=True,
use_long=cfg.CONFIG.TRAIN.MULTIGRID.USE_LONG_CYCLE,
use_short=cfg.CONFIG.TRAIN.MULTIGRID.USE_SHORT_CYCLE)
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=1, shuffle=False,
num_workers=9, pin_memory=True,
batch_sampler=mg_sampler)
else:
train_loader = torch.utils.data.DataLoader(
train_dataset, batch_size=cfg.CONFIG.TRAIN.BATCH_SIZE, shuffle=(train_sampler is None),
num_workers=9, sampler=train_sampler, pin_memory=True)
val_loader = torch.utils.data.DataLoader(
val_dataset, batch_size=cfg.CONFIG.VAL.BATCH_SIZE, shuffle=(val_sampler is None),
num_workers=9, sampler=val_sampler, pin_memory=True)
return train_loader, val_loader, train_sampler, val_sampler, mg_sampler
def build_dataloader_test(cfg):
"""Build dataloader for testing"""
test_dataset = VideoClsDataset(anno_path=cfg.CONFIG.DATA.VAL_ANNO_PATH,
data_path=cfg.CONFIG.DATA.VAL_DATA_PATH,
mode='test',
clip_len=cfg.CONFIG.DATA.CLIP_LEN,
frame_sample_rate=cfg.CONFIG.DATA.FRAME_RATE,
test_num_segment=cfg.CONFIG.DATA.TEST_NUM_SEGMENT,
test_num_crop=cfg.CONFIG.DATA.TEST_NUM_CROP,
keep_aspect_ratio=cfg.CONFIG.DATA.KEEP_ASPECT_RATIO,
crop_size=cfg.CONFIG.DATA.CROP_SIZE,
short_side_size=cfg.CONFIG.DATA.SHORT_SIDE_SIZE,
new_height=cfg.CONFIG.DATA.NEW_HEIGHT,
new_width=cfg.CONFIG.DATA.NEW_WIDTH)
if cfg.DDP_CONFIG.DISTRIBUTED:
test_sampler = torch.utils.data.distributed.DistributedSampler(test_dataset)
else:
test_sampler = None
test_loader = torch.utils.data.DataLoader(
test_dataset, batch_size=cfg.CONFIG.VAL.BATCH_SIZE, shuffle=(test_sampler is None),
num_workers=9, sampler=test_sampler, pin_memory=True)
return test_loader
|
the-stack_0_8474 | # Copyright 2014 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
"""Grab bag file for transaction."""
import logging
from google.appengine.api import datastore_errors
from google.appengine.ext import ndb
from google.appengine.ext.ndb import tasklets
from google.appengine.runtime import apiproxy_errors
__all__ = [
'CommitError',
'transaction',
'transaction_async',
'transactional_async',
'transactional',
'transactional_tasklet',
]
class CommitError(Exception):
"""A transaction probably failed but it may or may not have occurred.
The caller may want to run a second transaction to verify if the previous one
succeeded.
"""
@ndb.tasklet
def transaction_async(callback, **ctx_options):
"""Converts all sorts of random exceptions into CommitError.
Arguments:
callback: function to run in the transaction. See
https://cloud.google.com/appengine/docs/python/ndb/functions for more
details.
Sets retries default value to 1 instead 3 (!)
"""
ctx_options.setdefault('retries', 1)
try:
result = yield ndb.transaction_async(callback, **ctx_options)
raise ndb.Return(result)
except (
datastore_errors.InternalError,
datastore_errors.Timeout,
datastore_errors.TransactionFailedError) as e:
# https://cloud.google.com/appengine/docs/python/datastore/transactions
# states the result is ambiguous, it could have succeeded.
logging.info('Transaction likely failed: %s', e)
raise CommitError(e)
except (
apiproxy_errors.CancelledError,
datastore_errors.BadRequestError,
RuntimeError) as e:
logging.info('Transaction failure: %s', e.__class__.__name__)
raise CommitError(e)
def transaction(callback, **ctx_options):
"""Synchronous version of transaction_async()."""
future = transaction_async(callback, **ctx_options)
return future.get_result()
@ndb.utils.decorator
def transactional_async(func, args, kwds, **ctx_options):
"""The async version of @txn.transactional."""
if args or kwds:
return transaction_async(lambda: func(*args, **kwds), **ctx_options)
return transaction_async(func, **ctx_options)
@ndb.utils.decorator
def transactional(func, args, kwds, **ctx_options):
"""Decorator that wraps a function with txn.transaction."""
return transactional_async.wrapped_decorator(
func, args, kwds, **ctx_options).get_result()
@ndb.utils.decorator
def transactional_tasklet(func, args, kwds, **options):
"""The tasklet version of @txn.transactional_async."""
func = tasklets.tasklet(func)
return transactional_async.wrapped_decorator(func, args, kwds, **options)
|
the-stack_0_8476 | # -*- coding: utf-8 -*-
# vim: ft=python
"""
tests.unit.test_lfulib
"""
from __future__ import absolute_import
# Import 3rd party libs.
import pytest
# Import from local project.
from lfucache.exceptions import InvalidItemException
from lfucache.lfulib import LFUCache
# Import test scaffolding.
from tests.unit.fixtures.all import (
FREQUENCY,
NOT_FOUND,
)
# Mark everything here.
pytestmark = pytest.mark.unit
def test_get():
"""
Test - Use get to return the expected values.
"""
cache = LFUCache(2)
assert cache.get(1) == NOT_FOUND
cache.put(1, 1)
cache.put(2, 2)
# Increment the count for 1, moving 2 to least frequently used.
assert cache.get(1) == 1
cache.put(3, 3)
assert cache.get(2) == NOT_FOUND
assert cache.get(3) == 3
cache.put(4, 4)
assert cache.get(1) == NOT_FOUND
assert cache.get(3) == 3
assert cache.get(4) == 4
def test_put_failed():
"""
Test - Use put to check the expected functionality.
"""
cache = LFUCache(1)
with pytest.raises(InvalidItemException):
cache.put('invalid key', 1)
with pytest.raises(InvalidItemException):
cache.put(1, 'invalid value')
with pytest.raises(InvalidItemException):
cache.put(-1, -1)
def test_peek():
"""
Test - Check the content without incrementing the counter.
"""
cache = LFUCache(2)
cache.put(1, 1)
cache.put(2, 2)
_ = cache.get(1)
_ = cache.peek(1)
assert cache.peek(1) == (1, 2)
def test_get_frequency():
"""
Test - Check the frequency of .
"""
cache = LFUCache(3)
cache.put(1, 1)
cache.put(2, 2)
cache.put(3, 3)
_ = cache.get(1)
assert cache.get_frequency() == FREQUENCY
|
the-stack_0_8481 | # Copyright (c) 2014 EMC Corporation.
# 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 required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
FC Drivers for EMC VNX and VMAX arrays based on SMI-S.
"""
from cinder import context
from cinder.openstack.common import log as logging
from cinder.volume import driver
from cinder.volume.drivers.emc import emc_smis_common
LOG = logging.getLogger(__name__)
class EMCSMISFCDriver(driver.FibreChannelDriver):
"""EMC FC Drivers for VMAX and VNX using SMI-S.
Version history:
1.0.0 - Initial driver
1.1.0 - Multiple pools and thick/thin provisioning,
performance enhancement.
"""
VERSION = "1.1.0"
def __init__(self, *args, **kwargs):
super(EMCSMISFCDriver, self).__init__(*args, **kwargs)
self.common = emc_smis_common.EMCSMISCommon(
'FC',
configuration=self.configuration)
def check_for_setup_error(self):
pass
def create_volume(self, volume):
"""Creates a EMC(VMAX/VNX) volume."""
volpath = self.common.create_volume(volume)
model_update = {}
volume['provider_location'] = str(volpath)
model_update['provider_location'] = volume['provider_location']
return model_update
def create_volume_from_snapshot(self, volume, snapshot):
"""Creates a volume from a snapshot."""
volpath = self.common.create_volume_from_snapshot(volume, snapshot)
model_update = {}
volume['provider_location'] = str(volpath)
model_update['provider_location'] = volume['provider_location']
return model_update
def create_cloned_volume(self, volume, src_vref):
"""Creates a cloned volume."""
volpath = self.common.create_cloned_volume(volume, src_vref)
model_update = {}
volume['provider_location'] = str(volpath)
model_update['provider_location'] = volume['provider_location']
return model_update
def delete_volume(self, volume):
"""Deletes an EMC volume."""
self.common.delete_volume(volume)
def create_snapshot(self, snapshot):
"""Creates a snapshot."""
ctxt = context.get_admin_context()
volumename = snapshot['volume_name']
index = volumename.index('-')
volumeid = volumename[index + 1:]
volume = self.db.volume_get(ctxt, volumeid)
volpath = self.common.create_snapshot(snapshot, volume)
model_update = {}
snapshot['provider_location'] = str(volpath)
model_update['provider_location'] = snapshot['provider_location']
return model_update
def delete_snapshot(self, snapshot):
"""Deletes a snapshot."""
ctxt = context.get_admin_context()
volumename = snapshot['volume_name']
index = volumename.index('-')
volumeid = volumename[index + 1:]
volume = self.db.volume_get(ctxt, volumeid)
self.common.delete_snapshot(snapshot, volume)
def ensure_export(self, context, volume):
"""Driver entry point to get the export info for an existing volume."""
pass
def create_export(self, context, volume):
"""Driver entry point to get the export info for a new volume."""
pass
def remove_export(self, context, volume):
"""Driver entry point to remove an export for a volume."""
pass
def check_for_export(self, context, volume_id):
"""Make sure volume is exported."""
pass
def initialize_connection(self, volume, connector):
"""Initializes the connection and returns connection info.
Assign any created volume to a compute node/host so that it can be
used from that host.
The driver returns a driver_volume_type of 'fibre_channel'.
The target_wwn can be a single entry or a list of wwns that
correspond to the list of remote wwn(s) that will export the volume.
Example return values:
{
'driver_volume_type': 'fibre_channel'
'data': {
'target_discovered': True,
'target_lun': 1,
'target_wwn': '1234567890123',
}
}
or
{
'driver_volume_type': 'fibre_channel'
'data': {
'target_discovered': True,
'target_lun': 1,
'target_wwn': ['1234567890123', '0987654321321'],
}
}
"""
device_info = self.common.initialize_connection(volume,
connector)
device_number = device_info['hostlunid']
storage_system = device_info['storagesystem']
target_wwns, init_targ_map = self._build_initiator_target_map(
storage_system, connector)
data = {'driver_volume_type': 'fibre_channel',
'data': {'target_lun': device_number,
'target_discovered': True,
'target_wwn': target_wwns,
'initiator_target_map': init_targ_map}}
LOG.debug(_('Return FC data: %(data)s.')
% {'data': data})
return data
def terminate_connection(self, volume, connector, **kwargs):
"""Disallow connection from connector."""
self.common.terminate_connection(volume, connector)
loc = volume['provider_location']
name = eval(loc)
storage_system = name['keybindings']['SystemName']
target_wwns, init_targ_map = self._build_initiator_target_map(
storage_system, connector)
data = {'driver_volume_type': 'fibre_channel',
'data': {'target_wwn': target_wwns,
'initiator_target_map': init_targ_map}}
LOG.debug(_('Return FC data: %(data)s.')
% {'data': data})
return data
def _build_initiator_target_map(self, storage_system, connector):
"""Build the target_wwns and the initiator target map."""
target_wwns = self.common.get_target_wwns(storage_system, connector)
initiator_wwns = connector['wwpns']
init_targ_map = {}
for initiator in initiator_wwns:
init_targ_map[initiator] = target_wwns
return target_wwns, init_targ_map
def extend_volume(self, volume, new_size):
"""Extend an existing volume."""
self.common.extend_volume(volume, new_size)
def get_volume_stats(self, refresh=False):
"""Get volume stats.
If 'refresh' is True, run update the stats first.
"""
if refresh:
self.update_volume_stats()
return self._stats
def update_volume_stats(self):
"""Retrieve stats info from volume group."""
LOG.debug(_("Updating volume stats"))
data = self.common.update_volume_stats()
backend_name = self.configuration.safe_get('volume_backend_name')
data['volume_backend_name'] = backend_name or 'EMCSMISFCDriver'
data['storage_protocol'] = 'FC'
data['driver_version'] = self.VERSION
self._stats = data
|
the-stack_0_8484 | from database.models import *
from database.queries import hasKVPair
from IPython import embed
import numpy as np
from database.imports import printD,ploc,datetime,timedelta,_tdb,FlushError,IntegrityError
#_tdb.tdbOff()
#FIXME TODO, make all these things use queries instead of generating you nub
#and failover to create if absent
#creation order
#order=(Person,Project,Experiment,SlicePrep,Repository,RepoPath,DOB,Mouse,Sire,Dam,MatingRecord,Litter) #TODO
#order=(t_people,t_dob)# you get the idea... maybe make a tree in a dict or something?
class TEST:
def __init__(self,session,num=None,autocommit=True,Thing=None):
self.Thing=Thing
self.num=num
self.session=session
self.records=[] #this is the output
self.setup()
self.make_all()
if autocommit:
self.commit()
self.test_delete()
if autocommit:
self.commit()
self.tests()
def make_date(self):
from datetime import date,timedelta
num=self.num
seed=date.today()
days=np.random.randint(365*15,365*100,num) #historical dates not supported in the test
deltas=[timedelta(days=int(d)) for d in days] #fortunately timedelta defaults to days so I dont have to read the doccumentation for map
return [seed - delta for delta in deltas]
def make_datetime(self,num=None,years=5):
from datetime import datetime,timedelta
if not num:
num=self.num
seed=datetime.now()
days=np.random.randint(0,365*years,num) #historical dates not supported in the test
hours=np.random.randint(0,12,num) #historical dates not supported in the test
deltas=[timedelta(days=int(d),hours=int(h)) for d,h in zip(days,hours)] #fortunately timedelta defaults to days so I dont have to read the doccumentation for map
return [seed - delta for delta in deltas]
def make_sex(self):
num=self.num
#sex_seed=np.random.choice(2,num,.52)
#sex_seed=np.ones(num)
sex_arr=np.array(list('m'*num))
sex_arr[:int(num/2)]='f'
return sex_arr
def make_NONE(self,*arrays): #FIXME very broken for strings
noneArr=[]
num_nones=int(self.num/5)+1
[noneArr.append(None) for i in range(num_nones)]
noneArr=np.array(noneArr)
for array in arrays:
#array=np.array(array)
array[:num_nones]=noneArr
printD([n for n in array])
np.random.shuffle(array)
#methods every class should have
def setup(self):
#self.Thing
query=self.session.query(Mouse)
if not query.count():
pass
def make_all(self):
pass
def tests(self):
"things to do once the things are made"
pass
def test_delete(self):
pass
def commit(self): #XXX now flush, but hey...
assert self.records, 'self.records is empty!!!!'
self.session.add_all(self.records)
self.session.flush()
###--------
### people
###--------
class t_people(TEST):
def make_name(self,names_per=1):
num=self.num
names=open('names.txt')
nlist=[]
while 1:
name=names.readline()
if name:
nlist.append(name[:-1])
else:
break
num=len(nlist)
#FIXME lol broekn!!!! though if I test w/ more than 5000 names..
all_names=[np.random.permutation(nlist)[:num] for i in range(names_per)]
return all_names
def make_role(self):
num=self.num
roles=['wanker','narf','pi','turd','subject','gradstudent','postdoc']
#for the recored putting subjects in with everyone else is TOTALLY a HIPA violation
rollseed=np.random.choice(len(roles),num)
out=[roles[i] for i in rollseed]
return out
def make_all(self):
num=self.num
pfns, fns, mns, lns = self.make_name(4)
#print(pfns[num],fns[num],mns[num],lns[num])
genders=self.make_sex()
#print(genders)
birthdates=self.make_date()
roles=self.make_role()
ntids=np.unique(np.int32(np.random.sample(num*2)*50000))[:num] #still broken
#ntids=np.random.randint(0,99999,num) #test for non unique
#ntids=list(ntids)
ntids=[int(n) for n in ntids]
#self.make_NONE(pfns,fns,mns,lns,genders,birthdates,roles,ntids) #BROKEN
self.records=[]
self.records+=[Person(PrefixName=pfns[i],
FirstName=fns[i],
MiddleName=mns[i],
LastName=lns[i],
neurotree_id=ntids[i],
Birthdate=birthdates[i]) for i in range(8,num)]
self.records+=[Person(FirstName=fns[i],
MiddleName=mns[i],
LastName=lns[i],
neurotree_id=ntids[i],
Birthdate=birthdates[i]) for i in range(1)]
self.records+=[Person(PrefixName=pfns[i],
MiddleName=mns[i],
LastName=lns[i],
neurotree_id=ntids[i],
Birthdate=birthdates[i]) for i in range(1,2)]
self.records+=[Person(PrefixName=pfns[i],
FirstName=fns[i],
LastName=lns[i],
neurotree_id=ntids[i],
Birthdate=birthdates[i]) for i in range(2,3)]
self.records+=[Person(PrefixName=pfns[i],
FirstName=fns[i],
MiddleName=mns[i],
neurotree_id=ntids[i],
Birthdate=birthdates[i]) for i in range(3,4)]
self.records+=[Person(PrefixName=pfns[i],
FirstName=fns[i],
MiddleName=mns[i],
LastName=lns[i],
neurotree_id=ntids[i],
Birthdate=birthdates[i]) for i in range(4,5)]
self.records+=[Person(PrefixName=pfns[i],
FirstName=fns[i],
MiddleName=mns[i],
LastName=lns[i],
neurotree_id=ntids[i],
Birthdate=birthdates[i]) for i in range(5,6)]
self.records+=[Person(PrefixName=pfns[i],
FirstName=fns[i],
MiddleName=mns[i],
LastName=lns[i],
Birthdate=birthdates[i]) for i in range(6,7)]
self.records+=[Person(PrefixName=pfns[i],
FirstName=fns[i],
MiddleName=mns[i],
LastName=lns[i],
neurotree_id=ntids[i]) for i in range(7,8)]
def query(self):
printD([p for p in self.session.query(Person)])
###------
### Mice
###------
'''
class t_dob(TEST):
def __init__(self,session,num=None,datetimes=None):
self.datetimes=datetimes
super().__init__(session,num)
def make_all(self):
if not self.datetimes:
dts=self.make_datetime(years=2)
self.records=[DOB(d) for d in dts]
else:
self.records=[DOB(d) for d in self.datetimes]
class t_breeders(TEST):
"""makes n pairs of breeders"""
def make_all(self):
mice=t_mice(self.session,4*self.num)
sires=self.session.query(Mouse).filter(Mouse.sex_id=='m')
dams=self.session.query(Mouse).filter(Mouse.sex_id=='f')
self.records=[Sire(sire) for sire in sires[:self.num]]+[Dam(dam) for dam in dams[:self.num]]
'''
class t_mating_record(TEST):
def setup(self):
#self.sires=[s for s in hasKVPair(self.session,Mouse,'sex','m')]
#self.dams=[d for d in hasKVPair(self.session,Mouse,'sex','f')]
self.sires=self.session.query(Mouse).filter_by(sex_id='m').all()
self.dams=self.session.query(Mouse).filter_by(sex_id='f').all()
strain=self.session.query(Strain)[0]
s=[Mouse(sex_id='m',strain_id=strain) for i in range(self.num-len(self.sires))]
d=[Mouse(sex_id='f',strain_id=strain) for i in range(self.num-len(self.dams))]
self.session.add_all(s+d)
self.session.flush()
self.sires.extend(s)
self.dams.extend(d)
def make_all(self):
from datetime import datetime,timedelta
sire_arr=np.random.choice(len(self.sires),self.num)
dam_arr=np.random.choice(len(self.dams),self.num)
mins=np.random.randint(-60,60,self.num)
now=datetime.now()
type_=self.session.query(ExperimentType).filter_by(name='Mating Record')[0]
self.records=[Experiment(project_id=1,person_id=1,type_id=type_,Subjects=[self.sires[sire_arr[i]],self.dams[dam_arr[i]]],startDateTime=now+timedelta(hours=i),endDateTime=now+timedelta(hours=int(i)+12,minutes=int(mins[i]))) for i in range(self.num)]
class t_litters(TEST):
def make_all(self): #FIXME also need to test making without a MR
from datetime import timedelta
mrs=t_mating_record(self.session,self.num)
def getBD(exp,days=19):
durd2=(exp.endDateTime-exp.startDateTime)/2
conception=exp.startDateTime+durd2
return conception+timedelta(days)
self.records=[Litter(repro_experiment_id=mr,startDateTime=getBD(mr)) for mr in mrs.records]
def add_members(self):
mice=[] #FIXME there has to be a better way
#litter_sizes=np.random.randint(6,20,self.num) #randomize litter size
litter_sizes=np.int32(np.ones(self.num)*20)
#compare the two following methods: Second one seems faster, need to verify
#ms=[self.records[i].make_members(litter_sizes[i]) for i in range(self.num)]
#[mice.extend(m) for m in ms]
#self.session.add_all(mice)
strain=self.session.query(Strain)[0] #FIXME
for lit,i in zip(self.records,range(self.num)):
lit.children.extend([Mouse(repro_experiment_id=lit.repro_experiment_id,sex_id='u',strain_id=strain,startDateTime=lit.startDateTime) for i in range(litter_sizes[i])])
#VS
#[self.session.add_all(self.records[i].make_members(litter_sizes[i])) for i in range(self.num)]
self.session.commit()
class t_strain(TEST):
def make_all(self):
self.records=[Strain() for i in range(self.num)] #TODO itertools starmap
printD(self.records)
class t_mice(TEST):
def make_all(self):
#dobs=t_dob(self.session,self.num)
tags=np.random.randint(0,1000,self.num)
sexes=self.make_sex()
strain=self.session.query(Strain)[0]
dts=self.make_datetime(years=2)
self.records=[Mouse(Properties={'eartag':int(tags[i])},sex_id=sexes[i],strain_id=strain,startDateTime=dts[i]) for i in range(self.num)]
###--------------------
### subjects continued
###--------------------
class t_slice(TEST):
def make_all(self):
#preps=self.session.query(Experiment).filter(Experiment.type==self.session.query(ExperimentType).filter_by(name='acute slice prep'))[0]
preps=self.session.query(Experiment).join((ExperimentType,Experiment.type)).filter_by(name='acute slice prep').all()
self.records=[]
[[self.records.append(Slice(parent_id=prep.subjects[0],generating_experiment_id=prep,startDateTime=datetime.now()+timedelta(hours=i))) for i in range(self.num)] for prep in preps] #FIXME amplification of numbers
printD(self.records)
class t_cell(TEST):
def make_all(self):
slices=[s for s in self.session.query(Slice) if s.parent_id is not None]
assert slices, 'slices should not be empty here'
#printD([s.parent_id for s in slices])
#patches=[p for p in self.session.query(Experiment).filter_by(type='acute slice prep')]
#patches=[p for p in self.session.query(Experiment).filter(Experiment.type==self.session.query(ExperimentType).filter_by(name='acute slice prep')[0])] #FIXME clearly this expeirment type is wrong and I havent been catching it FIXME FIXME
patches=self.session.query(Experiment).join((ExperimentType,Experiment.type)).filter_by(name='in vitro patch').all()
assert patches, 'patches should not be empty here'
headstages=[h for h in self.session.query(Hardware).filter_by(type_id='headstage')][:2]
self.records=[]
z=0
for p in patches:
for i in range(z,len(slices)): #120 #FIXME pretty sure RI is broken here
s=slices[i]
for j in range(self.num):
self.records.extend([Cell(Hardware=[h],parent_id=s,Experiments=[p],generating_experiment_id=p) for h in headstages])
try:
if slices[i+1].parent_id != s.parent_id: #FIXME this should catch automatically when using session.add
z=i+1 #FIXME constraint!!!!
break
except IndexError: pass
#printD([c.experiments for c in self.records])
class t_c2c(TEST):
def make_all(self):
cells=self.session.query(Cell)
#circular link
self.records=[]
self.records.extend([CellPairs(cells[i-2],cells[i]) for i in range(cells.count())]) #this adds tripplets since a single row here is treated as simultaneous, INCIDENTALLY FIXME this is a problem because it means that a=b=c IS NOT TRUE on this set a=b b=c a!=c fuck
#HOWEVER: this is less of an integrity concern than having to make two entries for each pair, for higher numbers of recordin I should probably do this as cell1 cell2 cell3 cell4 to prevent stuipd combinatorial nightmares
#pairs
self.records.extend([CellPairs(cells[i],cells[i+1]) for i in range(0,cells.count()-1,2)])
#self.records.extend([CellPairs(cells[i+1],cells[i]) for i in range(0,cells.count()-1,2)])
###-------------
### experiments
###-------------
class t_project(TEST):
def make_all(self):
iacuc_protocol_id=None
blurb=None
self.records=[Project(lab='Scanziani',iacuc_protocol_id=iacuc_protocol_id,blurb=blurb) for n in range(self.num)]
count=0
def add_people(self): #has to be called after commit :/
people=t_people(self.session,100)
#HRM only queries can leverage the power of .filter
pis=[pi for pi in self.session.query(Person)]
pi_n=np.random.choice(len(pis),self.num)
#people=[p for p in self.session.query(Person)]
people_n=[np.random.permutation(people.records)[:np.random.randint(1,20)] for i in range(self.num)] #+pis[pi_n[i]]
assocs=[]
count=0
for rec,people in zip(self.records,people_n):
#assocs.append(person_to_project(rec,pis[pi_n[count]]))
assocs+=[person_to_project(rec,person) for person in people]
#[rec.people.append(person) for person in people] #FIXME somehow this no workey
count+=1
self.session.add_all(assocs)
self.session.commit()
class t_exptype(TEST):
def make_all(self):
self.records=[
ExperimentType(name='Mating Record',base_step_id=1),
ExperimentType(name='acute slice prep',abbrev='prep',base_step_id=2),
ExperimentType(name='in vitro patch',abbrev='patch',base_step_id=3),
]
class t_experiment(TEST):
def __init__(self,session,num=None,num_projects=None):
self.num_projects=num_projects
super().__init__(session,num)
def make_all(self):
#from time import sleep
projects=t_project(self.session,self.num_projects)
projects.add_people()
#projects.commit() #FIXME do I need to readd? or can I just commit directly?
lits=t_litters(self.session,1)
lits.add_members()
#lits.commit()
mice=[m for m in self.session.query(Mouse).filter(Mouse.breedingRec==None,Mouse.dod==None)] #FIXME
#mice=[m for m in self.session.query(Mouse).filter(Mouse.dod==None)]
self.records=[]
for p in projects.records:
#printD(p) #FIXME apparently p.__dict__ is not populated until AFTER you call the object...
#printD([t for t in p.__dict__.items()]) #FIXME what the fuck, sometimes this catches nothing!?
ms=[mice[i] for i in np.random.choice(len(mice),self.num)] #FIXME missing mouse
#TODO need to test with bad inputs
exps=[p.people[i] for i in np.random.choice(len(p.people),self.num)]
datetimes=self.make_datetime()
exptype=self.sessison.query(ExperimentType).filter_by(name='in vitro patch')[0]
self.records+=[Experiment(project_id=p,Person=exps[i],startDateTime=datetimes[i],type_id=exptype) for i in range(self.num)] #FIXME lol this is going to reaveal experiments on mice that aren't even born yet hehe
class t_patch(TEST):
def make_all(self):
#mice=[m for m in self.session.query(Mouse).filter(Mouse.dod==None)]
preps=[p for p in self.session.query(Experiment).filter(Experiment.type==self.session.query(ExperimentType).filter_by(name='acute slice prep')[0])]
project=self.session.query(Project)[0]
person=self.session.query(Person)[0]
#acsf=self.session.query(Reagent).filter_by(type_id=2)[0] #FIXME these are terrible useage patterns
#internal=self.session.query(Reagent).filter_by(type_id=3)[0] #FIXME these are terrible useage patterns
#acsf=None
#internal=None
#self.session.add_all([acsf,internal])
#self.session.flush() #shit not working FIXME
self.session.commit()
exptype=self.session.query(ExperimentType).filter_by(abbrev='patch')[0]
self.records=[]
datetimes=self.make_datetime()
[self.records.extend([Experiment(type_id=exptype,project_id=project,person_id=person,Reagents=[],startDateTime=datetimes[i]) for i in range(self.num)]) for p in preps] #FIXME classic mouse not born yet problem
class t_sliceprep(TEST):
def make_all(self):
project=self.session.query(Project)[0]
person=self.session.query(Person)[0]
#sucrose=self.session.query(Reagent).filter_by(type_id=1)[0]
exptype=self.session.query(ExperimentType).filter_by(abbrev='prep')[0]
self.records=[Experiment(type_id=exptype,project_id=project,person_id=person,Reagents=[],startDateTime=datetime.now()-timedelta(int(np.random.randint(1)))) for i in range(self.num)] #FIXME need to find a way to propagate mouse w/ RI
def add_mice(self):
mice=self.session.query(Mouse).filter_by(sex_id='u')[:self.num]
#mice=[s for s in hasKVPair(self.session,Mouse,'sex','u')]
printD(len(mice))
printD(len(self.records))
np.random.shuffle(mice)
for i in range(self.num):
#mice[i].experiment_id=self.records[i].id
self.records[i].subjects.append(mice[i])
self.session.commit()
class t_patch(TEST):
def make_all(self):
project=self.session.query(Project)[0]
person=self.session.query(Person)[0]
#sucrose=self.session.query(Reagent).filter_by(type_id=1)[0]
exptype=self.session.query(ExperimentType).filter_by(abbrev='patch')[0]
self.records=[Experiment(type_id=exptype,project_id=project,person_id=person,Reagents=[],startDateTime=datetime.now()-timedelta(int(np.random.randint(1)))) for i in range(self.num)] #FIXME need to find a way to propagate mouse w/ RI
#def add_mice(self): #add slices?
#mice=self.session.query(Mouse).filter_by(sex_id='u')[:self.num]
##mice=[s for s in hasKVPair(self.session,Mouse,'sex','u')]
#printD(len(mice))
#printD(len(self.records))
#np.random.shuffle(mice)
#for i in range(self.num):
#mice[i].experiment_id=self.records[i].id
#self.records[i].subjects.append(mice[i])
#self.session.commit()
###------
### data
###------
class t_repo(TEST):
def make_all(self):
self.records=[]
repos=(
'file:///C:/asdf/test1',
'file:///C:/asdf/test2//',
'file:///T:/db/Dropbox//',
'http://www.google.com/', #FIXME broken as expected?
'https://www.google.com/' #FIXME broken as expected?
)
for r in repos:
try:
self.records.append(Repository(url=r))
except:
#raise Warning('Local path \'%s\' does not exist!'%r)
print('Path \'%s\' does not exist!'%r)
#FIXME for some reason adding the fully inited Repository(url='asdf') inside the list didn't work...
#figure out why please?!
def tests(self):
self.commit()
repos=self.session.query(Repository).all()
for repo in repos:
[repo.mirrors_from_here.append(r) for r in repos if r!=repo]
print(repo.mirrors)
self.commit()
[print(r.mirrors) for r in repos]
class t_datafilesource(TEST):
def make_all(self):
self.records=[
DataFileSource(name='test',extension='data',docstring='wooo!'),
]
class t_metadatasource(TEST):
def make_all(self):
hw=self.session.query(Hardware).filter_by(name='the void')[0]
self.records=[
MetaDataSource(name='the void',prefix='T',unit='Pa',hardware_id=hw,docstring='yes I am nothing'),
]
class t_datafile(TEST):
#def __init__(self,session,num=None,num_experiments=None,num_projects=None):
#self.num_projects=num_projects
#self.num_experiments=num_experiments
#super().__init__(session,num)
def make_all(self):
repo=t_repo(self.session)
dfs=self.session.query(DataFileSource).filter_by(name='test')[0]
data=[]
#cells=self.session.query(Cell)
#for c1,c2 in zip(cells[:-1],cells[1:]):
subjects=self.session.query(Cell).filter(Cell.experiments.any()).all()
cells=self.session.query(Cell).all()
#printD(cells)
#printD([(subject,subject.experiments) for subject in subjects])
for subject in subjects:
#printD(subject.experiments)
for url in repo.records:
bn='exp%s_subs_%s_'%(subject.experiments[0].id,subject.id)
name=bn+'%s.data'
try:
data+=[DataFile(name%df,url,dfs,subject.experiments[0],
Subjects=[subject]) for df in range(self.num)] #FIXME this use pattern is clearly broken
except FileNotFoundError:
printD('some file was not found')
pass
#data+=[DataFile(Repo=rp,filename='exp%s_cells_%s_%s_%s.data'%(c1.experiments[0].id,c1.id,c2.id,df),Experiment=c1.experiments[0],DataSource=ds,Subjects=[c1,c2]) for df in range(self.num)]
self.records=data
class t_dfmetadata(TEST):
def make_all(self):
ds=self.session.query(MetaDataSource)[0]
self.records=[]
[self.records.extend([d.MetaData(i,parent_id=d,metadatasource_id=ds) for i in range(self.num)]) for d in self.session.query(DataFile)]
###-----------
### inventory
###-----------
class t_hardware(TEST):
def setup(self):
self.amps=[Hardware(type_id='amplifier',name='lolwut',Properties={'unique_id':'0012312'}),Hardware(type_id='amplifier',name='rudubme',Properties={'unique_id':'bob'})]
self.session.add_all(self.amps)
self.session.flush()
def make_all(self):
self.records=[]
[[self.records.append(Hardware(type_id='headstage',name='wut%s%s'%(amp.id,i),Properties={'unique_id':'%s%s'%(amp.id,i)}, parent_id=amp)) for i in range(2)] for amp in self.amps]
self.records.append(Hardware(type_id='digitizer',name='the void'))
#printD(self.records) #FIXME this whole make all is broken
class t_hwmetadata(TEST):
def make_all(self):
ds=self.session.query(MetaDataSource)[0] #TODO make sure this breaks, FIXME it breaks but not where expected...
self.records=[]
[self.records.extend([h.MetaData(i,h,ds) for i in range(self.num)]) for h in self.session.query(Hardware)]
class t_reagenttype(TEST):
def make_all(self):
self.records=[
ReagentType(name='poop'),
ReagentType(name='poop1'),
ReagentType(name='poop2')
]
class t_reagent(TEST):
def make_all(self):
rts=self.session.query(ReagentType)
self.records=[Reagent(Type=r) for r in rts]
###-------
### steps
###-------
class t_steps(TEST):
def make_all(self):
self.records.extend([Step(name='a%s'%i,dataio_id=1,docstring='') for i in range(self.num)])
class t_edges(TEST):
def make_all(self):
steps=self.session.query(Step).order_by(Step.id).all()
a=steps[0].id
b=a+1
c=b+1
def basic_tests():
failed=False
#cycle 1->1
try:
a1=StepEdge(a,a)
self.session.add(a1)
self.session.flush()
failed=True
except:
pass
self.session.query(StepEdge).all()
assert not failed, 'a==a check FAILED'
#basic add
a2=StepEdge(a,b) #OK
self.session.add(a2)
self.session.flush()
assert a2, 'basic test FAILED'
#cycle 1->2->1
try:
a3=StepEdge(b,a)
self.session.add(a3) #FIXME a3 still in records after delete!
self.session.flush()
failed=True
except:
pass
#printD(a3.__repr__())
assert not failed, 'circular 1-2-1 check FAILED'
#basic add 2 to add one more node to the cycle
a4=StepEdge(b,c) #OK
self.session.add(a4)
self.session.flush()
assert a4, 'basic test #2 FAILED'
#cycle from 1->2->3->1
try:
a5=StepEdge(c,a)
self.session.add(a5)
self.session.flush()
failed=True
except:
pass
assert not failed, 'circular 1-2-3-1 check FAILED'
def adv_tests():
se1=set(self.session.query(StepEdge).all())
assert se1 == se1 , 'A SET IS NOT EQUAL TO ITSELF RUNNNNNN!!!'
try:
[step.dependencies.update([steps[int(i)] for i in np.random.randint(0,100,20)]) for step in steps]
printD(self.session.new)
#[step.dependencies.update((steps[int(i)] for i in np.random.randint(0,100,20))) for step in steps]
except (ValueError, FlushError) as e:
if type(e) is FlushError:
printD('Rolling back!')
self.session.rollback()
printD(e)
printD(self.session.new)
self.session.flush()
self.session.expire_all()
se2=set(self.session.query(StepEdge).all())
assert se2 != se1, 'set used for update probably contained a duplicate'
try:
for i in range(20):
for step in steps:
step.dependencies.add(steps[int(np.random.randint(100))])
printD(self.session.new)
except (ValueError, FlushError) as e:
if type(e) is FlushError:
printD('Rolling back!')
self.session.rollback()
printD(e)
printD(self.session.new)
self.session.flush()
se3=set(self.session.query(StepEdge).all())
assert se3 != se2
for i in range(100): #FIXME somehow all this stuff really does not work well with the versioning
a,b=(steps[int(i)] for i in np.random.randint(0,len(steps),2))
try:
self.session.add(StepEdge(a,b))
self.session.flush()
except (ValueError, FlushError) as e:
printD(e)
#self.session.rollback() #FIXME <<< this is what causes all the good edges to get zapped
se4=set(self.session.query(StepEdge).all())
assert se4 != se3
printD('Num StepEdges',len(se4)) #FIXME this is patently wrong
def custom():
start=a
for i in range(0,10):
self.session.add(StepEdge(start+i,start+i+1))
self.session.flush()
for i in range(2,10):
self.session.add(StepEdge(start+i,start+i+12))
self.session.flush()
for i in range(4,10):
self.session.add(StepEdge(start+i,start+i+25))
self.session.flush()
self.session.add(StepEdge(start,14))
self.session.flush()
self.session.add(StepEdge(start+7,start+9))
self.session.flush()
#basic_tests()
custom()
#adv_tests()
def commit(self):
self.session.commit()
#todo test a double cycle and a split tree
def test_delete(self):
printD('running delete tests!')
#edges=self.session.query(StepEdge).all()
#[self.session.delete(edge) for edge in edges]
pass
def run_tests(session):
#FIXME for some reason running these sequentially causes all sorts of problems...
#RESPONSE turns out it is because I'm trying to make EXACTLY the same tables again and an identical mapped instance already exists
#so it doesnt happen with people, but a collision *could* happen
#FIXME the real test will be to vary the number of projects, experiments and datafiles
#compare these two cases with profiler
#d=t_datafile(session,5000,2,4) #add 1000 datafiles to 3 projects each with 10 experiments takes about 16 seconds, I'd say we're ok here
#d=t_datafile(session,20,500,4) #add 1000 datafiles to 3 projects each with 10 experiments takes about 16 seconds, I'd say we're ok here
#d=t_datafile(session,10,50,4)
#[print(df.creation_DateTime) for df in session.query(DataFile)]
if session.connection().engine.url.database != 'db_test':
return None
t_strain(session,2)
t_steps(session,3)
#t_edges(session)
expt=t_exptype(session)
hw=t_hardware(session)
ds=t_datafilesource(session)
mds=t_metadatasource(session)
#h=t_hardware(session)
hwmd=t_hwmetadata(session,5)
#t_experiment(session,1,4) #FIXME argh, so many things can become inconsistent...
t_people(session,20)
t_project(session,1)
t_mice(session,20)
l=t_litters(session,20)
l.add_members()
rt=t_reagenttype(session)
#i=t_reagent(session)
sp=t_sliceprep(session,5)
sp.add_mice()
p=t_patch(session,1) #FIXME you know it might be good to force a new exp rec when any of the variables changes... like the internal...? think think
s=t_slice(session,4)
pa=t_patch(session,2)
c=t_cell(session,5)
#c2c=t_c2c(session) #no longer used
d=t_datafile(session,1)#,2,1) #FIXME eating memory
dfmd=t_dfmetadata(session,1) #as in 8 gigs of memory...
session.commit()
#l=t_litters(session,20) #FIXME another wierd error here... saying that I tried to add a mouse as a breeder twice... hrm...
#l.add_members()
#printD([m for m in session.query(Mouse)]) #FIXME mice arent getting made?
def main():
pass
if __name__=='__main__':
main()
|
the-stack_0_8485 | #
# Copyright 2018 Analytics Zoo Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import numpy as np
import base64
from zoo.serving.client import InputQueue, OutputQueue, http_json_to_ndarray
import os
resource_path = os.path.join(os.path.split(__file__)[0], "../resources")
class TestSerialization:
def test_encode(self):
input_api = InputQueue()
b64 = input_api.data_to_b64(t1=np.array([1, 2]), t2=np.array([3, 4]))
byte = base64.b64decode(b64)
def test_http_response_to_ndarray(self):
with open(os.path.join(resource_path, "serving/http_response")) as f:
data = f.read()
arr = http_json_to_ndarray(data)
assert isinstance(arr, np.ndarray)
assert len(arr.shape) == 1
assert arr.shape[0] == 128
|
the-stack_0_8488 | # Copyright (c) 2014-2016, ConfigSpace developers
# Matthias Feurer
# Katharina Eggensperger
# and others (see commit history).
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the <organization> nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from io import StringIO
import os
import tempfile
import unittest
from ConfigSpace.configuration_space import ConfigurationSpace
import ConfigSpace.read_and_write.pcs as pcs
import ConfigSpace.read_and_write.pcs_new as pcs_new
from ConfigSpace.hyperparameters import CategoricalHyperparameter, \
UniformIntegerHyperparameter, UniformFloatHyperparameter, OrdinalHyperparameter
from ConfigSpace.conditions import EqualsCondition, InCondition, \
AndConjunction, OrConjunction, NotEqualsCondition, \
GreaterThanCondition
from ConfigSpace.forbidden import ForbiddenInClause, ForbiddenAndConjunction
# More complex search space
classifier = CategoricalHyperparameter("classifier", ["svm", "nn"])
kernel = CategoricalHyperparameter("kernel", ["rbf", "poly", "sigmoid"])
kernel_condition = EqualsCondition(kernel, classifier, "svm")
C = UniformFloatHyperparameter("C", 0.03125, 32768, log=True)
C_condition = EqualsCondition(C, classifier, "svm")
gamma = UniformFloatHyperparameter("gamma", 0.000030518, 8, log=True)
gamma_condition = EqualsCondition(gamma, kernel, "rbf")
degree = UniformIntegerHyperparameter("degree", 1, 5)
degree_condition = InCondition(degree, kernel, ["poly", "sigmoid"])
neurons = UniformIntegerHyperparameter("neurons", 16, 1024)
neurons_condition = EqualsCondition(neurons, classifier, "nn")
lr = UniformFloatHyperparameter("lr", 0.0001, 1.0)
lr_condition = EqualsCondition(lr, classifier, "nn")
preprocessing = CategoricalHyperparameter("preprocessing", ["None", "pca"])
conditional_space = ConfigurationSpace()
conditional_space.add_hyperparameter(preprocessing)
conditional_space.add_hyperparameter(classifier)
conditional_space.add_hyperparameter(kernel)
conditional_space.add_hyperparameter(C)
conditional_space.add_hyperparameter(neurons)
conditional_space.add_hyperparameter(lr)
conditional_space.add_hyperparameter(degree)
conditional_space.add_hyperparameter(gamma)
conditional_space.add_condition(C_condition)
conditional_space.add_condition(kernel_condition)
conditional_space.add_condition(lr_condition)
conditional_space.add_condition(neurons_condition)
conditional_space.add_condition(degree_condition)
conditional_space.add_condition(gamma_condition)
float_a = UniformFloatHyperparameter("float_a", -1.23, 6.45)
e_float_a = UniformFloatHyperparameter("e_float_a", .5E-2, 4.5e+06)
int_a = UniformIntegerHyperparameter("int_a", -1, 6)
log_a = UniformFloatHyperparameter("log_a", 4e-1, 6.45, log=True)
int_log_a = UniformIntegerHyperparameter("int_log_a", 1, 6, log=True)
cat_a = CategoricalHyperparameter("cat_a", ["a", "b", "c", "d"])
crazy = CategoricalHyperparameter(r"@.:;/\?!$%&_-<>*+1234567890", ["const"])
easy_space = ConfigurationSpace()
easy_space.add_hyperparameter(float_a)
easy_space.add_hyperparameter(e_float_a)
easy_space.add_hyperparameter(int_a)
easy_space.add_hyperparameter(log_a)
easy_space.add_hyperparameter(int_log_a)
easy_space.add_hyperparameter(cat_a)
easy_space.add_hyperparameter(crazy)
class TestPCSConverter(unittest.TestCase):
def setUp(self):
self.maxDiff = None
def test_read_configuration_space_basic(self):
# TODO: what does this test has to do with the PCS converter?
float_a_copy = UniformFloatHyperparameter("float_a", -1.23, 6.45)
a_copy = {"a": float_a_copy, "b": int_a}
a_real = {"b": int_a, "a": float_a}
self.assertDictEqual(a_real, a_copy)
'''
Tests for the "older pcs" version
'''
def test_read_configuration_space_easy(self):
expected = StringIO()
expected.write('# This is a \n')
expected.write(' # This is a comment with a leading whitespace ### ffds \n')
expected.write('\n')
expected.write('float_a [-1.23, 6.45] [2.61] # bla\n')
expected.write('e_float_a [.5E-2, 4.5e+06] [2250000.0025]\n')
expected.write('int_a [-1, 6] [2]i\n')
expected.write('log_a [4e-1, 6.45] [1.6062378404]l\n')
expected.write('int_log_a [1, 6] [2]il\n')
expected.write('cat_a {a,"b",c,d} [a]\n')
expected.write(r'@.:;/\?!$%&_-<>*+1234567890 {"const"} ["const"]\n')
expected.seek(0)
cs = pcs.read(expected)
self.assertEqual(cs, easy_space)
def test_read_configuration_space_conditional(self):
# More complex search space as string array
complex_cs = list()
complex_cs.append("preprocessing {None, pca} [None]")
complex_cs.append("classifier {svm, nn} [svm]")
complex_cs.append("kernel {rbf, poly, sigmoid} [rbf]")
complex_cs.append("C [0.03125, 32768] [32]l")
complex_cs.append("neurons [16, 1024] [520]i # Should be Q16")
complex_cs.append("lr [0.0001, 1.0] [0.50005]")
complex_cs.append("degree [1, 5] [3]i")
complex_cs.append("gamma [0.000030518, 8] [0.0156251079996]l")
complex_cs.append("C | classifier in {svm}")
complex_cs.append("kernel | classifier in {svm}")
complex_cs.append("lr | classifier in {nn}")
complex_cs.append("neurons | classifier in {nn}")
complex_cs.append("degree | kernel in {poly, sigmoid}")
complex_cs.append("gamma | kernel in {rbf}")
cs = pcs.read(complex_cs)
self.assertEqual(cs, conditional_space)
def test_read_configuration_space_conditional_with_two_parents(self):
config_space = list()
config_space.append("@1:0:restarts {F,L,D,x,+,no}[x]")
config_space.append("@1:S:Luby:aryrestarts {1,2}[1]")
config_space.append("@1:2:Luby:restarts [1,65535][1000]il")
config_space.append("@1:2:Luby:restarts | @1:0:restarts in {L}")
config_space.append("@1:2:Luby:restarts | @1:S:Luby:aryrestarts in {2}")
cs = pcs.read(config_space)
self.assertEqual(len(cs.get_conditions()), 1)
self.assertIsInstance(cs.get_conditions()[0], AndConjunction)
def test_write_illegal_argument(self):
sp = {"a": int_a}
self.assertRaisesRegex(TypeError, r"pcs_parser.write expects an "
r"instance of "
r"<class "
r"'ConfigSpace.configuration_"
r"space.ConfigurationSpace'>, you provided "
r"'<(type|class) 'dict'>'", pcs.write, sp)
def test_write_int(self):
expected = "int_a [-1, 6] [2]i"
cs = ConfigurationSpace()
cs.add_hyperparameter(int_a)
value = pcs.write(cs)
self.assertEqual(expected, value)
def test_write_log_int(self):
expected = "int_log_a [1, 6] [2]il"
cs = ConfigurationSpace()
cs.add_hyperparameter(int_log_a)
value = pcs.write(cs)
self.assertEqual(expected, value)
def test_write_q_int(self):
expected = "Q16_int_a [16, 1024] [520]i"
cs = ConfigurationSpace()
cs.add_hyperparameter(
UniformIntegerHyperparameter("int_a", 16, 1024, q=16))
value = pcs.write(cs)
self.assertEqual(expected, value)
def test_write_q_float(self):
expected = "Q16_float_a [16.0, 1024.0] [520.0]"
cs = ConfigurationSpace()
cs.add_hyperparameter(
UniformFloatHyperparameter("float_a", 16, 1024, q=16))
value = pcs.write(cs)
self.assertEqual(expected, value)
def test_write_log10(self):
expected = "a [10.0, 1000.0] [100.0]l"
cs = ConfigurationSpace()
cs.add_hyperparameter(
UniformFloatHyperparameter("a", 10, 1000, log=True))
value = pcs.write(cs)
self.assertEqual(expected, value)
def test_build_forbidden(self):
expected = "a {a, b, c} [a]\nb {a, b, c} [c]\n\n" \
"{a=a, b=a}\n{a=a, b=b}\n{a=b, b=a}\n{a=b, b=b}"
cs = ConfigurationSpace()
a = CategoricalHyperparameter("a", ["a", "b", "c"], "a")
b = CategoricalHyperparameter("b", ["a", "b", "c"], "c")
cs.add_hyperparameter(a)
cs.add_hyperparameter(b)
fb = ForbiddenAndConjunction(ForbiddenInClause(a, ["a", "b"]),
ForbiddenInClause(b, ["a", "b"]))
cs.add_forbidden_clause(fb)
value = pcs.write(cs)
self.assertIn(expected, value)
"""
Tests for the "newer pcs" version in order to check
if both deliver the same results
"""
def test_read_new_configuration_space_easy(self):
expected = StringIO()
expected.write('# This is a \n')
expected.write(' # This is a comment with a leading whitespace ### ffds \n')
expected.write('\n')
expected.write('float_a real [-1.23, 6.45] [2.61] # bla\n')
expected.write('e_float_a real [.5E-2, 4.5e+06] [2250000.0025]\n')
expected.write('int_a integer [-1, 6] [2]\n')
expected.write('log_a real [4e-1, 6.45] [1.6062378404]log\n')
expected.write('int_log_a integer [1, 6] [2]log\n')
expected.write('cat_a categorical {a,"b",c,d} [a]\n')
expected.write(r'@.:;/\?!$%&_-<>*+1234567890 categorical {"const"} ["const"]\n')
expected.seek(0)
cs = pcs_new.read(expected)
self.assertEqual(cs, easy_space)
def test_read_new_configuration_space_conditional(self):
# More complex search space as string array
complex_cs = list()
complex_cs.append("preprocessing categorical {None, pca} [None]")
complex_cs.append("classifier categorical {svm, nn} [svm]")
complex_cs.append("kernel categorical {rbf, poly, sigmoid} [rbf]")
complex_cs.append("C real [0.03125, 32768] [32]log")
complex_cs.append("neurons integer [16, 1024] [520] # Should be Q16")
complex_cs.append("lr real [0.0001, 1.0] [0.50005]")
complex_cs.append("degree integer [1, 5] [3]")
complex_cs.append("gamma real [0.000030518, 8] [0.0156251079996]log")
complex_cs.append("C | classifier in {svm}")
complex_cs.append("kernel | classifier in {svm}")
complex_cs.append("lr | classifier in {nn}")
complex_cs.append("neurons | classifier in {nn}")
complex_cs.append("degree | kernel in {poly, sigmoid}")
complex_cs.append("gamma | kernel in {rbf}")
cs_new = pcs_new.read(complex_cs)
self.assertEqual(cs_new, conditional_space)
# same in older version
complex_cs_old = list()
complex_cs_old.append("preprocessing {None, pca} [None]")
complex_cs_old.append("classifier {svm, nn} [svm]")
complex_cs_old.append("kernel {rbf, poly, sigmoid} [rbf]")
complex_cs_old.append("C [0.03125, 32768] [32]l")
complex_cs_old.append("neurons [16, 1024] [520]i # Should be Q16")
complex_cs_old.append("lr [0.0001, 1.0] [0.50005]")
complex_cs_old.append("degree [1, 5] [3]i")
complex_cs_old.append("gamma [0.000030518, 8] [0.0156251079996]l")
complex_cs_old.append("C | classifier in {svm}")
complex_cs_old.append("kernel | classifier in {svm}")
complex_cs_old.append("lr | classifier in {nn}")
complex_cs_old.append("neurons | classifier in {nn}")
complex_cs_old.append("degree | kernel in {poly, sigmoid}")
complex_cs_old.append("gamma | kernel in {rbf}")
cs_old = pcs.read(complex_cs_old)
self.assertEqual(cs_old, cs_new)
def test_write_new_illegal_argument(self):
sp = {"a": int_a}
self.assertRaisesRegex(TypeError,
r"pcs_parser.write expects an "
r"instance of "
r"<class "
r"'ConfigSpace.configuration_"
r"space.ConfigurationSpace'>, you provided "
r"'<(type|class) 'dict'>'", pcs_new.write, sp)
def test_write_new_int(self):
expected = "int_a integer [-1, 6] [2]"
cs = ConfigurationSpace()
cs.add_hyperparameter(int_a)
value = pcs_new.write(cs)
self.assertEqual(expected, value)
def test_write_new_log_int(self):
expected = "int_log_a integer [1, 6] [2]log"
cs = ConfigurationSpace()
cs.add_hyperparameter(int_log_a)
value = pcs_new.write(cs)
self.assertEqual(expected, value)
def test_write_new_q_int(self):
expected = "Q16_int_a integer [16, 1024] [520]"
cs = ConfigurationSpace()
cs.add_hyperparameter(
UniformIntegerHyperparameter("int_a", 16, 1024, q=16))
value = pcs_new.write(cs)
self.assertEqual(expected, value)
def test_write_new_q_float(self):
expected = "Q16_float_a real [16.0, 1024.0] [520.0]"
cs = ConfigurationSpace()
cs.add_hyperparameter(
UniformFloatHyperparameter("float_a", 16, 1024, q=16))
value = pcs_new.write(cs)
self.assertEqual(expected, value)
def test_write_new_log10(self):
expected = "a real [10.0, 1000.0] [100.0]log"
cs = ConfigurationSpace()
cs.add_hyperparameter(
UniformFloatHyperparameter("a", 10, 1000, log=True))
value = pcs_new.write(cs)
self.assertEqual(expected, value)
def test_build_new_forbidden(self):
expected = "a categorical {a, b, c} [a]\nb categorical {a, b, c} [c]\n\n" \
"{a=a, b=a}\n{a=a, b=b}\n{a=b, b=a}\n{a=b, b=b}\n"
cs = ConfigurationSpace()
a = CategoricalHyperparameter("a", ["a", "b", "c"], "a")
b = CategoricalHyperparameter("b", ["a", "b", "c"], "c")
cs.add_hyperparameter(a)
cs.add_hyperparameter(b)
fb = ForbiddenAndConjunction(ForbiddenInClause(a, ["a", "b"]),
ForbiddenInClause(b, ["a", "b"]))
cs.add_forbidden_clause(fb)
value = pcs_new.write(cs)
self.assertEqual(expected, value)
def test_build_new_GreaterThanFloatCondition(self):
expected = "b integer [0, 10] [5]\n" \
"a real [0.0, 1.0] [0.5]\n\n" \
"a | b > 5"
cs = ConfigurationSpace()
a = UniformFloatHyperparameter("a", 0, 1, 0.5)
b = UniformIntegerHyperparameter("b", 0, 10, 5)
cs.add_hyperparameter(a)
cs.add_hyperparameter(b)
cond = GreaterThanCondition(a, b, 5)
cs.add_condition(cond)
value = pcs_new.write(cs)
self.assertEqual(expected, value)
expected = "b real [0.0, 10.0] [5.0]\n" \
"a real [0.0, 1.0] [0.5]\n\n" \
"a | b > 5"
cs = ConfigurationSpace()
a = UniformFloatHyperparameter("a", 0, 1, 0.5)
b = UniformFloatHyperparameter("b", 0, 10, 5)
cs.add_hyperparameter(a)
cs.add_hyperparameter(b)
cond = GreaterThanCondition(a, b, 5)
cs.add_condition(cond)
value = pcs_new.write(cs)
self.assertEqual(expected, value)
def test_build_new_GreaterThanIntCondition(self):
expected = "a real [0.0, 1.0] [0.5]\n" \
"b integer [0, 10] [5]\n\n" \
"b | a > 0.5"
cs = ConfigurationSpace()
a = UniformFloatHyperparameter("a", 0, 1, 0.5)
b = UniformIntegerHyperparameter("b", 0, 10, 5)
cs.add_hyperparameter(a)
cs.add_hyperparameter(b)
cond = GreaterThanCondition(b, a, 0.5)
cs.add_condition(cond)
value = pcs_new.write(cs)
self.assertEqual(expected, value)
expected = "a integer [0, 10] [5]\n" \
"b integer [0, 10] [5]\n\n" \
"b | a > 5"
cs = ConfigurationSpace()
a = UniformIntegerHyperparameter("a", 0, 10, 5)
b = UniformIntegerHyperparameter("b", 0, 10, 5)
cs.add_hyperparameter(a)
cs.add_hyperparameter(b)
cond = GreaterThanCondition(b, a, 5)
cs.add_condition(cond)
value = pcs_new.write(cs)
self.assertEqual(expected, value)
def test_read_new_configuration_space_complex_conditionals(self):
classi = OrdinalHyperparameter(
"classi",
["random_forest", "extra_trees", "k_nearest_neighbors", "something"],
)
knn_weights = CategoricalHyperparameter("knn_weights", ["uniform", "distance"])
weather = OrdinalHyperparameter("weather", ["sunny", "rainy", "cloudy", "snowing"])
temperature = CategoricalHyperparameter("temperature", ["high", "low"])
rain = CategoricalHyperparameter("rain", ["yes", "no"])
gloves = OrdinalHyperparameter("gloves", ["none", "yarn", "leather", "gortex"])
heur1 = CategoricalHyperparameter("heur1", ["off", "on"])
heur2 = CategoricalHyperparameter("heur2", ["off", "on"])
heur_order = CategoricalHyperparameter("heur_order", ["heur1then2", "heur2then1"])
gloves_condition = OrConjunction(EqualsCondition(gloves, rain, "yes"),
EqualsCondition(gloves, temperature, "low"))
heur_condition = AndConjunction(EqualsCondition(heur_order, heur1, "on"),
EqualsCondition(heur_order, heur2, "on"))
and_conjunction = AndConjunction(NotEqualsCondition(knn_weights, classi, "extra_trees"),
EqualsCondition(knn_weights, classi, "random_forest"))
Cl_condition = OrConjunction(EqualsCondition(knn_weights, classi, "k_nearest_neighbors"),
and_conjunction,
EqualsCondition(knn_weights, classi, "something"))
and1 = AndConjunction(EqualsCondition(temperature, weather, "rainy"),
EqualsCondition(temperature, weather, "cloudy"))
and2 = AndConjunction(EqualsCondition(temperature, weather, "sunny"),
NotEqualsCondition(temperature, weather, "snowing"))
another_condition = OrConjunction(and1, and2)
complex_conditional_space = ConfigurationSpace()
complex_conditional_space.add_hyperparameter(classi)
complex_conditional_space.add_hyperparameter(knn_weights)
complex_conditional_space.add_hyperparameter(weather)
complex_conditional_space.add_hyperparameter(temperature)
complex_conditional_space.add_hyperparameter(rain)
complex_conditional_space.add_hyperparameter(gloves)
complex_conditional_space.add_hyperparameter(heur1)
complex_conditional_space.add_hyperparameter(heur2)
complex_conditional_space.add_hyperparameter(heur_order)
complex_conditional_space.add_condition(gloves_condition)
complex_conditional_space.add_condition(heur_condition)
complex_conditional_space.add_condition(Cl_condition)
complex_conditional_space.add_condition(another_condition)
complex_cs = list()
complex_cs.append(
"classi ordinal {random_forest,extra_trees,k_nearest_neighbors, something} "
"[random_forest]"
)
complex_cs.append("knn_weights categorical {uniform, distance} [uniform]")
complex_cs.append("weather ordinal {sunny, rainy, cloudy, snowing} [sunny]")
complex_cs.append("temperature categorical {high, low} [high]")
complex_cs.append("rain categorical { yes, no } [yes]")
complex_cs.append("gloves ordinal { none, yarn, leather, gortex } [none]")
complex_cs.append("heur1 categorical { off, on } [off]")
complex_cs.append("heur2 categorical { off, on } [off]")
complex_cs.append("heur_order categorical { heur1then2, heur2then1 } [heur1then2]")
complex_cs.append("gloves | rain == yes || temperature == low")
complex_cs.append("heur_order | heur1 == on && heur2 == on")
complex_cs.append("knn_weights | classi == k_nearest_neighbors || "
"classi != extra_trees && classi == random_forest || classi == something")
complex_cs.append("temperature | weather == rainy && weather == cloudy || "
"weather == sunny && weather != snowing")
cs_new = pcs_new.read(complex_cs)
self.assertEqual(cs_new, complex_conditional_space)
def test_convert_restrictions(self):
# This is a smoke test to make sure that the int/float values in the
# greater or smaller statements are converted to the right type when
# reading them
s = """x1 real [0,1] [0]
x2 real [0,1] [0]
x3 real [0,1] [0]
x4 integer [0,2] [0]
x5 real [0,1] [0]
x6 ordinal {cold, luke-warm, hot} [cold]
x1 | x2 > 0.5
x3 | x4 > 1 && x4 == 2 && x4 in {2}
x5 | x6 > luke-warm"""
pcs_new.read(s.split('\n'))
def test_write_restrictions(self):
s = "c integer [0, 2] [0]\n" + \
"d ordinal {cold, luke-warm, hot} [cold]\n" + \
"e real [0.0, 1.0] [0.0]\n" + \
"b real [0.0, 1.0] [0.0]\n" + \
"a real [0.0, 1.0] [0.0]\n" + \
"\n" + \
"b | d in {luke-warm, hot} || c > 1\n" + \
"a | b == 0.5 && e > 0.5"
a = pcs_new.read(s.split('\n'))
out = pcs_new.write(a)
self.assertEqual(out, s)
def test_read_write(self):
# Some smoke tests whether reading, writing, reading alters makes the
# configspace incomparable
this_file = os.path.abspath(__file__)
this_directory = os.path.dirname(this_file)
configuration_space_path = os.path.join(this_directory,
"..", "test_searchspaces")
configuration_space_path = os.path.abspath(configuration_space_path)
configuration_space_path = os.path.join(configuration_space_path,
"spear-params-mixed.pcs")
with open(configuration_space_path) as fh:
cs = pcs.read(fh)
tf = tempfile.NamedTemporaryFile()
name = tf.name
tf.close()
with open(name, 'w') as fh:
pcs_string = pcs.write(cs)
fh.write(pcs_string)
with open(name, 'r') as fh:
pcs_new = pcs.read(fh)
self.assertEqual(pcs_new, cs, msg=(pcs_new, cs))
|
the-stack_0_8490 | import os
import sys
import uuid
import fileinput
import boto3
region = os.getenv('AWS_REGION')
tg = os.getenv('AWS_IOT_THING_NAME')
try:
mac_address = hex(uuid.getnode())
mac_address = mac_address[2:8] + 'fffe' + mac_address[8:]
print('the GatewayEui for the gateway will be', mac_address)
input_file = "./station.conf"
file_object = open( input_file, 'r+' )
for line in fileinput.input(input_file):
file_object.write(line.replace('"routerid": ""', f'"routerid": "{mac_address}"'))
file_object.close()
print('routerid configured in station.conf file')
if os.path.isfile('cups.crt'):
print('Found credentials in the folder, gateway provisioning step skipped')
exit(0)
lora_region = sys.argv[1]
print('Lora region for the gateway:', lora_region)
print('AWS region:', region)
print('ThingName used for the name of the gateway:', tg)
iot = boto3.client('iot', region_name= region)
iotw = boto3.client('iotwireless', region_name= region)
gateway = None
try:
gateway = iotw.get_wireless_gateway(
Identifier= mac_address,
IdentifierType= 'GatewayEui'
)
except iotw.exceptions.from_code('ResourceNotFoundException'):
gateway = iotw.create_wireless_gateway(
Name= tg,
Description=f'The LoRaWAN Gateway {tg} has been registered using an AWS IoT Greengrass component',
LoRaWAN={
'GatewayEui': mac_address,
'RfRegion': lora_region
}
)
except Exception as e:
print(e)
exit(1)
# if the gateway is not created, raise an error
if gateway.get('Id') == None:
raise ValueError('Error when provisioning the gateway')
certs = iot.create_keys_and_certificate(
setAsActive=True
)
cups= iotw.get_service_endpoint(ServiceType = 'CUPS')
with open('cups.uri', 'w') as f:
f.write(cups['ServiceEndpoint'])
with open('cups.trust', 'w') as f:
f.write(cups['ServerTrust'])
cert_id= certs['certificateId']
with open('cups.crt', 'w') as f:
f.write(certs['certificatePem'])
with open('cups.key', 'w') as f:
f.write(certs['keyPair']['PrivateKey'])
associate_gateway = iotw.associate_wireless_gateway_with_certificate(
Id= gateway['Id'],
IotCertificateId= certs['certificateId']
)
print(f"The certificate {certs.get('certificateId')} has been associated with the gateway {tg}")
except Exception as e:
print(e)
exit(1) |
the-stack_0_8491 | import csv
import math
import re
import argparse
import random
def calculate_quota(num_winners, num_votes):
return math.floor(num_votes * (1.0 / (1 + num_winners)))
class Candidate:
""" A model for representing vote counts.
Args:
name: String key for the candidate.
ballots: A 2D array where each element is a string list of candidate
names sorted in preferences order.
"""
def __init__(self, name, ballots):
self.__name = name
self.__votes = 10_000 * len(ballots)
self.__ballots = ballots
@property
def votes(self):
return self.__votes
@property
def name(self):
return self.__name
@property
def ballots(self):
return self.__ballots
def surplus_for_candidate(self, starting_votes, surplus, candidate_name):
surplus_per_vote = surplus / len(self.ballots)
votes_for_candidate = sum(
[1 for b in self.__ballots if len(b) > 0 and b[0] == candidate_name])
result = math.ceil(votes_for_candidate * surplus_per_vote)
self.__votes -= result
return result
def exhausted_ballots(self, surplus):
surplus_per_vote = surplus / (self.votes) * 10_000
exhausted_votes = sum([1 for b in self.__ballots if len(b) == 0])
result = math.ceil(exhausted_votes * surplus_per_vote)
self.__votes -= result
return result
def add_surplus(self, surplus):
self.__votes += math.floor(surplus)
def surplus(self, quota):
return max(self.__votes - quota, 0.0)
def add_ballot(self, new_ballot, votes_per_ballot):
self.__ballots.append(new_ballot)
self.__votes += math.floor(votes_per_ballot)
def drop_candidate(self, candidate):
for b in self.__ballots:
if(candidate.name in b):
b.remove(candidate.name)
def __repr__(self):
return str(self)
def __str__(self):
return f"{{name: {self.name}, votes: {self.__votes}}}"
def __lt__(self, other):
return self.votes < other.votes
def __eq__(self, other):
return other is Candidate and self.name == other.name
def award_first_pref(candidate_names, ballot_data):
""" Generates a list of candidates with their approriate 1st round votes
and ballot data.
Returns:
list of Candidates.
"""
num_choices = len(ballot_data)
FIRST = "1"
choices = [str(n) for n in range(2, num_choices)]
ballots = {c: [] for c in candidate_names}
for row in ballot_data:
key = candidate_names[row.index(FIRST)]
value = ballots[key]
ballots[key] = [
*value, [candidate_names[row.index(choice)] for choice in choices if choice in row]]
candidates = [Candidate(name=k, ballots=v) for (k, v) in ballots.items()]
random.shuffle(candidates)
return candidates
def find_winners(candidates, quota):
"""Returns candidates that have met the quota."""
return [c for c in candidates if c.votes >= quota]
def distribute_surplus(candidates, exhausted, quota):
"""
Returns the given list of Candidates with the surplus votes from the
Candidate with the most surpluss votes transfered to their next
preference.
"""
max_surplus = max([c.surplus(quota) for c in candidates])
biggest_winners = [c for c in candidates if c.surplus(quota) == max_surplus]
winner = biggest_winners[0]
candidates.remove(winner)
surplus = winner.surplus(quota)
starting_votes = winner.votes
for c in candidates:
c.drop_candidate(winner)
c.add_surplus(winner.surplus_for_candidate(starting_votes, surplus, c.name))
exhausted.add_surplus(winner.exhausted_ballots(surplus))
return candidates
def redisitribute_loser(candidates, exhausted):
"""
Returns: A list of Candidates with the lowest vote
getting Canidate removed
"""
fewest_votes = min(candidates).votes
biggest_losers = [c for c in candidates if c.votes == fewest_votes]
eliminated = biggest_losers[-1]
candidates.remove(eliminated)
starting_votes = eliminated.votes
for b in eliminated.ballots:
next_choice = b[0] if len(b) > 0 else None
if(next_choice == None):
exhausted.add_ballot(b, eliminated.votes)
for c in candidates:
c.drop_candidate(eliminated)
if c.name == next_choice:
c.add_ballot(b[1:], starting_votes / len(eliminated.ballots))
return candidates
def parse_vote_data(csv_data):
""" Retrieves candidate names from the input file, cleans ballots rows
such that contain only the numeric ranked preference number. This
function also discards invalid ballots.
Returns: A String[] of names, and a String[][] where each row is a String[]
representating a ballot. Each row item is a stringified integer
representing the index of the corresponding candidate in the candidates
array, or an empty string if the ballot does not rank all candidates.
"""
def valid(ballot, num_candidates):
prefs = [int(p) for p in ballot if p]
if(len(prefs) == 0 or len(prefs) > num_candidates):
return False
return sorted(prefs) == list(range(1, len(prefs) + 1))
candidate_names = [n.strip() for n in next(csv_data)]
parsed_vote_data = []
for row in csv_data:
ballot = [re.sub(r"\D", "", c) for c in row]
if(valid(ballot, len(candidate_names))):
parsed_vote_data.append(ballot)
else:
print(f"❌ {ballot}")
return candidate_names, parsed_vote_data
def count_ballots(file_name, num_winners):
with open(file_name) as csv_file:
csv_data = csv.reader(csv_file, delimiter=',')
candidate_names, vote_data = parse_vote_data(csv_data)
candidates_to_votes = award_first_pref(candidate_names, vote_data)
round_num = 1
exhausted = Candidate("Exhausted", [])
winners = []
while True:
num_votes = sum([c.votes for c in candidates_to_votes])
quota = calculate_quota(num_winners, num_votes)
candidates_to_votes.sort(reverse=True)
# Print stats
print(f"Round {round_num}:")
for w in winners:
print(f"🏆: {w}")
print(f"Votes: {num_votes + exhausted.votes + sum([w.votes for w in winners])}")
print(f"Quota to win: {quota}")
for c in candidates_to_votes:
print(f" {c.name}: {c.votes}")
print(f" Exhausted: {exhausted.votes}")
# Update winners
round_winners = find_winners(candidates_to_votes, quota)
for w in round_winners:
winners.append(w)
if(len(winners) >= num_winners):
return winners[:num_winners], exhausted
elif(sum([w.surplus(quota) for w in round_winners]) > 0.0):
candidates_to_votes = distribute_surplus(
candidates_to_votes, exhausted, quota)
else:
candidates_to_votes = redisitribute_loser(
candidates_to_votes, exhausted)
round_num += 1
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Administer election.')
parser.add_argument('-f', '--file', action='store', type=str,
help='Name of the election results file')
parser.add_argument('-n', '--num_winners', action='store',
type=int, default=1, help='Number of winners to pick')
args = parser.parse_args()
winners, exhausted = count_ballots(args.file, num_winners=args.num_winners)
print("")
for w in winners:
print(f"🏆: {w}")
print(f"exhausted votes {exhausted.votes}")
|
the-stack_0_8492 | class Student(object):
"""This is a Superclass
It holds holds the total number of students
"""
counter = 0
def __init__(self):
type(self).counter += 1
def __del__(self):
type(self).counter -= 1
def student_stream(self):
"""data encapsulation: color can not be accessed by another class
Abstraction: checks the color if it valid
"""
if self._color == "yelow":
stream = "North"
elif self._color == "pink":
strem = "South"
elif self._color == "red":
stream = "East"
else:
stream = "Invalid stream"
return stream
class Students(Student):
"""Subclass of Student_counter: it inherits methods from Student_counter
It holds student details
"""
def __init__(self, name, school_id, fees_paid, student_class, color):
self.name = name
self.school_id = school_id
self.fees_paid = fees_paid
self.student_class = student_class
self._color = color
Student.__init__(self)
if self.student_class == 4:
self.__fees = 5000
elif student_class == 3:
self.__fees = 4000
elif student_class == 2:
self.__fees = 37122
else:
self.__fees = 56000
def fees_arrears(self):
balance = self.__fees - self.fees_paid
return balance
class Studentsubjects(Student):
"""Subclass of Student_counter: it inherits methods from Student_counter
It holds student details
"""
def __init__(self, name, color):
self.name = name
self._color = color
Student.__init__(self)
def student_stream(self):
"""data encapsulation: color can not be accessed by another class
Abstraction: checks the color if it valid
Polymophism: using the same method to return different outputs
"""
if self._color == "yelow":
stream = "Geography"
elif self._color == "pink":
stream = "Music"
elif self._color == "red":
stream = "Agriculture"
else:
stream = "Invalid stream"
return stream
|
the-stack_0_8493 |
from unittest import TestCase
from unittest import mock
from multiphase.multiphase import Multiphase
class MultiphaseTests(TestCase):
"""
Test Multiphase.
"""
def setUp(self):
self.app = Multiphase()
def test_run(self):
"""
Test the run code.
"""
args = []
if self.app.TYPE == 'ds':
args.append('inputdir') # you may want to change this inputdir mock
args.append('outputdir') # you may want to change this outputdir mock
# you may want to add more of your custom defined optional arguments to test
# your app with
# eg.
# args.append('--custom-int')
# args.append(10)
options = self.app.parse_args(args)
self.app.run(options)
# write your own assertions
self.assertEqual(options.outputdir, 'outputdir')
|
the-stack_0_8494 | """
Data structure for 1-dimensional cross-sectional and time series data
"""
from io import StringIO
from shutil import get_terminal_size
from textwrap import dedent
from typing import (
IO,
TYPE_CHECKING,
Any,
Callable,
Iterable,
List,
Optional,
Tuple,
Type,
Union,
)
import warnings
import numpy as np
from pandas._config import get_option
from pandas._libs import lib, properties, reshape, tslibs
from pandas._libs.lib import no_default
from pandas._typing import (
ArrayLike,
Axis,
DtypeObj,
FrameOrSeriesUnion,
IndexKeyFunc,
Label,
ValueKeyFunc,
)
from pandas.compat.numpy import function as nv
from pandas.errors import InvalidIndexError
from pandas.util._decorators import Appender, Substitution, doc
from pandas.util._validators import validate_bool_kwarg, validate_percentile
from pandas.core.dtypes.cast import (
convert_dtypes,
maybe_cast_to_extension_array,
validate_numeric_casting,
)
from pandas.core.dtypes.common import (
ensure_platform_int,
is_bool,
is_categorical_dtype,
is_dict_like,
is_extension_array_dtype,
is_integer,
is_iterator,
is_list_like,
is_object_dtype,
is_scalar,
)
from pandas.core.dtypes.generic import ABCDataFrame
from pandas.core.dtypes.inference import is_hashable
from pandas.core.dtypes.missing import (
isna,
na_value_for_dtype,
notna,
remove_na_arraylike,
)
import pandas as pd
from pandas.core import algorithms, base, generic, nanops, ops
from pandas.core.accessor import CachedAccessor
from pandas.core.arrays import ExtensionArray
from pandas.core.arrays.categorical import CategoricalAccessor
from pandas.core.arrays.sparse import SparseAccessor
import pandas.core.common as com
from pandas.core.construction import (
create_series_with_explicit_dtype,
extract_array,
is_empty_data,
sanitize_array,
)
from pandas.core.generic import NDFrame
from pandas.core.indexers import deprecate_ndim_indexing, unpack_1tuple
from pandas.core.indexes.accessors import CombinedDatetimelikeProperties
from pandas.core.indexes.api import Float64Index, Index, MultiIndex, ensure_index
import pandas.core.indexes.base as ibase
from pandas.core.indexes.datetimes import DatetimeIndex
from pandas.core.indexes.period import PeriodIndex
from pandas.core.indexes.timedeltas import TimedeltaIndex
from pandas.core.indexing import check_bool_indexer
from pandas.core.internals import SingleBlockManager
from pandas.core.sorting import ensure_key_mapped
from pandas.core.strings import StringMethods
from pandas.core.tools.datetimes import to_datetime
import pandas.io.formats.format as fmt
import pandas.plotting
if TYPE_CHECKING:
from pandas.core.frame import DataFrame
from pandas.core.groupby.generic import SeriesGroupBy
__all__ = ["Series"]
_shared_doc_kwargs = dict(
axes="index",
klass="Series",
axes_single_arg="{0 or 'index'}",
axis="""axis : {0 or 'index'}
Parameter needed for compatibility with DataFrame.""",
inplace="""inplace : boolean, default False
If True, performs operation inplace and returns None.""",
unique="np.ndarray",
duplicated="Series",
optional_by="",
optional_mapper="",
optional_labels="",
optional_axis="",
versionadded_to_excel="\n .. versionadded:: 0.20.0\n",
)
def _coerce_method(converter):
"""
Install the scalar coercion methods.
"""
def wrapper(self):
if len(self) == 1:
return converter(self.iloc[0])
raise TypeError(f"cannot convert the series to {converter}")
wrapper.__name__ = f"__{converter.__name__}__"
return wrapper
# ----------------------------------------------------------------------
# Series class
class Series(base.IndexOpsMixin, generic.NDFrame):
"""
One-dimensional ndarray with axis labels (including time series).
Labels need not be unique but must be a hashable type. The object
supports both integer- and label-based indexing and provides a host of
methods for performing operations involving the index. Statistical
methods from ndarray have been overridden to automatically exclude
missing data (currently represented as NaN).
Operations between Series (+, -, /, *, **) align values based on their
associated index values-- they need not be the same length. The result
index will be the sorted union of the two indexes.
Parameters
----------
data : array-like, Iterable, dict, or scalar value
Contains data stored in Series.
.. versionchanged:: 0.23.0
If data is a dict, argument order is maintained for Python 3.6
and later.
index : array-like or Index (1d)
Values must be hashable and have the same length as `data`.
Non-unique index values are allowed. Will default to
RangeIndex (0, 1, 2, ..., n) if not provided. If both a dict and index
sequence are used, the index will override the keys found in the
dict.
dtype : str, numpy.dtype, or ExtensionDtype, optional
Data type for the output Series. If not specified, this will be
inferred from `data`.
See the :ref:`user guide <basics.dtypes>` for more usages.
name : str, optional
The name to give to the Series.
copy : bool, default False
Copy input data.
"""
_typ = "series"
_name: Label
_metadata: List[str] = ["name"]
_internal_names_set = {"index"} | generic.NDFrame._internal_names_set
_accessors = {"dt", "cat", "str", "sparse"}
_deprecations = (
base.IndexOpsMixin._deprecations
| generic.NDFrame._deprecations
| frozenset(["compress", "ptp"])
)
# Override cache_readonly bc Series is mutable
hasnans = property(
base.IndexOpsMixin.hasnans.func, doc=base.IndexOpsMixin.hasnans.__doc__
)
_mgr: SingleBlockManager
div: Callable[["Series", Any], "Series"]
rdiv: Callable[["Series", Any], "Series"]
# ----------------------------------------------------------------------
# Constructors
def __init__(
self, data=None, index=None, dtype=None, name=None, copy=False, fastpath=False
):
if (
isinstance(data, SingleBlockManager)
and index is None
and dtype is None
and copy is False
):
# GH#33357 called with just the SingleBlockManager
NDFrame.__init__(self, data)
self.name = name
return
# we are called internally, so short-circuit
if fastpath:
# data is an ndarray, index is defined
if not isinstance(data, SingleBlockManager):
data = SingleBlockManager.from_array(data, index)
if copy:
data = data.copy()
if index is None:
index = data.index
else:
name = ibase.maybe_extract_name(name, data, type(self))
if is_empty_data(data) and dtype is None:
# gh-17261
warnings.warn(
"The default dtype for empty Series will be 'object' instead "
"of 'float64' in a future version. Specify a dtype explicitly "
"to silence this warning.",
DeprecationWarning,
stacklevel=2,
)
# uncomment the line below when removing the DeprecationWarning
# dtype = np.dtype(object)
if index is not None:
index = ensure_index(index)
if data is None:
data = {}
if dtype is not None:
dtype = self._validate_dtype(dtype)
if isinstance(data, MultiIndex):
raise NotImplementedError(
"initializing a Series from a MultiIndex is not supported"
)
elif isinstance(data, Index):
if dtype is not None:
# astype copies
data = data.astype(dtype)
else:
# GH#24096 we need to ensure the index remains immutable
data = data._values.copy()
copy = False
elif isinstance(data, np.ndarray):
if len(data.dtype):
# GH#13296 we are dealing with a compound dtype, which
# should be treated as 2D
raise ValueError(
"Cannot construct a Series from an ndarray with "
"compound dtype. Use DataFrame instead."
)
elif isinstance(data, Series):
if index is None:
index = data.index
else:
data = data.reindex(index, copy=copy)
copy = False
data = data._mgr
elif is_dict_like(data):
data, index = self._init_dict(data, index, dtype)
dtype = None
copy = False
elif isinstance(data, SingleBlockManager):
if index is None:
index = data.index
elif not data.index.equals(index) or copy:
# GH#19275 SingleBlockManager input should only be called
# internally
raise AssertionError(
"Cannot pass both SingleBlockManager "
"`data` argument and a different "
"`index` argument. `copy` must be False."
)
elif is_extension_array_dtype(data):
pass
elif isinstance(data, (set, frozenset)):
raise TypeError(f"'{type(data).__name__}' type is unordered")
else:
data = com.maybe_iterable_to_list(data)
if index is None:
if not is_list_like(data):
data = [data]
index = ibase.default_index(len(data))
elif is_list_like(data):
# a scalar numpy array is list-like but doesn't
# have a proper length
try:
if len(index) != len(data):
raise ValueError(
f"Length of passed values is {len(data)}, "
f"index implies {len(index)}."
)
except TypeError:
pass
# create/copy the manager
if isinstance(data, SingleBlockManager):
if dtype is not None:
data = data.astype(dtype=dtype, errors="ignore", copy=copy)
elif copy:
data = data.copy()
else:
data = sanitize_array(data, index, dtype, copy, raise_cast_failure=True)
data = SingleBlockManager.from_array(data, index)
generic.NDFrame.__init__(self, data)
self.name = name
self._set_axis(0, index, fastpath=True)
def _init_dict(self, data, index=None, dtype=None):
"""
Derive the "_mgr" and "index" attributes of a new Series from a
dictionary input.
Parameters
----------
data : dict or dict-like
Data used to populate the new Series.
index : Index or index-like, default None
Index for the new Series: if None, use dict keys.
dtype : dtype, default None
The dtype for the new Series: if None, infer from data.
Returns
-------
_data : BlockManager for the new Series
index : index for the new Series
"""
# Looking for NaN in dict doesn't work ({np.nan : 1}[float('nan')]
# raises KeyError), so we iterate the entire dict, and align
if data:
keys, values = zip(*data.items())
values = list(values)
elif index is not None:
# fastpath for Series(data=None). Just use broadcasting a scalar
# instead of reindexing.
values = na_value_for_dtype(dtype)
keys = index
else:
keys, values = [], []
# Input is now list-like, so rely on "standard" construction:
# TODO: passing np.float64 to not break anything yet. See GH-17261
s = create_series_with_explicit_dtype(
values, index=keys, dtype=dtype, dtype_if_empty=np.float64
)
# Now we just make sure the order is respected, if any
if data and index is not None:
s = s.reindex(index, copy=False)
return s._mgr, s.index
# ----------------------------------------------------------------------
@property
def _constructor(self) -> Type["Series"]:
return Series
@property
def _constructor_expanddim(self) -> Type["DataFrame"]:
from pandas.core.frame import DataFrame
return DataFrame
# types
@property
def _can_hold_na(self):
return self._mgr._can_hold_na
_index = None
def _set_axis(self, axis: int, labels, fastpath: bool = False) -> None:
"""
Override generic, we want to set the _typ here.
This is called from the cython code when we set the `index` attribute
directly, e.g. `series.index = [1, 2, 3]`.
"""
if not fastpath:
labels = ensure_index(labels)
is_all_dates = labels.is_all_dates
if is_all_dates:
if not isinstance(labels, (DatetimeIndex, PeriodIndex, TimedeltaIndex)):
try:
labels = DatetimeIndex(labels)
# need to set here because we changed the index
if fastpath:
self._mgr.set_axis(axis, labels)
except (tslibs.OutOfBoundsDatetime, ValueError):
# labels may exceeds datetime bounds,
# or not be a DatetimeIndex
pass
object.__setattr__(self, "_index", labels)
if not fastpath:
# The ensure_index call above ensures we have an Index object
self._mgr.set_axis(axis, labels)
# ndarray compatibility
@property
def dtype(self) -> DtypeObj:
"""
Return the dtype object of the underlying data.
"""
return self._mgr.dtype
@property
def dtypes(self) -> DtypeObj:
"""
Return the dtype object of the underlying data.
"""
# DataFrame compatibility
return self.dtype
@property
def name(self) -> Label:
"""
Return the name of the Series.
The name of a Series becomes its index or column name if it is used
to form a DataFrame. It is also used whenever displaying the Series
using the interpreter.
Returns
-------
label (hashable object)
The name of the Series, also the column name if part of a DataFrame.
See Also
--------
Series.rename : Sets the Series name when given a scalar input.
Index.name : Corresponding Index property.
Examples
--------
The Series name can be set initially when calling the constructor.
>>> s = pd.Series([1, 2, 3], dtype=np.int64, name='Numbers')
>>> s
0 1
1 2
2 3
Name: Numbers, dtype: int64
>>> s.name = "Integers"
>>> s
0 1
1 2
2 3
Name: Integers, dtype: int64
The name of a Series within a DataFrame is its column name.
>>> df = pd.DataFrame([[1, 2], [3, 4], [5, 6]],
... columns=["Odd Numbers", "Even Numbers"])
>>> df
Odd Numbers Even Numbers
0 1 2
1 3 4
2 5 6
>>> df["Even Numbers"].name
'Even Numbers'
"""
return self._name
@name.setter
def name(self, value: Label) -> None:
if not is_hashable(value):
raise TypeError("Series.name must be a hashable type")
object.__setattr__(self, "_name", value)
@property
def values(self):
"""
Return Series as ndarray or ndarray-like depending on the dtype.
.. warning::
We recommend using :attr:`Series.array` or
:meth:`Series.to_numpy`, depending on whether you need
a reference to the underlying data or a NumPy array.
Returns
-------
numpy.ndarray or ndarray-like
See Also
--------
Series.array : Reference to the underlying data.
Series.to_numpy : A NumPy array representing the underlying data.
Examples
--------
>>> pd.Series([1, 2, 3]).values
array([1, 2, 3])
>>> pd.Series(list('aabc')).values
array(['a', 'a', 'b', 'c'], dtype=object)
>>> pd.Series(list('aabc')).astype('category').values
['a', 'a', 'b', 'c']
Categories (3, object): ['a', 'b', 'c']
Timezone aware datetime data is converted to UTC:
>>> pd.Series(pd.date_range('20130101', periods=3,
... tz='US/Eastern')).values
array(['2013-01-01T05:00:00.000000000',
'2013-01-02T05:00:00.000000000',
'2013-01-03T05:00:00.000000000'], dtype='datetime64[ns]')
"""
return self._mgr.external_values()
@property
def _values(self):
"""
Return the internal repr of this data (defined by Block.interval_values).
This are the values as stored in the Block (ndarray or ExtensionArray
depending on the Block class), with datetime64[ns] and timedelta64[ns]
wrapped in ExtensionArrays to match Index._values behavior.
Differs from the public ``.values`` for certain data types, because of
historical backwards compatibility of the public attribute (e.g. period
returns object ndarray and datetimetz a datetime64[ns] ndarray for
``.values`` while it returns an ExtensionArray for ``._values`` in those
cases).
Differs from ``.array`` in that this still returns the numpy array if
the Block is backed by a numpy array (except for datetime64 and
timedelta64 dtypes), while ``.array`` ensures to always return an
ExtensionArray.
Overview:
dtype | values | _values | array |
----------- | ------------- | ------------- | ------------- |
Numeric | ndarray | ndarray | PandasArray |
Category | Categorical | Categorical | Categorical |
dt64[ns] | ndarray[M8ns] | DatetimeArray | DatetimeArray |
dt64[ns tz] | ndarray[M8ns] | DatetimeArray | DatetimeArray |
td64[ns] | ndarray[m8ns] | TimedeltaArray| ndarray[m8ns] |
Period | ndarray[obj] | PeriodArray | PeriodArray |
Nullable | EA | EA | EA |
"""
return self._mgr.internal_values()
@Appender(base.IndexOpsMixin.array.__doc__) # type: ignore
@property
def array(self) -> ExtensionArray:
return self._mgr._block.array_values()
# ops
def ravel(self, order="C"):
"""
Return the flattened underlying data as an ndarray.
Returns
-------
numpy.ndarray or ndarray-like
Flattened data of the Series.
See Also
--------
numpy.ndarray.ravel : Return a flattened array.
"""
return self._values.ravel(order=order)
def __len__(self) -> int:
"""
Return the length of the Series.
"""
return len(self._mgr)
def view(self, dtype=None) -> "Series":
"""
Create a new view of the Series.
This function will return a new Series with a view of the same
underlying values in memory, optionally reinterpreted with a new data
type. The new data type must preserve the same size in bytes as to not
cause index misalignment.
Parameters
----------
dtype : data type
Data type object or one of their string representations.
Returns
-------
Series
A new Series object as a view of the same data in memory.
See Also
--------
numpy.ndarray.view : Equivalent numpy function to create a new view of
the same data in memory.
Notes
-----
Series are instantiated with ``dtype=float64`` by default. While
``numpy.ndarray.view()`` will return a view with the same data type as
the original array, ``Series.view()`` (without specified dtype)
will try using ``float64`` and may fail if the original data type size
in bytes is not the same.
Examples
--------
>>> s = pd.Series([-2, -1, 0, 1, 2], dtype='int8')
>>> s
0 -2
1 -1
2 0
3 1
4 2
dtype: int8
The 8 bit signed integer representation of `-1` is `0b11111111`, but
the same bytes represent 255 if read as an 8 bit unsigned integer:
>>> us = s.view('uint8')
>>> us
0 254
1 255
2 0
3 1
4 2
dtype: uint8
The views share the same underlying values:
>>> us[0] = 128
>>> s
0 -128
1 -1
2 0
3 1
4 2
dtype: int8
"""
return self._constructor(
self._values.view(dtype), index=self.index
).__finalize__(self, method="view")
# ----------------------------------------------------------------------
# NDArray Compat
_HANDLED_TYPES = (Index, ExtensionArray, np.ndarray)
def __array_ufunc__(
self, ufunc: Callable, method: str, *inputs: Any, **kwargs: Any
):
# TODO: handle DataFrame
cls = type(self)
# for binary ops, use our custom dunder methods
result = ops.maybe_dispatch_ufunc_to_dunder_op(
self, ufunc, method, *inputs, **kwargs
)
if result is not NotImplemented:
return result
# Determine if we should defer.
no_defer = (np.ndarray.__array_ufunc__, cls.__array_ufunc__)
for item in inputs:
higher_priority = (
hasattr(item, "__array_priority__")
and item.__array_priority__ > self.__array_priority__
)
has_array_ufunc = (
hasattr(item, "__array_ufunc__")
and type(item).__array_ufunc__ not in no_defer
and not isinstance(item, self._HANDLED_TYPES)
)
if higher_priority or has_array_ufunc:
return NotImplemented
# align all the inputs.
names = [getattr(x, "name") for x in inputs if hasattr(x, "name")]
types = tuple(type(x) for x in inputs)
# TODO: dataframe
alignable = [x for x, t in zip(inputs, types) if issubclass(t, Series)]
if len(alignable) > 1:
# This triggers alignment.
# At the moment, there aren't any ufuncs with more than two inputs
# so this ends up just being x1.index | x2.index, but we write
# it to handle *args.
index = alignable[0].index
for s in alignable[1:]:
index |= s.index
inputs = tuple(
x.reindex(index) if issubclass(t, Series) else x
for x, t in zip(inputs, types)
)
else:
index = self.index
inputs = tuple(extract_array(x, extract_numpy=True) for x in inputs)
result = getattr(ufunc, method)(*inputs, **kwargs)
name = names[0] if len(set(names)) == 1 else None
def construct_return(result):
if lib.is_scalar(result):
return result
elif result.ndim > 1:
# e.g. np.subtract.outer
if method == "outer":
# GH#27198
raise NotImplementedError
return result
return self._constructor(result, index=index, name=name, copy=False)
if type(result) is tuple:
# multiple return values
return tuple(construct_return(x) for x in result)
elif method == "at":
# no return value
return None
else:
return construct_return(result)
def __array__(self, dtype=None) -> np.ndarray:
"""
Return the values as a NumPy array.
Users should not call this directly. Rather, it is invoked by
:func:`numpy.array` and :func:`numpy.asarray`.
Parameters
----------
dtype : str or numpy.dtype, optional
The dtype to use for the resulting NumPy array. By default,
the dtype is inferred from the data.
Returns
-------
numpy.ndarray
The values in the series converted to a :class:`numpy.ndarray`
with the specified `dtype`.
See Also
--------
array : Create a new array from data.
Series.array : Zero-copy view to the array backing the Series.
Series.to_numpy : Series method for similar behavior.
Examples
--------
>>> ser = pd.Series([1, 2, 3])
>>> np.asarray(ser)
array([1, 2, 3])
For timezone-aware data, the timezones may be retained with
``dtype='object'``
>>> tzser = pd.Series(pd.date_range('2000', periods=2, tz="CET"))
>>> np.asarray(tzser, dtype="object")
array([Timestamp('2000-01-01 00:00:00+0100', tz='CET', freq='D'),
Timestamp('2000-01-02 00:00:00+0100', tz='CET', freq='D')],
dtype=object)
Or the values may be localized to UTC and the tzinfo discarded with
``dtype='datetime64[ns]'``
>>> np.asarray(tzser, dtype="datetime64[ns]") # doctest: +ELLIPSIS
array(['1999-12-31T23:00:00.000000000', ...],
dtype='datetime64[ns]')
"""
return np.asarray(self.array, dtype)
# ----------------------------------------------------------------------
# Unary Methods
# coercion
__float__ = _coerce_method(float)
__long__ = _coerce_method(int)
__int__ = _coerce_method(int)
# ----------------------------------------------------------------------
# indexers
@property
def axes(self) -> List[Index]:
"""
Return a list of the row axis labels.
"""
return [self.index]
# ----------------------------------------------------------------------
# Indexing Methods
@Appender(generic.NDFrame.take.__doc__)
def take(self, indices, axis=0, is_copy=None, **kwargs) -> "Series":
if is_copy is not None:
warnings.warn(
"is_copy is deprecated and will be removed in a future version. "
"'take' always returns a copy, so there is no need to specify this.",
FutureWarning,
stacklevel=2,
)
nv.validate_take(tuple(), kwargs)
indices = ensure_platform_int(indices)
new_index = self.index.take(indices)
new_values = self._values.take(indices)
result = self._constructor(new_values, index=new_index, fastpath=True)
return result.__finalize__(self, method="take")
def _take_with_is_copy(self, indices, axis=0):
"""
Internal version of the `take` method that sets the `_is_copy`
attribute to keep track of the parent dataframe (using in indexing
for the SettingWithCopyWarning). For Series this does the same
as the public take (it never sets `_is_copy`).
See the docstring of `take` for full explanation of the parameters.
"""
return self.take(indices=indices, axis=axis)
def _ixs(self, i: int, axis: int = 0):
"""
Return the i-th value or values in the Series by location.
Parameters
----------
i : int
Returns
-------
scalar (int) or Series (slice, sequence)
"""
return self._values[i]
def _slice(self, slobj: slice, axis: int = 0) -> "Series":
# axis kwarg is retained for compat with NDFrame method
# _slice is *always* positional
return self._get_values(slobj)
def __getitem__(self, key):
key = com.apply_if_callable(key, self)
if key is Ellipsis:
return self
key_is_scalar = is_scalar(key)
if isinstance(key, (list, tuple)):
key = unpack_1tuple(key)
if is_integer(key) and self.index._should_fallback_to_positional():
return self._values[key]
elif key_is_scalar:
return self._get_value(key)
if is_hashable(key):
# Otherwise index.get_value will raise InvalidIndexError
try:
# For labels that don't resolve as scalars like tuples and frozensets
result = self._get_value(key)
return result
except (KeyError, TypeError):
if isinstance(key, tuple) and isinstance(self.index, MultiIndex):
# We still have the corner case where a tuple is a key
# in the first level of our MultiIndex
return self._get_values_tuple(key)
if is_iterator(key):
key = list(key)
if com.is_bool_indexer(key):
key = check_bool_indexer(self.index, key)
key = np.asarray(key, dtype=bool)
return self._get_values(key)
return self._get_with(key)
def _get_with(self, key):
# other: fancy integer or otherwise
if isinstance(key, slice):
# _convert_slice_indexer to determine if this slice is positional
# or label based, and if the latter, convert to positional
slobj = self.index._convert_slice_indexer(key, kind="getitem")
return self._slice(slobj)
elif isinstance(key, ABCDataFrame):
raise TypeError(
"Indexing a Series with DataFrame is not "
"supported, use the appropriate DataFrame column"
)
elif isinstance(key, tuple):
return self._get_values_tuple(key)
elif not is_list_like(key):
# e.g. scalars that aren't recognized by lib.is_scalar, GH#32684
return self.loc[key]
if not isinstance(key, (list, np.ndarray, ExtensionArray, Series, Index)):
key = list(key)
if isinstance(key, Index):
key_type = key.inferred_type
else:
key_type = lib.infer_dtype(key, skipna=False)
# Note: The key_type == "boolean" case should be caught by the
# com.is_bool_indexer check in __getitem__
if key_type == "integer":
# We need to decide whether to treat this as a positional indexer
# (i.e. self.iloc) or label-based (i.e. self.loc)
if not self.index._should_fallback_to_positional():
return self.loc[key]
else:
return self.iloc[key]
# handle the dup indexing case GH#4246
return self.loc[key]
def _get_values_tuple(self, key):
# mpl hackaround
if com.any_none(*key):
result = self._get_values(key)
deprecate_ndim_indexing(result, stacklevel=5)
return result
if not isinstance(self.index, MultiIndex):
raise KeyError("key of type tuple not found and not a MultiIndex")
# If key is contained, would have returned by now
indexer, new_index = self.index.get_loc_level(key)
return self._constructor(self._values[indexer], index=new_index).__finalize__(
self,
)
def _get_values(self, indexer):
try:
return self._constructor(self._mgr.get_slice(indexer)).__finalize__(self,)
except ValueError:
# mpl compat if we look up e.g. ser[:, np.newaxis];
# see tests.series.timeseries.test_mpl_compat_hack
# the asarray is needed to avoid returning a 2D DatetimeArray
return np.asarray(self._values)[indexer]
def _get_value(self, label, takeable: bool = False):
"""
Quickly retrieve single value at passed index label.
Parameters
----------
label : object
takeable : interpret the index as indexers, default False
Returns
-------
scalar value
"""
if takeable:
return self._values[label]
# Similar to Index.get_value, but we do not fall back to positional
loc = self.index.get_loc(label)
return self.index._get_values_for_loc(self, loc, label)
def __setitem__(self, key, value):
key = com.apply_if_callable(key, self)
cacher_needs_updating = self._check_is_chained_assignment_possible()
if key is Ellipsis:
key = slice(None)
try:
self._set_with_engine(key, value)
except (KeyError, ValueError):
values = self._values
if is_integer(key) and not self.index.inferred_type == "integer":
# positional setter
values[key] = value
else:
# GH#12862 adding an new key to the Series
self.loc[key] = value
except TypeError as err:
if isinstance(key, tuple) and not isinstance(self.index, MultiIndex):
raise KeyError(
"key of type tuple not found and not a MultiIndex"
) from err
if com.is_bool_indexer(key):
key = check_bool_indexer(self.index, key)
key = np.asarray(key, dtype=bool)
try:
self._where(~key, value, inplace=True)
except InvalidIndexError:
self.iloc[key] = value
return
else:
self._set_with(key, value)
if cacher_needs_updating:
self._maybe_update_cacher()
def _set_with_engine(self, key, value):
# fails with AttributeError for IntervalIndex
loc = self.index._engine.get_loc(key)
validate_numeric_casting(self.dtype, value)
self._values[loc] = value
def _set_with(self, key, value):
# other: fancy integer or otherwise
if isinstance(key, slice):
indexer = self.index._convert_slice_indexer(key, kind="getitem")
return self._set_values(indexer, value)
else:
assert not isinstance(key, tuple)
if is_scalar(key):
key = [key]
if isinstance(key, Index):
key_type = key.inferred_type
key = key._values
else:
key_type = lib.infer_dtype(key, skipna=False)
# Note: key_type == "boolean" should not occur because that
# should be caught by the is_bool_indexer check in __setitem__
if key_type == "integer":
if not self.index._should_fallback_to_positional():
self._set_labels(key, value)
else:
self._set_values(key, value)
else:
self.loc[key] = value
def _set_labels(self, key, value):
key = com.asarray_tuplesafe(key)
indexer: np.ndarray = self.index.get_indexer(key)
mask = indexer == -1
if mask.any():
raise KeyError(f"{key[mask]} not in index")
self._set_values(indexer, value)
def _set_values(self, key, value):
if isinstance(key, Series):
key = key._values
self._mgr = self._mgr.setitem(indexer=key, value=value)
self._maybe_update_cacher()
def _set_value(self, label, value, takeable: bool = False):
"""
Quickly set single value at passed label.
If label is not contained, a new object is created with the label
placed at the end of the result index.
Parameters
----------
label : object
Partial indexing with MultiIndex not allowed.
value : object
Scalar value.
takeable : interpret the index as indexers, default False
"""
try:
if takeable:
self._values[label] = value
else:
loc = self.index.get_loc(label)
validate_numeric_casting(self.dtype, value)
self._values[loc] = value
except KeyError:
# set using a non-recursive method
self.loc[label] = value
# ----------------------------------------------------------------------
# Unsorted
@property
def _is_mixed_type(self):
return False
def repeat(self, repeats, axis=None) -> "Series":
"""
Repeat elements of a Series.
Returns a new Series where each element of the current Series
is repeated consecutively a given number of times.
Parameters
----------
repeats : int or array of ints
The number of repetitions for each element. This should be a
non-negative integer. Repeating 0 times will return an empty
Series.
axis : None
Must be ``None``. Has no effect but is accepted for compatibility
with numpy.
Returns
-------
Series
Newly created Series with repeated elements.
See Also
--------
Index.repeat : Equivalent function for Index.
numpy.repeat : Similar method for :class:`numpy.ndarray`.
Examples
--------
>>> s = pd.Series(['a', 'b', 'c'])
>>> s
0 a
1 b
2 c
dtype: object
>>> s.repeat(2)
0 a
0 a
1 b
1 b
2 c
2 c
dtype: object
>>> s.repeat([1, 2, 3])
0 a
1 b
1 b
2 c
2 c
2 c
dtype: object
"""
nv.validate_repeat(tuple(), dict(axis=axis))
new_index = self.index.repeat(repeats)
new_values = self._values.repeat(repeats)
return self._constructor(new_values, index=new_index).__finalize__(
self, method="repeat"
)
def reset_index(self, level=None, drop=False, name=None, inplace=False):
"""
Generate a new DataFrame or Series with the index reset.
This is useful when the index needs to be treated as a column, or
when the index is meaningless and needs to be reset to the default
before another operation.
Parameters
----------
level : int, str, tuple, or list, default optional
For a Series with a MultiIndex, only remove the specified levels
from the index. Removes all levels by default.
drop : bool, default False
Just reset the index, without inserting it as a column in
the new DataFrame.
name : object, optional
The name to use for the column containing the original Series
values. Uses ``self.name`` by default. This argument is ignored
when `drop` is True.
inplace : bool, default False
Modify the Series in place (do not create a new object).
Returns
-------
Series or DataFrame
When `drop` is False (the default), a DataFrame is returned.
The newly created columns will come first in the DataFrame,
followed by the original Series values.
When `drop` is True, a `Series` is returned.
In either case, if ``inplace=True``, no value is returned.
See Also
--------
DataFrame.reset_index: Analogous function for DataFrame.
Examples
--------
>>> s = pd.Series([1, 2, 3, 4], name='foo',
... index=pd.Index(['a', 'b', 'c', 'd'], name='idx'))
Generate a DataFrame with default index.
>>> s.reset_index()
idx foo
0 a 1
1 b 2
2 c 3
3 d 4
To specify the name of the new column use `name`.
>>> s.reset_index(name='values')
idx values
0 a 1
1 b 2
2 c 3
3 d 4
To generate a new Series with the default set `drop` to True.
>>> s.reset_index(drop=True)
0 1
1 2
2 3
3 4
Name: foo, dtype: int64
To update the Series in place, without generating a new one
set `inplace` to True. Note that it also requires ``drop=True``.
>>> s.reset_index(inplace=True, drop=True)
>>> s
0 1
1 2
2 3
3 4
Name: foo, dtype: int64
The `level` parameter is interesting for Series with a multi-level
index.
>>> arrays = [np.array(['bar', 'bar', 'baz', 'baz']),
... np.array(['one', 'two', 'one', 'two'])]
>>> s2 = pd.Series(
... range(4), name='foo',
... index=pd.MultiIndex.from_arrays(arrays,
... names=['a', 'b']))
To remove a specific level from the Index, use `level`.
>>> s2.reset_index(level='a')
a foo
b
one bar 0
two bar 1
one baz 2
two baz 3
If `level` is not set, all levels are removed from the Index.
>>> s2.reset_index()
a b foo
0 bar one 0
1 bar two 1
2 baz one 2
3 baz two 3
"""
inplace = validate_bool_kwarg(inplace, "inplace")
if drop:
new_index = ibase.default_index(len(self))
if level is not None:
if not isinstance(level, (tuple, list)):
level = [level]
level = [self.index._get_level_number(lev) for lev in level]
if len(level) < self.index.nlevels:
new_index = self.index.droplevel(level)
if inplace:
self.index = new_index
# set name if it was passed, otherwise, keep the previous name
self.name = name or self.name
else:
return self._constructor(
self._values.copy(), index=new_index
).__finalize__(self, method="reset_index")
elif inplace:
raise TypeError(
"Cannot reset_index inplace on a Series to create a DataFrame"
)
else:
df = self.to_frame(name)
return df.reset_index(level=level, drop=drop)
# ----------------------------------------------------------------------
# Rendering Methods
def __repr__(self) -> str:
"""
Return a string representation for a particular Series.
"""
buf = StringIO("")
width, height = get_terminal_size()
max_rows = (
height
if get_option("display.max_rows") == 0
else get_option("display.max_rows")
)
min_rows = (
height
if get_option("display.max_rows") == 0
else get_option("display.min_rows")
)
show_dimensions = get_option("display.show_dimensions")
self.to_string(
buf=buf,
name=self.name,
dtype=self.dtype,
min_rows=min_rows,
max_rows=max_rows,
length=show_dimensions,
)
result = buf.getvalue()
return result
def to_string(
self,
buf=None,
na_rep="NaN",
float_format=None,
header=True,
index=True,
length=False,
dtype=False,
name=False,
max_rows=None,
min_rows=None,
):
"""
Render a string representation of the Series.
Parameters
----------
buf : StringIO-like, optional
Buffer to write to.
na_rep : str, optional
String representation of NaN to use, default 'NaN'.
float_format : one-parameter function, optional
Formatter function to apply to columns' elements if they are
floats, default None.
header : bool, default True
Add the Series header (index name).
index : bool, optional
Add index (row) labels, default True.
length : bool, default False
Add the Series length.
dtype : bool, default False
Add the Series dtype.
name : bool, default False
Add the Series name if not None.
max_rows : int, optional
Maximum number of rows to show before truncating. If None, show
all.
min_rows : int, optional
The number of rows to display in a truncated repr (when number
of rows is above `max_rows`).
Returns
-------
str or None
String representation of Series if ``buf=None``, otherwise None.
"""
formatter = fmt.SeriesFormatter(
self,
name=name,
length=length,
header=header,
index=index,
dtype=dtype,
na_rep=na_rep,
float_format=float_format,
min_rows=min_rows,
max_rows=max_rows,
)
result = formatter.to_string()
# catch contract violations
if not isinstance(result, str):
raise AssertionError(
"result must be of type str, type "
f"of result is {repr(type(result).__name__)}"
)
if buf is None:
return result
else:
try:
buf.write(result)
except AttributeError:
with open(buf, "w") as f:
f.write(result)
@doc(
klass=_shared_doc_kwargs["klass"],
examples=dedent(
"""
Examples
--------
>>> s = pd.Series(["elk", "pig", "dog", "quetzal"], name="animal")
>>> print(s.to_markdown())
| | animal |
|---:|:---------|
| 0 | elk |
| 1 | pig |
| 2 | dog |
| 3 | quetzal |
"""
),
)
def to_markdown(
self,
buf: Optional[IO[str]] = None,
mode: Optional[str] = None,
index: bool = True,
**kwargs,
) -> Optional[str]:
"""
Print {klass} in Markdown-friendly format.
.. versionadded:: 1.0.0
Parameters
----------
buf : str, Path or StringIO-like, optional, default None
Buffer to write to. If None, the output is returned as a string.
mode : str, optional
Mode in which file is opened.
index : bool, optional, default True
Add index (row) labels.
.. versionadded:: 1.1.0
**kwargs
These parameters will be passed to `tabulate \
<https://pypi.org/project/tabulate>`_.
Returns
-------
str
{klass} in Markdown-friendly format.
Examples
--------
>>> s = pd.Series(["elk", "pig", "dog", "quetzal"], name="animal")
>>> print(s.to_markdown())
| | animal |
|---:|:---------|
| 0 | elk |
| 1 | pig |
| 2 | dog |
| 3 | quetzal |
Output markdown with a tabulate option.
>>> print(s.to_markdown(tablefmt="grid"))
+----+----------+
| | animal |
+====+==========+
| 0 | elk |
+----+----------+
| 1 | pig |
+----+----------+
| 2 | dog |
+----+----------+
| 3 | quetzal |
+----+----------+
"""
return self.to_frame().to_markdown(buf, mode, index, **kwargs)
# ----------------------------------------------------------------------
def items(self) -> Iterable[Tuple[Label, Any]]:
"""
Lazily iterate over (index, value) tuples.
This method returns an iterable tuple (index, value). This is
convenient if you want to create a lazy iterator.
Returns
-------
iterable
Iterable of tuples containing the (index, value) pairs from a
Series.
See Also
--------
DataFrame.items : Iterate over (column name, Series) pairs.
DataFrame.iterrows : Iterate over DataFrame rows as (index, Series) pairs.
Examples
--------
>>> s = pd.Series(['A', 'B', 'C'])
>>> for index, value in s.items():
... print(f"Index : {index}, Value : {value}")
Index : 0, Value : A
Index : 1, Value : B
Index : 2, Value : C
"""
return zip(iter(self.index), iter(self))
@Appender(items.__doc__)
def iteritems(self) -> Iterable[Tuple[Label, Any]]:
return self.items()
# ----------------------------------------------------------------------
# Misc public methods
def keys(self) -> Index:
"""
Return alias for index.
Returns
-------
Index
Index of the Series.
"""
return self.index
def to_dict(self, into=dict):
"""
Convert Series to {label -> value} dict or dict-like object.
Parameters
----------
into : class, default dict
The collections.abc.Mapping subclass to use as the return
object. Can be the actual class or an empty
instance of the mapping type you want. If you want a
collections.defaultdict, you must pass it initialized.
Returns
-------
collections.abc.Mapping
Key-value representation of Series.
Examples
--------
>>> s = pd.Series([1, 2, 3, 4])
>>> s.to_dict()
{0: 1, 1: 2, 2: 3, 3: 4}
>>> from collections import OrderedDict, defaultdict
>>> s.to_dict(OrderedDict)
OrderedDict([(0, 1), (1, 2), (2, 3), (3, 4)])
>>> dd = defaultdict(list)
>>> s.to_dict(dd)
defaultdict(<class 'list'>, {0: 1, 1: 2, 2: 3, 3: 4})
"""
# GH16122
into_c = com.standardize_mapping(into)
return into_c(self.items())
def to_frame(self, name=None) -> "DataFrame":
"""
Convert Series to DataFrame.
Parameters
----------
name : object, default None
The passed name should substitute for the series name (if it has
one).
Returns
-------
DataFrame
DataFrame representation of Series.
Examples
--------
>>> s = pd.Series(["a", "b", "c"],
... name="vals")
>>> s.to_frame()
vals
0 a
1 b
2 c
"""
if name is None:
df = self._constructor_expanddim(self)
else:
df = self._constructor_expanddim({name: self})
return df
def _set_name(self, name, inplace=False) -> "Series":
"""
Set the Series name.
Parameters
----------
name : str
inplace : bool
Whether to modify `self` directly or return a copy.
"""
inplace = validate_bool_kwarg(inplace, "inplace")
ser = self if inplace else self.copy()
ser.name = name
return ser
@Appender(
"""
Examples
--------
>>> ser = pd.Series([390., 350., 30., 20.],
... index=['Falcon', 'Falcon', 'Parrot', 'Parrot'], name="Max Speed")
>>> ser
Falcon 390.0
Falcon 350.0
Parrot 30.0
Parrot 20.0
Name: Max Speed, dtype: float64
>>> ser.groupby(["a", "b", "a", "b"]).mean()
a 210.0
b 185.0
Name: Max Speed, dtype: float64
>>> ser.groupby(level=0).mean()
Falcon 370.0
Parrot 25.0
Name: Max Speed, dtype: float64
>>> ser.groupby(ser > 100).mean()
Max Speed
False 25.0
True 370.0
Name: Max Speed, dtype: float64
**Grouping by Indexes**
We can groupby different levels of a hierarchical index
using the `level` parameter:
>>> arrays = [['Falcon', 'Falcon', 'Parrot', 'Parrot'],
... ['Captive', 'Wild', 'Captive', 'Wild']]
>>> index = pd.MultiIndex.from_arrays(arrays, names=('Animal', 'Type'))
>>> ser = pd.Series([390., 350., 30., 20.], index=index, name="Max Speed")
>>> ser
Animal Type
Falcon Captive 390.0
Wild 350.0
Parrot Captive 30.0
Wild 20.0
Name: Max Speed, dtype: float64
>>> ser.groupby(level=0).mean()
Animal
Falcon 370.0
Parrot 25.0
Name: Max Speed, dtype: float64
>>> ser.groupby(level="Type").mean()
Type
Captive 210.0
Wild 185.0
Name: Max Speed, dtype: float64
We can also choose to include `NA` in group keys or not by defining
`dropna` parameter, the default setting is `True`:
>>> ser = pd.Series([1, 2, 3, 3], index=["a", 'a', 'b', np.nan])
>>> ser.groupby(level=0).sum()
a 3
b 3
dtype: int64
>>> ser.groupby(level=0, dropna=False).sum()
a 3
b 3
NaN 3
dtype: int64
>>> arrays = ['Falcon', 'Falcon', 'Parrot', 'Parrot']
>>> ser = pd.Series([390., 350., 30., 20.], index=arrays, name="Max Speed")
>>> ser.groupby(["a", "b", "a", np.nan]).mean()
a 210.0
b 350.0
Name: Max Speed, dtype: float64
>>> ser.groupby(["a", "b", "a", np.nan], dropna=False).mean()
a 210.0
b 350.0
NaN 20.0
Name: Max Speed, dtype: float64
"""
)
@Appender(generic._shared_docs["groupby"] % _shared_doc_kwargs)
def groupby(
self,
by=None,
axis=0,
level=None,
as_index: bool = True,
sort: bool = True,
group_keys: bool = True,
squeeze: bool = no_default,
observed: bool = False,
dropna: bool = True,
) -> "SeriesGroupBy":
from pandas.core.groupby.generic import SeriesGroupBy
if squeeze is not no_default:
warnings.warn(
(
"The `squeeze` parameter is deprecated and "
"will be removed in a future version."
),
FutureWarning,
stacklevel=2,
)
else:
squeeze = False
if level is None and by is None:
raise TypeError("You have to supply one of 'by' and 'level'")
axis = self._get_axis_number(axis)
return SeriesGroupBy(
obj=self,
keys=by,
axis=axis,
level=level,
as_index=as_index,
sort=sort,
group_keys=group_keys,
squeeze=squeeze,
observed=observed,
dropna=dropna,
)
# ----------------------------------------------------------------------
# Statistics, overridden ndarray methods
# TODO: integrate bottleneck
def count(self, level=None):
"""
Return number of non-NA/null observations in the Series.
Parameters
----------
level : int or level name, default None
If the axis is a MultiIndex (hierarchical), count along a
particular level, collapsing into a smaller Series.
Returns
-------
int or Series (if level specified)
Number of non-null values in the Series.
See Also
--------
DataFrame.count : Count non-NA cells for each column or row.
Examples
--------
>>> s = pd.Series([0.0, 1.0, np.nan])
>>> s.count()
2
"""
if level is None:
return notna(self.array).sum()
if isinstance(level, str):
level = self.index._get_level_number(level)
lev = self.index.levels[level]
level_codes = np.array(self.index.codes[level], subok=False, copy=True)
mask = level_codes == -1
if mask.any():
level_codes[mask] = cnt = len(lev)
lev = lev.insert(cnt, lev._na_value)
obs = level_codes[notna(self._values)]
out = np.bincount(obs, minlength=len(lev) or None)
return self._constructor(out, index=lev, dtype="int64").__finalize__(
self, method="count"
)
def mode(self, dropna=True) -> "Series":
"""
Return the mode(s) of the dataset.
Always returns Series even if only one value is returned.
Parameters
----------
dropna : bool, default True
Don't consider counts of NaN/NaT.
.. versionadded:: 0.24.0
Returns
-------
Series
Modes of the Series in sorted order.
"""
# TODO: Add option for bins like value_counts()
return algorithms.mode(self, dropna=dropna)
def unique(self):
"""
Return unique values of Series object.
Uniques are returned in order of appearance. Hash table-based unique,
therefore does NOT sort.
Returns
-------
ndarray or ExtensionArray
The unique values returned as a NumPy array. See Notes.
See Also
--------
unique : Top-level unique method for any 1-d array-like object.
Index.unique : Return Index with unique values from an Index object.
Notes
-----
Returns the unique values as a NumPy array. In case of an
extension-array backed Series, a new
:class:`~api.extensions.ExtensionArray` of that type with just
the unique values is returned. This includes
* Categorical
* Period
* Datetime with Timezone
* Interval
* Sparse
* IntegerNA
See Examples section.
Examples
--------
>>> pd.Series([2, 1, 3, 3], name='A').unique()
array([2, 1, 3])
>>> pd.Series([pd.Timestamp('2016-01-01') for _ in range(3)]).unique()
array(['2016-01-01T00:00:00.000000000'], dtype='datetime64[ns]')
>>> pd.Series([pd.Timestamp('2016-01-01', tz='US/Eastern')
... for _ in range(3)]).unique()
<DatetimeArray>
['2016-01-01 00:00:00-05:00']
Length: 1, dtype: datetime64[ns, US/Eastern]
An unordered Categorical will return categories in the order of
appearance.
>>> pd.Series(pd.Categorical(list('baabc'))).unique()
['b', 'a', 'c']
Categories (3, object): ['b', 'a', 'c']
An ordered Categorical preserves the category ordering.
>>> pd.Series(pd.Categorical(list('baabc'), categories=list('abc'),
... ordered=True)).unique()
['b', 'a', 'c']
Categories (3, object): ['a' < 'b' < 'c']
"""
result = super().unique()
return result
def drop_duplicates(self, keep="first", inplace=False) -> Optional["Series"]:
"""
Return Series with duplicate values removed.
Parameters
----------
keep : {'first', 'last', ``False``}, default 'first'
Method to handle dropping duplicates:
- 'first' : Drop duplicates except for the first occurrence.
- 'last' : Drop duplicates except for the last occurrence.
- ``False`` : Drop all duplicates.
inplace : bool, default ``False``
If ``True``, performs operation inplace and returns None.
Returns
-------
Series
Series with duplicates dropped.
See Also
--------
Index.drop_duplicates : Equivalent method on Index.
DataFrame.drop_duplicates : Equivalent method on DataFrame.
Series.duplicated : Related method on Series, indicating duplicate
Series values.
Examples
--------
Generate a Series with duplicated entries.
>>> s = pd.Series(['lama', 'cow', 'lama', 'beetle', 'lama', 'hippo'],
... name='animal')
>>> s
0 lama
1 cow
2 lama
3 beetle
4 lama
5 hippo
Name: animal, dtype: object
With the 'keep' parameter, the selection behaviour of duplicated values
can be changed. The value 'first' keeps the first occurrence for each
set of duplicated entries. The default value of keep is 'first'.
>>> s.drop_duplicates()
0 lama
1 cow
3 beetle
5 hippo
Name: animal, dtype: object
The value 'last' for parameter 'keep' keeps the last occurrence for
each set of duplicated entries.
>>> s.drop_duplicates(keep='last')
1 cow
3 beetle
4 lama
5 hippo
Name: animal, dtype: object
The value ``False`` for parameter 'keep' discards all sets of
duplicated entries. Setting the value of 'inplace' to ``True`` performs
the operation inplace and returns ``None``.
>>> s.drop_duplicates(keep=False, inplace=True)
>>> s
1 cow
3 beetle
5 hippo
Name: animal, dtype: object
"""
inplace = validate_bool_kwarg(inplace, "inplace")
result = super().drop_duplicates(keep=keep)
if inplace:
self._update_inplace(result)
return None
else:
return result
def duplicated(self, keep="first") -> "Series":
"""
Indicate duplicate Series values.
Duplicated values are indicated as ``True`` values in the resulting
Series. Either all duplicates, all except the first or all except the
last occurrence of duplicates can be indicated.
Parameters
----------
keep : {'first', 'last', False}, default 'first'
Method to handle dropping duplicates:
- 'first' : Mark duplicates as ``True`` except for the first
occurrence.
- 'last' : Mark duplicates as ``True`` except for the last
occurrence.
- ``False`` : Mark all duplicates as ``True``.
Returns
-------
Series
Series indicating whether each value has occurred in the
preceding values.
See Also
--------
Index.duplicated : Equivalent method on pandas.Index.
DataFrame.duplicated : Equivalent method on pandas.DataFrame.
Series.drop_duplicates : Remove duplicate values from Series.
Examples
--------
By default, for each set of duplicated values, the first occurrence is
set on False and all others on True:
>>> animals = pd.Series(['lama', 'cow', 'lama', 'beetle', 'lama'])
>>> animals.duplicated()
0 False
1 False
2 True
3 False
4 True
dtype: bool
which is equivalent to
>>> animals.duplicated(keep='first')
0 False
1 False
2 True
3 False
4 True
dtype: bool
By using 'last', the last occurrence of each set of duplicated values
is set on False and all others on True:
>>> animals.duplicated(keep='last')
0 True
1 False
2 True
3 False
4 False
dtype: bool
By setting keep on ``False``, all duplicates are True:
>>> animals.duplicated(keep=False)
0 True
1 False
2 True
3 False
4 True
dtype: bool
"""
return super().duplicated(keep=keep)
def idxmin(self, axis=0, skipna=True, *args, **kwargs):
"""
Return the row label of the minimum value.
If multiple values equal the minimum, the first row label with that
value is returned.
Parameters
----------
axis : int, default 0
For compatibility with DataFrame.idxmin. Redundant for application
on Series.
skipna : bool, default True
Exclude NA/null values. If the entire Series is NA, the result
will be NA.
*args, **kwargs
Additional arguments and keywords have no effect but might be
accepted for compatibility with NumPy.
Returns
-------
Index
Label of the minimum value.
Raises
------
ValueError
If the Series is empty.
See Also
--------
numpy.argmin : Return indices of the minimum values
along the given axis.
DataFrame.idxmin : Return index of first occurrence of minimum
over requested axis.
Series.idxmax : Return index *label* of the first occurrence
of maximum of values.
Notes
-----
This method is the Series version of ``ndarray.argmin``. This method
returns the label of the minimum, while ``ndarray.argmin`` returns
the position. To get the position, use ``series.values.argmin()``.
Examples
--------
>>> s = pd.Series(data=[1, None, 4, 1],
... index=['A', 'B', 'C', 'D'])
>>> s
A 1.0
B NaN
C 4.0
D 1.0
dtype: float64
>>> s.idxmin()
'A'
If `skipna` is False and there is an NA value in the data,
the function returns ``nan``.
>>> s.idxmin(skipna=False)
nan
"""
skipna = nv.validate_argmin_with_skipna(skipna, args, kwargs)
i = nanops.nanargmin(self._values, skipna=skipna)
if i == -1:
return np.nan
return self.index[i]
def idxmax(self, axis=0, skipna=True, *args, **kwargs):
"""
Return the row label of the maximum value.
If multiple values equal the maximum, the first row label with that
value is returned.
Parameters
----------
axis : int, default 0
For compatibility with DataFrame.idxmax. Redundant for application
on Series.
skipna : bool, default True
Exclude NA/null values. If the entire Series is NA, the result
will be NA.
*args, **kwargs
Additional arguments and keywords have no effect but might be
accepted for compatibility with NumPy.
Returns
-------
Index
Label of the maximum value.
Raises
------
ValueError
If the Series is empty.
See Also
--------
numpy.argmax : Return indices of the maximum values
along the given axis.
DataFrame.idxmax : Return index of first occurrence of maximum
over requested axis.
Series.idxmin : Return index *label* of the first occurrence
of minimum of values.
Notes
-----
This method is the Series version of ``ndarray.argmax``. This method
returns the label of the maximum, while ``ndarray.argmax`` returns
the position. To get the position, use ``series.values.argmax()``.
Examples
--------
>>> s = pd.Series(data=[1, None, 4, 3, 4],
... index=['A', 'B', 'C', 'D', 'E'])
>>> s
A 1.0
B NaN
C 4.0
D 3.0
E 4.0
dtype: float64
>>> s.idxmax()
'C'
If `skipna` is False and there is an NA value in the data,
the function returns ``nan``.
>>> s.idxmax(skipna=False)
nan
"""
skipna = nv.validate_argmax_with_skipna(skipna, args, kwargs)
i = nanops.nanargmax(self._values, skipna=skipna)
if i == -1:
return np.nan
return self.index[i]
def round(self, decimals=0, *args, **kwargs) -> "Series":
"""
Round each value in a Series to the given number of decimals.
Parameters
----------
decimals : int, default 0
Number of decimal places to round to. If decimals is negative,
it specifies the number of positions to the left of the decimal point.
*args, **kwargs
Additional arguments and keywords have no effect but might be
accepted for compatibility with NumPy.
Returns
-------
Series
Rounded values of the Series.
See Also
--------
numpy.around : Round values of an np.array.
DataFrame.round : Round values of a DataFrame.
Examples
--------
>>> s = pd.Series([0.1, 1.3, 2.7])
>>> s.round()
0 0.0
1 1.0
2 3.0
dtype: float64
"""
nv.validate_round(args, kwargs)
result = self._values.round(decimals)
result = self._constructor(result, index=self.index).__finalize__(
self, method="round"
)
return result
def quantile(self, q=0.5, interpolation="linear"):
"""
Return value at the given quantile.
Parameters
----------
q : float or array-like, default 0.5 (50% quantile)
The quantile(s) to compute, which can lie in range: 0 <= q <= 1.
interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'}
This optional parameter specifies the interpolation method to use,
when the desired quantile lies between two data points `i` and `j`:
* linear: `i + (j - i) * fraction`, where `fraction` is the
fractional part of the index surrounded by `i` and `j`.
* lower: `i`.
* higher: `j`.
* nearest: `i` or `j` whichever is nearest.
* midpoint: (`i` + `j`) / 2.
Returns
-------
float or Series
If ``q`` is an array, a Series will be returned where the
index is ``q`` and the values are the quantiles, otherwise
a float will be returned.
See Also
--------
core.window.Rolling.quantile : Calculate the rolling quantile.
numpy.percentile : Returns the q-th percentile(s) of the array elements.
Examples
--------
>>> s = pd.Series([1, 2, 3, 4])
>>> s.quantile(.5)
2.5
>>> s.quantile([.25, .5, .75])
0.25 1.75
0.50 2.50
0.75 3.25
dtype: float64
"""
validate_percentile(q)
# We dispatch to DataFrame so that core.internals only has to worry
# about 2D cases.
df = self.to_frame()
result = df.quantile(q=q, interpolation=interpolation, numeric_only=False)
if result.ndim == 2:
result = result.iloc[:, 0]
if is_list_like(q):
result.name = self.name
return self._constructor(result, index=Float64Index(q), name=self.name)
else:
# scalar
return result.iloc[0]
def corr(self, other, method="pearson", min_periods=None) -> float:
"""
Compute correlation with `other` Series, excluding missing values.
Parameters
----------
other : Series
Series with which to compute the correlation.
method : {'pearson', 'kendall', 'spearman'} or callable
Method used to compute correlation:
- pearson : Standard correlation coefficient
- kendall : Kendall Tau correlation coefficient
- spearman : Spearman rank correlation
- callable: Callable with input two 1d ndarrays and returning a float.
.. versionadded:: 0.24.0
Note that the returned matrix from corr will have 1 along the
diagonals and will be symmetric regardless of the callable's
behavior.
min_periods : int, optional
Minimum number of observations needed to have a valid result.
Returns
-------
float
Correlation with other.
See Also
--------
DataFrame.corr : Compute pairwise correlation between columns.
DataFrame.corrwith : Compute pairwise correlation with another
DataFrame or Series.
Examples
--------
>>> def histogram_intersection(a, b):
... v = np.minimum(a, b).sum().round(decimals=1)
... return v
>>> s1 = pd.Series([.2, .0, .6, .2])
>>> s2 = pd.Series([.3, .6, .0, .1])
>>> s1.corr(s2, method=histogram_intersection)
0.3
"""
this, other = self.align(other, join="inner", copy=False)
if len(this) == 0:
return np.nan
if method in ["pearson", "spearman", "kendall"] or callable(method):
return nanops.nancorr(
this.values, other.values, method=method, min_periods=min_periods
)
raise ValueError(
"method must be either 'pearson', "
"'spearman', 'kendall', or a callable, "
f"'{method}' was supplied"
)
def cov(
self,
other: "Series",
min_periods: Optional[int] = None,
ddof: Optional[int] = 1,
) -> float:
"""
Compute covariance with Series, excluding missing values.
Parameters
----------
other : Series
Series with which to compute the covariance.
min_periods : int, optional
Minimum number of observations needed to have a valid result.
ddof : int, default 1
Delta degrees of freedom. The divisor used in calculations
is ``N - ddof``, where ``N`` represents the number of elements.
.. versionadded:: 1.1.0
Returns
-------
float
Covariance between Series and other normalized by N-1
(unbiased estimator).
See Also
--------
DataFrame.cov : Compute pairwise covariance of columns.
Examples
--------
>>> s1 = pd.Series([0.90010907, 0.13484424, 0.62036035])
>>> s2 = pd.Series([0.12528585, 0.26962463, 0.51111198])
>>> s1.cov(s2)
-0.01685762652715874
"""
this, other = self.align(other, join="inner", copy=False)
if len(this) == 0:
return np.nan
return nanops.nancov(
this.values, other.values, min_periods=min_periods, ddof=ddof
)
@doc(
klass="Series",
extra_params="",
other_klass="DataFrame",
examples=dedent(
"""
Difference with previous row
>>> s = pd.Series([1, 1, 2, 3, 5, 8])
>>> s.diff()
0 NaN
1 0.0
2 1.0
3 1.0
4 2.0
5 3.0
dtype: float64
Difference with 3rd previous row
>>> s.diff(periods=3)
0 NaN
1 NaN
2 NaN
3 2.0
4 4.0
5 6.0
dtype: float64
Difference with following row
>>> s.diff(periods=-1)
0 0.0
1 -1.0
2 -1.0
3 -2.0
4 -3.0
5 NaN
dtype: float64
Overflow in input dtype
>>> s = pd.Series([1, 0], dtype=np.uint8)
>>> s.diff()
0 NaN
1 255.0
dtype: float64"""
),
)
def diff(self, periods: int = 1) -> "Series":
"""
First discrete difference of element.
Calculates the difference of a {klass} element compared with another
element in the {klass} (default is element in previous row).
Parameters
----------
periods : int, default 1
Periods to shift for calculating difference, accepts negative
values.
{extra_params}
Returns
-------
{klass}
First differences of the Series.
See Also
--------
{klass}.pct_change: Percent change over given number of periods.
{klass}.shift: Shift index by desired number of periods with an
optional time freq.
{other_klass}.diff: First discrete difference of object.
Notes
-----
For boolean dtypes, this uses :meth:`operator.xor` rather than
:meth:`operator.sub`.
The result is calculated according to current dtype in {klass},
however dtype of the result is always float64.
Examples
--------
{examples}
"""
result = algorithms.diff(self.array, periods)
return self._constructor(result, index=self.index).__finalize__(
self, method="diff"
)
def autocorr(self, lag=1) -> float:
"""
Compute the lag-N autocorrelation.
This method computes the Pearson correlation between
the Series and its shifted self.
Parameters
----------
lag : int, default 1
Number of lags to apply before performing autocorrelation.
Returns
-------
float
The Pearson correlation between self and self.shift(lag).
See Also
--------
Series.corr : Compute the correlation between two Series.
Series.shift : Shift index by desired number of periods.
DataFrame.corr : Compute pairwise correlation of columns.
DataFrame.corrwith : Compute pairwise correlation between rows or
columns of two DataFrame objects.
Notes
-----
If the Pearson correlation is not well defined return 'NaN'.
Examples
--------
>>> s = pd.Series([0.25, 0.5, 0.2, -0.05])
>>> s.autocorr() # doctest: +ELLIPSIS
0.10355...
>>> s.autocorr(lag=2) # doctest: +ELLIPSIS
-0.99999...
If the Pearson correlation is not well defined, then 'NaN' is returned.
>>> s = pd.Series([1, 0, 0, 0])
>>> s.autocorr()
nan
"""
return self.corr(self.shift(lag))
def dot(self, other):
"""
Compute the dot product between the Series and the columns of other.
This method computes the dot product between the Series and another
one, or the Series and each columns of a DataFrame, or the Series and
each columns of an array.
It can also be called using `self @ other` in Python >= 3.5.
Parameters
----------
other : Series, DataFrame or array-like
The other object to compute the dot product with its columns.
Returns
-------
scalar, Series or numpy.ndarray
Return the dot product of the Series and other if other is a
Series, the Series of the dot product of Series and each rows of
other if other is a DataFrame or a numpy.ndarray between the Series
and each columns of the numpy array.
See Also
--------
DataFrame.dot: Compute the matrix product with the DataFrame.
Series.mul: Multiplication of series and other, element-wise.
Notes
-----
The Series and other has to share the same index if other is a Series
or a DataFrame.
Examples
--------
>>> s = pd.Series([0, 1, 2, 3])
>>> other = pd.Series([-1, 2, -3, 4])
>>> s.dot(other)
8
>>> s @ other
8
>>> df = pd.DataFrame([[0, 1], [-2, 3], [4, -5], [6, 7]])
>>> s.dot(df)
0 24
1 14
dtype: int64
>>> arr = np.array([[0, 1], [-2, 3], [4, -5], [6, 7]])
>>> s.dot(arr)
array([24, 14])
"""
if isinstance(other, (Series, ABCDataFrame)):
common = self.index.union(other.index)
if len(common) > len(self.index) or len(common) > len(other.index):
raise ValueError("matrices are not aligned")
left = self.reindex(index=common, copy=False)
right = other.reindex(index=common, copy=False)
lvals = left.values
rvals = right.values
else:
lvals = self.values
rvals = np.asarray(other)
if lvals.shape[0] != rvals.shape[0]:
raise Exception(
f"Dot product shape mismatch, {lvals.shape} vs {rvals.shape}"
)
if isinstance(other, ABCDataFrame):
return self._constructor(
np.dot(lvals, rvals), index=other.columns
).__finalize__(self, method="dot")
elif isinstance(other, Series):
return np.dot(lvals, rvals)
elif isinstance(rvals, np.ndarray):
return np.dot(lvals, rvals)
else: # pragma: no cover
raise TypeError(f"unsupported type: {type(other)}")
def __matmul__(self, other):
"""
Matrix multiplication using binary `@` operator in Python>=3.5.
"""
return self.dot(other)
def __rmatmul__(self, other):
"""
Matrix multiplication using binary `@` operator in Python>=3.5.
"""
return self.dot(np.transpose(other))
@doc(base.IndexOpsMixin.searchsorted, klass="Series")
def searchsorted(self, value, side="left", sorter=None):
return algorithms.searchsorted(self._values, value, side=side, sorter=sorter)
# -------------------------------------------------------------------
# Combination
def append(self, to_append, ignore_index=False, verify_integrity=False):
"""
Concatenate two or more Series.
Parameters
----------
to_append : Series or list/tuple of Series
Series to append with self.
ignore_index : bool, default False
If True, the resulting axis will be labeled 0, 1, …, n - 1.
verify_integrity : bool, default False
If True, raise Exception on creating index with duplicates.
Returns
-------
Series
Concatenated Series.
See Also
--------
concat : General function to concatenate DataFrame or Series objects.
Notes
-----
Iteratively appending to a Series can be more computationally intensive
than a single concatenate. A better solution is to append values to a
list and then concatenate the list with the original Series all at
once.
Examples
--------
>>> s1 = pd.Series([1, 2, 3])
>>> s2 = pd.Series([4, 5, 6])
>>> s3 = pd.Series([4, 5, 6], index=[3, 4, 5])
>>> s1.append(s2)
0 1
1 2
2 3
0 4
1 5
2 6
dtype: int64
>>> s1.append(s3)
0 1
1 2
2 3
3 4
4 5
5 6
dtype: int64
With `ignore_index` set to True:
>>> s1.append(s2, ignore_index=True)
0 1
1 2
2 3
3 4
4 5
5 6
dtype: int64
With `verify_integrity` set to True:
>>> s1.append(s2, verify_integrity=True)
Traceback (most recent call last):
...
ValueError: Indexes have overlapping values: [0, 1, 2]
"""
from pandas.core.reshape.concat import concat
if isinstance(to_append, (list, tuple)):
to_concat = [self]
to_concat.extend(to_append)
else:
to_concat = [self, to_append]
if any(isinstance(x, (ABCDataFrame,)) for x in to_concat[1:]):
msg = "to_append should be a Series or list/tuple of Series, got DataFrame"
raise TypeError(msg)
return concat(
to_concat, ignore_index=ignore_index, verify_integrity=verify_integrity
)
def _binop(self, other, func, level=None, fill_value=None):
"""
Perform generic binary operation with optional fill value.
Parameters
----------
other : Series
func : binary operator
fill_value : float or object
Value to substitute for NA/null values. If both Series are NA in a
location, the result will be NA regardless of the passed fill value.
level : int or level name, default None
Broadcast across a level, matching Index values on the
passed MultiIndex level.
Returns
-------
Series
"""
if not isinstance(other, Series):
raise AssertionError("Other operand must be Series")
this = self
if not self.index.equals(other.index):
this, other = self.align(other, level=level, join="outer", copy=False)
this_vals, other_vals = ops.fill_binop(this.values, other.values, fill_value)
with np.errstate(all="ignore"):
result = func(this_vals, other_vals)
name = ops.get_op_result_name(self, other)
ret = this._construct_result(result, name)
return ret
def _construct_result(
self, result: Union[ArrayLike, Tuple[ArrayLike, ArrayLike]], name: Label
) -> Union["Series", Tuple["Series", "Series"]]:
"""
Construct an appropriately-labelled Series from the result of an op.
Parameters
----------
result : ndarray or ExtensionArray
name : Label
Returns
-------
Series
In the case of __divmod__ or __rdivmod__, a 2-tuple of Series.
"""
if isinstance(result, tuple):
# produced by divmod or rdivmod
res1 = self._construct_result(result[0], name=name)
res2 = self._construct_result(result[1], name=name)
# GH#33427 assertions to keep mypy happy
assert isinstance(res1, Series)
assert isinstance(res2, Series)
return (res1, res2)
# We do not pass dtype to ensure that the Series constructor
# does inference in the case where `result` has object-dtype.
out = self._constructor(result, index=self.index)
out = out.__finalize__(self)
# Set the result's name after __finalize__ is called because __finalize__
# would set it back to self.name
out.name = name
return out
@Appender(
"""
Returns
-------
Series or DataFrame
If axis is 0 or 'index' the result will be a Series.
The resulting index will be a MultiIndex with 'self' and 'other'
stacked alternately at the inner level.
If axis is 1 or 'columns' the result will be a DataFrame.
It will have two columns namely 'self' and 'other'.
See Also
--------
DataFrame.compare : Compare with another DataFrame and show differences.
Notes
-----
Matching NaNs will not appear as a difference.
Examples
--------
>>> s1 = pd.Series(["a", "b", "c", "d", "e"])
>>> s2 = pd.Series(["a", "a", "c", "b", "e"])
Align the differences on columns
>>> s1.compare(s2)
self other
1 b a
3 d b
Stack the differences on indices
>>> s1.compare(s2, align_axis=0)
1 self b
other a
3 self d
other b
dtype: object
Keep all original rows
>>> s1.compare(s2, keep_shape=True)
self other
0 NaN NaN
1 b a
2 NaN NaN
3 d b
4 NaN NaN
Keep all original rows and also all original values
>>> s1.compare(s2, keep_shape=True, keep_equal=True)
self other
0 a a
1 b a
2 c c
3 d b
4 e e
"""
)
@Appender(generic._shared_docs["compare"] % _shared_doc_kwargs)
def compare(
self,
other: "Series",
align_axis: Axis = 1,
keep_shape: bool = False,
keep_equal: bool = False,
) -> FrameOrSeriesUnion:
return super().compare(
other=other,
align_axis=align_axis,
keep_shape=keep_shape,
keep_equal=keep_equal,
)
def combine(self, other, func, fill_value=None) -> "Series":
"""
Combine the Series with a Series or scalar according to `func`.
Combine the Series and `other` using `func` to perform elementwise
selection for combined Series.
`fill_value` is assumed when value is missing at some index
from one of the two objects being combined.
Parameters
----------
other : Series or scalar
The value(s) to be combined with the `Series`.
func : function
Function that takes two scalars as inputs and returns an element.
fill_value : scalar, optional
The value to assume when an index is missing from
one Series or the other. The default specifies to use the
appropriate NaN value for the underlying dtype of the Series.
Returns
-------
Series
The result of combining the Series with the other object.
See Also
--------
Series.combine_first : Combine Series values, choosing the calling
Series' values first.
Examples
--------
Consider 2 Datasets ``s1`` and ``s2`` containing
highest clocked speeds of different birds.
>>> s1 = pd.Series({'falcon': 330.0, 'eagle': 160.0})
>>> s1
falcon 330.0
eagle 160.0
dtype: float64
>>> s2 = pd.Series({'falcon': 345.0, 'eagle': 200.0, 'duck': 30.0})
>>> s2
falcon 345.0
eagle 200.0
duck 30.0
dtype: float64
Now, to combine the two datasets and view the highest speeds
of the birds across the two datasets
>>> s1.combine(s2, max)
duck NaN
eagle 200.0
falcon 345.0
dtype: float64
In the previous example, the resulting value for duck is missing,
because the maximum of a NaN and a float is a NaN.
So, in the example, we set ``fill_value=0``,
so the maximum value returned will be the value from some dataset.
>>> s1.combine(s2, max, fill_value=0)
duck 30.0
eagle 200.0
falcon 345.0
dtype: float64
"""
if fill_value is None:
fill_value = na_value_for_dtype(self.dtype, compat=False)
if isinstance(other, Series):
# If other is a Series, result is based on union of Series,
# so do this element by element
new_index = self.index.union(other.index)
new_name = ops.get_op_result_name(self, other)
new_values = []
for idx in new_index:
lv = self.get(idx, fill_value)
rv = other.get(idx, fill_value)
with np.errstate(all="ignore"):
new_values.append(func(lv, rv))
else:
# Assume that other is a scalar, so apply the function for
# each element in the Series
new_index = self.index
with np.errstate(all="ignore"):
new_values = [func(lv, other) for lv in self._values]
new_name = self.name
if is_categorical_dtype(self.dtype):
pass
elif is_extension_array_dtype(self.dtype):
# TODO: can we do this for only SparseDtype?
# The function can return something of any type, so check
# if the type is compatible with the calling EA.
new_values = maybe_cast_to_extension_array(type(self._values), new_values)
return self._constructor(new_values, index=new_index, name=new_name)
def combine_first(self, other) -> "Series":
"""
Combine Series values, choosing the calling Series's values first.
Parameters
----------
other : Series
The value(s) to be combined with the `Series`.
Returns
-------
Series
The result of combining the Series with the other object.
See Also
--------
Series.combine : Perform elementwise operation on two Series
using a given function.
Notes
-----
Result index will be the union of the two indexes.
Examples
--------
>>> s1 = pd.Series([1, np.nan])
>>> s2 = pd.Series([3, 4])
>>> s1.combine_first(s2)
0 1.0
1 4.0
dtype: float64
"""
new_index = self.index.union(other.index)
this = self.reindex(new_index, copy=False)
other = other.reindex(new_index, copy=False)
if this.dtype.kind == "M" and other.dtype.kind != "M":
other = to_datetime(other)
return this.where(notna(this), other)
def update(self, other) -> None:
"""
Modify Series in place using values from passed Series.
Uses non-NA values from passed Series to make updates. Aligns
on index.
Parameters
----------
other : Series, or object coercible into Series
Examples
--------
>>> s = pd.Series([1, 2, 3])
>>> s.update(pd.Series([4, 5, 6]))
>>> s
0 4
1 5
2 6
dtype: int64
>>> s = pd.Series(['a', 'b', 'c'])
>>> s.update(pd.Series(['d', 'e'], index=[0, 2]))
>>> s
0 d
1 b
2 e
dtype: object
>>> s = pd.Series([1, 2, 3])
>>> s.update(pd.Series([4, 5, 6, 7, 8]))
>>> s
0 4
1 5
2 6
dtype: int64
If ``other`` contains NaNs the corresponding values are not updated
in the original Series.
>>> s = pd.Series([1, 2, 3])
>>> s.update(pd.Series([4, np.nan, 6]))
>>> s
0 4
1 2
2 6
dtype: int64
``other`` can also be a non-Series object type
that is coercible into a Series
>>> s = pd.Series([1, 2, 3])
>>> s.update([4, np.nan, 6])
>>> s
0 4
1 2
2 6
dtype: int64
>>> s = pd.Series([1, 2, 3])
>>> s.update({1: 9})
>>> s
0 1
1 9
2 3
dtype: int64
"""
if not isinstance(other, Series):
other = Series(other)
other = other.reindex_like(self)
mask = notna(other)
self._mgr = self._mgr.putmask(mask=mask, new=other)
self._maybe_update_cacher()
# ----------------------------------------------------------------------
# Reindexing, sorting
def sort_values(
self,
axis=0,
ascending=True,
inplace: bool = False,
kind: str = "quicksort",
na_position: str = "last",
ignore_index: bool = False,
key: ValueKeyFunc = None,
):
"""
Sort by the values.
Sort a Series in ascending or descending order by some
criterion.
Parameters
----------
axis : {0 or 'index'}, default 0
Axis to direct sorting. The value 'index' is accepted for
compatibility with DataFrame.sort_values.
ascending : bool, default True
If True, sort values in ascending order, otherwise descending.
inplace : bool, default False
If True, perform operation in-place.
kind : {'quicksort', 'mergesort' or 'heapsort'}, default 'quicksort'
Choice of sorting algorithm. See also :func:`numpy.sort` for more
information. 'mergesort' is the only stable algorithm.
na_position : {'first' or 'last'}, default 'last'
Argument 'first' puts NaNs at the beginning, 'last' puts NaNs at
the end.
ignore_index : bool, default False
If True, the resulting axis will be labeled 0, 1, …, n - 1.
.. versionadded:: 1.0.0
key : callable, optional
If not None, apply the key function to the series values
before sorting. This is similar to the `key` argument in the
builtin :meth:`sorted` function, with the notable difference that
this `key` function should be *vectorized*. It should expect a
``Series`` and return an array-like.
.. versionadded:: 1.1.0
Returns
-------
Series
Series ordered by values.
See Also
--------
Series.sort_index : Sort by the Series indices.
DataFrame.sort_values : Sort DataFrame by the values along either axis.
DataFrame.sort_index : Sort DataFrame by indices.
Examples
--------
>>> s = pd.Series([np.nan, 1, 3, 10, 5])
>>> s
0 NaN
1 1.0
2 3.0
3 10.0
4 5.0
dtype: float64
Sort values ascending order (default behaviour)
>>> s.sort_values(ascending=True)
1 1.0
2 3.0
4 5.0
3 10.0
0 NaN
dtype: float64
Sort values descending order
>>> s.sort_values(ascending=False)
3 10.0
4 5.0
2 3.0
1 1.0
0 NaN
dtype: float64
Sort values inplace
>>> s.sort_values(ascending=False, inplace=True)
>>> s
3 10.0
4 5.0
2 3.0
1 1.0
0 NaN
dtype: float64
Sort values putting NAs first
>>> s.sort_values(na_position='first')
0 NaN
1 1.0
2 3.0
4 5.0
3 10.0
dtype: float64
Sort a series of strings
>>> s = pd.Series(['z', 'b', 'd', 'a', 'c'])
>>> s
0 z
1 b
2 d
3 a
4 c
dtype: object
>>> s.sort_values()
3 a
1 b
4 c
2 d
0 z
dtype: object
Sort using a key function. Your `key` function will be
given the ``Series`` of values and should return an array-like.
>>> s = pd.Series(['a', 'B', 'c', 'D', 'e'])
>>> s.sort_values()
1 B
3 D
0 a
2 c
4 e
dtype: object
>>> s.sort_values(key=lambda x: x.str.lower())
0 a
1 B
2 c
3 D
4 e
dtype: object
NumPy ufuncs work well here. For example, we can
sort by the ``sin`` of the value
>>> s = pd.Series([-4, -2, 0, 2, 4])
>>> s.sort_values(key=np.sin)
1 -2
4 4
2 0
0 -4
3 2
dtype: int64
More complicated user-defined functions can be used,
as long as they expect a Series and return an array-like
>>> s.sort_values(key=lambda x: (np.tan(x.cumsum())))
0 -4
3 2
4 4
1 -2
2 0
dtype: int64
"""
inplace = validate_bool_kwarg(inplace, "inplace")
# Validate the axis parameter
self._get_axis_number(axis)
# GH 5856/5853
if inplace and self._is_cached:
raise ValueError(
"This Series is a view of some other array, to "
"sort in-place you must create a copy"
)
def _try_kind_sort(arr):
arr = ensure_key_mapped(arr, key)
arr = getattr(arr, "_values", arr)
# easier to ask forgiveness than permission
try:
# if kind==mergesort, it can fail for object dtype
return arr.argsort(kind=kind)
except TypeError:
# stable sort not available for object dtype
# uses the argsort default quicksort
return arr.argsort(kind="quicksort")
arr = self._values
sorted_index = np.empty(len(self), dtype=np.int32)
bad = isna(arr)
good = ~bad
idx = ibase.default_index(len(self))
argsorted = _try_kind_sort(self[good])
if is_list_like(ascending):
if len(ascending) != 1:
raise ValueError(
f"Length of ascending ({len(ascending)}) must be 1 for Series"
)
ascending = ascending[0]
if not is_bool(ascending):
raise ValueError("ascending must be boolean")
if not ascending:
argsorted = argsorted[::-1]
if na_position == "last":
n = good.sum()
sorted_index[:n] = idx[good][argsorted]
sorted_index[n:] = idx[bad]
elif na_position == "first":
n = bad.sum()
sorted_index[n:] = idx[good][argsorted]
sorted_index[:n] = idx[bad]
else:
raise ValueError(f"invalid na_position: {na_position}")
result = self._constructor(arr[sorted_index], index=self.index[sorted_index])
if ignore_index:
result.index = ibase.default_index(len(sorted_index))
if inplace:
self._update_inplace(result)
else:
return result.__finalize__(self, method="sort_values")
def sort_index(
self,
axis=0,
level=None,
ascending: bool = True,
inplace: bool = False,
kind: str = "quicksort",
na_position: str = "last",
sort_remaining: bool = True,
ignore_index: bool = False,
key: IndexKeyFunc = None,
):
"""
Sort Series by index labels.
Returns a new Series sorted by label if `inplace` argument is
``False``, otherwise updates the original series and returns None.
Parameters
----------
axis : int, default 0
Axis to direct sorting. This can only be 0 for Series.
level : int, optional
If not None, sort on values in specified index level(s).
ascending : bool or list of bools, default True
Sort ascending vs. descending. When the index is a MultiIndex the
sort direction can be controlled for each level individually.
inplace : bool, default False
If True, perform operation in-place.
kind : {'quicksort', 'mergesort', 'heapsort'}, default 'quicksort'
Choice of sorting algorithm. See also :func:`numpy.sort` for more
information. 'mergesort' is the only stable algorithm. For
DataFrames, this option is only applied when sorting on a single
column or label.
na_position : {'first', 'last'}, default 'last'
If 'first' puts NaNs at the beginning, 'last' puts NaNs at the end.
Not implemented for MultiIndex.
sort_remaining : bool, default True
If True and sorting by level and index is multilevel, sort by other
levels too (in order) after sorting by specified level.
ignore_index : bool, default False
If True, the resulting axis will be labeled 0, 1, …, n - 1.
.. versionadded:: 1.0.0
key : callable, optional
If not None, apply the key function to the index values
before sorting. This is similar to the `key` argument in the
builtin :meth:`sorted` function, with the notable difference that
this `key` function should be *vectorized*. It should expect an
``Index`` and return an ``Index`` of the same shape.
.. versionadded:: 1.1.0
Returns
-------
Series
The original Series sorted by the labels.
See Also
--------
DataFrame.sort_index: Sort DataFrame by the index.
DataFrame.sort_values: Sort DataFrame by the value.
Series.sort_values : Sort Series by the value.
Examples
--------
>>> s = pd.Series(['a', 'b', 'c', 'd'], index=[3, 2, 1, 4])
>>> s.sort_index()
1 c
2 b
3 a
4 d
dtype: object
Sort Descending
>>> s.sort_index(ascending=False)
4 d
3 a
2 b
1 c
dtype: object
Sort Inplace
>>> s.sort_index(inplace=True)
>>> s
1 c
2 b
3 a
4 d
dtype: object
By default NaNs are put at the end, but use `na_position` to place
them at the beginning
>>> s = pd.Series(['a', 'b', 'c', 'd'], index=[3, 2, 1, np.nan])
>>> s.sort_index(na_position='first')
NaN d
1.0 c
2.0 b
3.0 a
dtype: object
Specify index level to sort
>>> arrays = [np.array(['qux', 'qux', 'foo', 'foo',
... 'baz', 'baz', 'bar', 'bar']),
... np.array(['two', 'one', 'two', 'one',
... 'two', 'one', 'two', 'one'])]
>>> s = pd.Series([1, 2, 3, 4, 5, 6, 7, 8], index=arrays)
>>> s.sort_index(level=1)
bar one 8
baz one 6
foo one 4
qux one 2
bar two 7
baz two 5
foo two 3
qux two 1
dtype: int64
Does not sort by remaining levels when sorting by levels
>>> s.sort_index(level=1, sort_remaining=False)
qux one 2
foo one 4
baz one 6
bar one 8
qux two 1
foo two 3
baz two 5
bar two 7
dtype: int64
Apply a key function before sorting
>>> s = pd.Series([1, 2, 3, 4], index=['A', 'b', 'C', 'd'])
>>> s.sort_index(key=lambda x : x.str.lower())
A 1
b 2
C 3
d 4
dtype: int64
"""
# TODO: this can be combined with DataFrame.sort_index impl as
# almost identical
inplace = validate_bool_kwarg(inplace, "inplace")
# Validate the axis parameter
self._get_axis_number(axis)
index = ensure_key_mapped(self.index, key, levels=level)
if level is not None:
new_index, indexer = index.sortlevel(
level, ascending=ascending, sort_remaining=sort_remaining
)
elif isinstance(index, MultiIndex):
from pandas.core.sorting import lexsort_indexer
labels = index._sort_levels_monotonic()
indexer = lexsort_indexer(
labels._get_codes_for_sorting(),
orders=ascending,
na_position=na_position,
)
else:
from pandas.core.sorting import nargsort
# Check monotonic-ness before sort an index
# GH11080
if (ascending and index.is_monotonic_increasing) or (
not ascending and index.is_monotonic_decreasing
):
if inplace:
return
else:
return self.copy()
indexer = nargsort(
index, kind=kind, ascending=ascending, na_position=na_position
)
indexer = ensure_platform_int(indexer)
new_index = self.index.take(indexer)
new_index = new_index._sort_levels_monotonic()
new_values = self._values.take(indexer)
result = self._constructor(new_values, index=new_index)
if ignore_index:
result.index = ibase.default_index(len(result))
if inplace:
self._update_inplace(result)
else:
return result.__finalize__(self, method="sort_index")
def argsort(self, axis=0, kind="quicksort", order=None) -> "Series":
"""
Return the integer indices that would sort the Series values.
Override ndarray.argsort. Argsorts the value, omitting NA/null values,
and places the result in the same locations as the non-NA values.
Parameters
----------
axis : {0 or "index"}
Has no effect but is accepted for compatibility with numpy.
kind : {'mergesort', 'quicksort', 'heapsort'}, default 'quicksort'
Choice of sorting algorithm. See np.sort for more
information. 'mergesort' is the only stable algorithm.
order : None
Has no effect but is accepted for compatibility with numpy.
Returns
-------
Series
Positions of values within the sort order with -1 indicating
nan values.
See Also
--------
numpy.ndarray.argsort : Returns the indices that would sort this array.
"""
values = self._values
mask = isna(values)
if mask.any():
result = Series(-1, index=self.index, name=self.name, dtype="int64")
notmask = ~mask
result[notmask] = np.argsort(values[notmask], kind=kind)
return self._constructor(result, index=self.index).__finalize__(
self, method="argsort"
)
else:
return self._constructor(
np.argsort(values, kind=kind), index=self.index, dtype="int64"
).__finalize__(self, method="argsort")
def nlargest(self, n=5, keep="first") -> "Series":
"""
Return the largest `n` elements.
Parameters
----------
n : int, default 5
Return this many descending sorted values.
keep : {'first', 'last', 'all'}, default 'first'
When there are duplicate values that cannot all fit in a
Series of `n` elements:
- ``first`` : return the first `n` occurrences in order
of appearance.
- ``last`` : return the last `n` occurrences in reverse
order of appearance.
- ``all`` : keep all occurrences. This can result in a Series of
size larger than `n`.
Returns
-------
Series
The `n` largest values in the Series, sorted in decreasing order.
See Also
--------
Series.nsmallest: Get the `n` smallest elements.
Series.sort_values: Sort Series by values.
Series.head: Return the first `n` rows.
Notes
-----
Faster than ``.sort_values(ascending=False).head(n)`` for small `n`
relative to the size of the ``Series`` object.
Examples
--------
>>> countries_population = {"Italy": 59000000, "France": 65000000,
... "Malta": 434000, "Maldives": 434000,
... "Brunei": 434000, "Iceland": 337000,
... "Nauru": 11300, "Tuvalu": 11300,
... "Anguilla": 11300, "Montserrat": 5200}
>>> s = pd.Series(countries_population)
>>> s
Italy 59000000
France 65000000
Malta 434000
Maldives 434000
Brunei 434000
Iceland 337000
Nauru 11300
Tuvalu 11300
Anguilla 11300
Montserrat 5200
dtype: int64
The `n` largest elements where ``n=5`` by default.
>>> s.nlargest()
France 65000000
Italy 59000000
Malta 434000
Maldives 434000
Brunei 434000
dtype: int64
The `n` largest elements where ``n=3``. Default `keep` value is 'first'
so Malta will be kept.
>>> s.nlargest(3)
France 65000000
Italy 59000000
Malta 434000
dtype: int64
The `n` largest elements where ``n=3`` and keeping the last duplicates.
Brunei will be kept since it is the last with value 434000 based on
the index order.
>>> s.nlargest(3, keep='last')
France 65000000
Italy 59000000
Brunei 434000
dtype: int64
The `n` largest elements where ``n=3`` with all duplicates kept. Note
that the returned Series has five elements due to the three duplicates.
>>> s.nlargest(3, keep='all')
France 65000000
Italy 59000000
Malta 434000
Maldives 434000
Brunei 434000
dtype: int64
"""
return algorithms.SelectNSeries(self, n=n, keep=keep).nlargest()
def nsmallest(self, n=5, keep="first") -> "Series":
"""
Return the smallest `n` elements.
Parameters
----------
n : int, default 5
Return this many ascending sorted values.
keep : {'first', 'last', 'all'}, default 'first'
When there are duplicate values that cannot all fit in a
Series of `n` elements:
- ``first`` : return the first `n` occurrences in order
of appearance.
- ``last`` : return the last `n` occurrences in reverse
order of appearance.
- ``all`` : keep all occurrences. This can result in a Series of
size larger than `n`.
Returns
-------
Series
The `n` smallest values in the Series, sorted in increasing order.
See Also
--------
Series.nlargest: Get the `n` largest elements.
Series.sort_values: Sort Series by values.
Series.head: Return the first `n` rows.
Notes
-----
Faster than ``.sort_values().head(n)`` for small `n` relative to
the size of the ``Series`` object.
Examples
--------
>>> countries_population = {"Italy": 59000000, "France": 65000000,
... "Brunei": 434000, "Malta": 434000,
... "Maldives": 434000, "Iceland": 337000,
... "Nauru": 11300, "Tuvalu": 11300,
... "Anguilla": 11300, "Montserrat": 5200}
>>> s = pd.Series(countries_population)
>>> s
Italy 59000000
France 65000000
Brunei 434000
Malta 434000
Maldives 434000
Iceland 337000
Nauru 11300
Tuvalu 11300
Anguilla 11300
Montserrat 5200
dtype: int64
The `n` smallest elements where ``n=5`` by default.
>>> s.nsmallest()
Montserrat 5200
Nauru 11300
Tuvalu 11300
Anguilla 11300
Iceland 337000
dtype: int64
The `n` smallest elements where ``n=3``. Default `keep` value is
'first' so Nauru and Tuvalu will be kept.
>>> s.nsmallest(3)
Montserrat 5200
Nauru 11300
Tuvalu 11300
dtype: int64
The `n` smallest elements where ``n=3`` and keeping the last
duplicates. Anguilla and Tuvalu will be kept since they are the last
with value 11300 based on the index order.
>>> s.nsmallest(3, keep='last')
Montserrat 5200
Anguilla 11300
Tuvalu 11300
dtype: int64
The `n` smallest elements where ``n=3`` with all duplicates kept. Note
that the returned Series has four elements due to the three duplicates.
>>> s.nsmallest(3, keep='all')
Montserrat 5200
Nauru 11300
Tuvalu 11300
Anguilla 11300
dtype: int64
"""
return algorithms.SelectNSeries(self, n=n, keep=keep).nsmallest()
def swaplevel(self, i=-2, j=-1, copy=True) -> "Series":
"""
Swap levels i and j in a :class:`MultiIndex`.
Default is to swap the two innermost levels of the index.
Parameters
----------
i, j : int, str
Level of the indices to be swapped. Can pass level name as string.
copy : bool, default True
Whether to copy underlying data.
Returns
-------
Series
Series with levels swapped in MultiIndex.
"""
assert isinstance(self.index, MultiIndex)
new_index = self.index.swaplevel(i, j)
return self._constructor(self._values, index=new_index, copy=copy).__finalize__(
self, method="swaplevel"
)
def reorder_levels(self, order) -> "Series":
"""
Rearrange index levels using input order.
May not drop or duplicate levels.
Parameters
----------
order : list of int representing new level order
Reference level by number or key.
Returns
-------
type of caller (new object)
"""
if not isinstance(self.index, MultiIndex): # pragma: no cover
raise Exception("Can only reorder levels on a hierarchical axis.")
result = self.copy()
assert isinstance(result.index, MultiIndex)
result.index = result.index.reorder_levels(order)
return result
def explode(self, ignore_index: bool = False) -> "Series":
"""
Transform each element of a list-like to a row.
.. versionadded:: 0.25.0
Parameters
----------
ignore_index : bool, default False
If True, the resulting index will be labeled 0, 1, …, n - 1.
.. versionadded:: 1.1.0
Returns
-------
Series
Exploded lists to rows; index will be duplicated for these rows.
See Also
--------
Series.str.split : Split string values on specified separator.
Series.unstack : Unstack, a.k.a. pivot, Series with MultiIndex
to produce DataFrame.
DataFrame.melt : Unpivot a DataFrame from wide format to long format.
DataFrame.explode : Explode a DataFrame from list-like
columns to long format.
Notes
-----
This routine will explode list-likes including lists, tuples,
Series, and np.ndarray. The result dtype of the subset rows will
be object. Scalars will be returned unchanged. Empty list-likes will
result in a np.nan for that row.
Examples
--------
>>> s = pd.Series([[1, 2, 3], 'foo', [], [3, 4]])
>>> s
0 [1, 2, 3]
1 foo
2 []
3 [3, 4]
dtype: object
>>> s.explode()
0 1
0 2
0 3
1 foo
2 NaN
3 3
3 4
dtype: object
"""
if not len(self) or not is_object_dtype(self):
return self.copy()
values, counts = reshape.explode(np.asarray(self.array))
if ignore_index:
index = ibase.default_index(len(values))
else:
index = self.index.repeat(counts)
result = self._constructor(values, index=index, name=self.name)
return result
def unstack(self, level=-1, fill_value=None):
"""
Unstack, also known as pivot, Series with MultiIndex to produce DataFrame.
Parameters
----------
level : int, str, or list of these, default last level
Level(s) to unstack, can pass level name.
fill_value : scalar value, default None
Value to use when replacing NaN values.
Returns
-------
DataFrame
Unstacked Series.
Examples
--------
>>> s = pd.Series([1, 2, 3, 4],
... index=pd.MultiIndex.from_product([['one', 'two'],
... ['a', 'b']]))
>>> s
one a 1
b 2
two a 3
b 4
dtype: int64
>>> s.unstack(level=-1)
a b
one 1 2
two 3 4
>>> s.unstack(level=0)
one two
a 1 3
b 2 4
"""
from pandas.core.reshape.reshape import unstack
return unstack(self, level, fill_value)
# ----------------------------------------------------------------------
# function application
def map(self, arg, na_action=None) -> "Series":
"""
Map values of Series according to input correspondence.
Used for substituting each value in a Series with another value,
that may be derived from a function, a ``dict`` or
a :class:`Series`.
Parameters
----------
arg : function, collections.abc.Mapping subclass or Series
Mapping correspondence.
na_action : {None, 'ignore'}, default None
If 'ignore', propagate NaN values, without passing them to the
mapping correspondence.
Returns
-------
Series
Same index as caller.
See Also
--------
Series.apply : For applying more complex functions on a Series.
DataFrame.apply : Apply a function row-/column-wise.
DataFrame.applymap : Apply a function elementwise on a whole DataFrame.
Notes
-----
When ``arg`` is a dictionary, values in Series that are not in the
dictionary (as keys) are converted to ``NaN``. However, if the
dictionary is a ``dict`` subclass that defines ``__missing__`` (i.e.
provides a method for default values), then this default is used
rather than ``NaN``.
Examples
--------
>>> s = pd.Series(['cat', 'dog', np.nan, 'rabbit'])
>>> s
0 cat
1 dog
2 NaN
3 rabbit
dtype: object
``map`` accepts a ``dict`` or a ``Series``. Values that are not found
in the ``dict`` are converted to ``NaN``, unless the dict has a default
value (e.g. ``defaultdict``):
>>> s.map({'cat': 'kitten', 'dog': 'puppy'})
0 kitten
1 puppy
2 NaN
3 NaN
dtype: object
It also accepts a function:
>>> s.map('I am a {}'.format)
0 I am a cat
1 I am a dog
2 I am a nan
3 I am a rabbit
dtype: object
To avoid applying the function to missing values (and keep them as
``NaN``) ``na_action='ignore'`` can be used:
>>> s.map('I am a {}'.format, na_action='ignore')
0 I am a cat
1 I am a dog
2 NaN
3 I am a rabbit
dtype: object
"""
new_values = super()._map_values(arg, na_action=na_action)
return self._constructor(new_values, index=self.index).__finalize__(
self, method="map"
)
def _gotitem(self, key, ndim, subset=None) -> "Series":
"""
Sub-classes to define. Return a sliced object.
Parameters
----------
key : string / list of selections
ndim : 1,2
Requested ndim of result.
subset : object, default None
Subset to act on.
"""
return self
_agg_see_also_doc = dedent(
"""
See Also
--------
Series.apply : Invoke function on a Series.
Series.transform : Transform function producing a Series with like indexes.
"""
)
_agg_examples_doc = dedent(
"""
Examples
--------
>>> s = pd.Series([1, 2, 3, 4])
>>> s
0 1
1 2
2 3
3 4
dtype: int64
>>> s.agg('min')
1
>>> s.agg(['min', 'max'])
min 1
max 4
dtype: int64
"""
)
@doc(
generic._shared_docs["aggregate"],
klass=_shared_doc_kwargs["klass"],
axis=_shared_doc_kwargs["axis"],
see_also=_agg_see_also_doc,
examples=_agg_examples_doc,
versionadded="\n.. versionadded:: 0.20.0\n",
)
def aggregate(self, func=None, axis=0, *args, **kwargs):
# Validate the axis parameter
self._get_axis_number(axis)
# if func is None, will switch to user-provided "named aggregation" kwargs
if func is None:
func = dict(kwargs.items())
result, how = self._aggregate(func, *args, **kwargs)
if result is None:
# we can be called from an inner function which
# passes this meta-data
kwargs.pop("_axis", None)
kwargs.pop("_level", None)
# try a regular apply, this evaluates lambdas
# row-by-row; however if the lambda is expected a Series
# expression, e.g.: lambda x: x-x.quantile(0.25)
# this will fail, so we can try a vectorized evaluation
# we cannot FIRST try the vectorized evaluation, because
# then .agg and .apply would have different semantics if the
# operation is actually defined on the Series, e.g. str
try:
result = self.apply(func, *args, **kwargs)
except (ValueError, AttributeError, TypeError):
result = func(self, *args, **kwargs)
return result
agg = aggregate
@doc(
NDFrame.transform,
klass=_shared_doc_kwargs["klass"],
axis=_shared_doc_kwargs["axis"],
)
def transform(self, func, axis=0, *args, **kwargs):
# Validate the axis parameter
self._get_axis_number(axis)
return super().transform(func, *args, **kwargs)
def apply(self, func, convert_dtype=True, args=(), **kwds):
"""
Invoke function on values of Series.
Can be ufunc (a NumPy function that applies to the entire Series)
or a Python function that only works on single values.
Parameters
----------
func : function
Python function or NumPy ufunc to apply.
convert_dtype : bool, default True
Try to find better dtype for elementwise function results. If
False, leave as dtype=object.
args : tuple
Positional arguments passed to func after the series value.
**kwds
Additional keyword arguments passed to func.
Returns
-------
Series or DataFrame
If func returns a Series object the result will be a DataFrame.
See Also
--------
Series.map: For element-wise operations.
Series.agg: Only perform aggregating type operations.
Series.transform: Only perform transforming type operations.
Examples
--------
Create a series with typical summer temperatures for each city.
>>> s = pd.Series([20, 21, 12],
... index=['London', 'New York', 'Helsinki'])
>>> s
London 20
New York 21
Helsinki 12
dtype: int64
Square the values by defining a function and passing it as an
argument to ``apply()``.
>>> def square(x):
... return x ** 2
>>> s.apply(square)
London 400
New York 441
Helsinki 144
dtype: int64
Square the values by passing an anonymous function as an
argument to ``apply()``.
>>> s.apply(lambda x: x ** 2)
London 400
New York 441
Helsinki 144
dtype: int64
Define a custom function that needs additional positional
arguments and pass these additional arguments using the
``args`` keyword.
>>> def subtract_custom_value(x, custom_value):
... return x - custom_value
>>> s.apply(subtract_custom_value, args=(5,))
London 15
New York 16
Helsinki 7
dtype: int64
Define a custom function that takes keyword arguments
and pass these arguments to ``apply``.
>>> def add_custom_values(x, **kwargs):
... for month in kwargs:
... x += kwargs[month]
... return x
>>> s.apply(add_custom_values, june=30, july=20, august=25)
London 95
New York 96
Helsinki 87
dtype: int64
Use a function from the Numpy library.
>>> s.apply(np.log)
London 2.995732
New York 3.044522
Helsinki 2.484907
dtype: float64
"""
if len(self) == 0:
return self._constructor(dtype=self.dtype, index=self.index).__finalize__(
self, method="apply"
)
# dispatch to agg
if isinstance(func, (list, dict)):
return self.aggregate(func, *args, **kwds)
# if we are a string, try to dispatch
if isinstance(func, str):
return self._try_aggregate_string_function(func, *args, **kwds)
# handle ufuncs and lambdas
if kwds or args and not isinstance(func, np.ufunc):
def f(x):
return func(x, *args, **kwds)
else:
f = func
with np.errstate(all="ignore"):
if isinstance(f, np.ufunc):
return f(self)
# row-wise access
if is_extension_array_dtype(self.dtype) and hasattr(self._values, "map"):
# GH#23179 some EAs do not have `map`
mapped = self._values.map(f)
else:
values = self.astype(object)._values
mapped = lib.map_infer(values, f, convert=convert_dtype)
if len(mapped) and isinstance(mapped[0], Series):
# GH 25959 use pd.array instead of tolist
# so extension arrays can be used
return self._constructor_expanddim(pd.array(mapped), index=self.index)
else:
return self._constructor(mapped, index=self.index).__finalize__(
self, method="apply"
)
def _reduce(
self, op, name, axis=0, skipna=True, numeric_only=None, filter_type=None, **kwds
):
"""
Perform a reduction operation.
If we have an ndarray as a value, then simply perform the operation,
otherwise delegate to the object.
"""
delegate = self._values
if axis is not None:
self._get_axis_number(axis)
if isinstance(delegate, ExtensionArray):
# dispatch to ExtensionArray interface
return delegate._reduce(name, skipna=skipna, **kwds)
else:
# dispatch to numpy arrays
if numeric_only:
raise NotImplementedError(
f"Series.{name} does not implement numeric_only."
)
with np.errstate(all="ignore"):
return op(delegate, skipna=skipna, **kwds)
def _reindex_indexer(self, new_index, indexer, copy):
if indexer is None:
if copy:
return self.copy()
return self
new_values = algorithms.take_1d(
self._values, indexer, allow_fill=True, fill_value=None
)
return self._constructor(new_values, index=new_index)
def _needs_reindex_multi(self, axes, method, level):
"""
Check if we do need a multi reindex; this is for compat with
higher dims.
"""
return False
@doc(
NDFrame.align,
klass=_shared_doc_kwargs["klass"],
axes_single_arg=_shared_doc_kwargs["axes_single_arg"],
)
def align(
self,
other,
join="outer",
axis=None,
level=None,
copy=True,
fill_value=None,
method=None,
limit=None,
fill_axis=0,
broadcast_axis=None,
):
return super().align(
other,
join=join,
axis=axis,
level=level,
copy=copy,
fill_value=fill_value,
method=method,
limit=limit,
fill_axis=fill_axis,
broadcast_axis=broadcast_axis,
)
def rename(
self,
index=None,
*,
axis=None,
copy=True,
inplace=False,
level=None,
errors="ignore",
):
"""
Alter Series index labels or name.
Function / dict values must be unique (1-to-1). Labels not contained in
a dict / Series will be left as-is. Extra labels listed don't throw an
error.
Alternatively, change ``Series.name`` with a scalar value.
See the :ref:`user guide <basics.rename>` for more.
Parameters
----------
axis : {0 or "index"}
Unused. Accepted for compatibility with DataFrame method only.
index : scalar, hashable sequence, dict-like or function, optional
Functions or dict-like are transformations to apply to
the index.
Scalar or hashable sequence-like will alter the ``Series.name``
attribute.
**kwargs
Additional keyword arguments passed to the function. Only the
"inplace" keyword is used.
Returns
-------
Series
Series with index labels or name altered.
See Also
--------
DataFrame.rename : Corresponding DataFrame method.
Series.rename_axis : Set the name of the axis.
Examples
--------
>>> s = pd.Series([1, 2, 3])
>>> s
0 1
1 2
2 3
dtype: int64
>>> s.rename("my_name") # scalar, changes Series.name
0 1
1 2
2 3
Name: my_name, dtype: int64
>>> s.rename(lambda x: x ** 2) # function, changes labels
0 1
1 2
4 3
dtype: int64
>>> s.rename({1: 3, 2: 5}) # mapping, changes labels
0 1
3 2
5 3
dtype: int64
"""
if callable(index) or is_dict_like(index):
return super().rename(
index, copy=copy, inplace=inplace, level=level, errors=errors
)
else:
return self._set_name(index, inplace=inplace)
@Appender(
"""
Examples
--------
>>> s = pd.Series([1, 2, 3])
>>> s
0 1
1 2
2 3
dtype: int64
>>> s.set_axis(['a', 'b', 'c'], axis=0)
a 1
b 2
c 3
dtype: int64
"""
)
@Substitution(
**_shared_doc_kwargs,
extended_summary_sub="",
axis_description_sub="",
see_also_sub="",
)
@Appender(generic.NDFrame.set_axis.__doc__)
def set_axis(self, labels, axis: Axis = 0, inplace: bool = False):
return super().set_axis(labels, axis=axis, inplace=inplace)
@doc(
NDFrame.reindex,
klass=_shared_doc_kwargs["klass"],
axes=_shared_doc_kwargs["axes"],
optional_labels=_shared_doc_kwargs["optional_labels"],
optional_axis=_shared_doc_kwargs["optional_axis"],
)
def reindex(self, index=None, **kwargs):
return super().reindex(index=index, **kwargs)
def drop(
self,
labels=None,
axis=0,
index=None,
columns=None,
level=None,
inplace=False,
errors="raise",
) -> "Series":
"""
Return Series with specified index labels removed.
Remove elements of a Series based on specifying the index labels.
When using a multi-index, labels on different levels can be removed
by specifying the level.
Parameters
----------
labels : single label or list-like
Index labels to drop.
axis : 0, default 0
Redundant for application on Series.
index : single label or list-like
Redundant for application on Series, but 'index' can be used instead
of 'labels'.
columns : single label or list-like
No change is made to the Series; use 'index' or 'labels' instead.
level : int or level name, optional
For MultiIndex, level for which the labels will be removed.
inplace : bool, default False
If True, do operation inplace and return None.
errors : {'ignore', 'raise'}, default 'raise'
If 'ignore', suppress error and only existing labels are dropped.
Returns
-------
Series
Series with specified index labels removed.
Raises
------
KeyError
If none of the labels are found in the index.
See Also
--------
Series.reindex : Return only specified index labels of Series.
Series.dropna : Return series without null values.
Series.drop_duplicates : Return Series with duplicate values removed.
DataFrame.drop : Drop specified labels from rows or columns.
Examples
--------
>>> s = pd.Series(data=np.arange(3), index=['A', 'B', 'C'])
>>> s
A 0
B 1
C 2
dtype: int64
Drop labels B en C
>>> s.drop(labels=['B', 'C'])
A 0
dtype: int64
Drop 2nd level label in MultiIndex Series
>>> midx = pd.MultiIndex(levels=[['lama', 'cow', 'falcon'],
... ['speed', 'weight', 'length']],
... codes=[[0, 0, 0, 1, 1, 1, 2, 2, 2],
... [0, 1, 2, 0, 1, 2, 0, 1, 2]])
>>> s = pd.Series([45, 200, 1.2, 30, 250, 1.5, 320, 1, 0.3],
... index=midx)
>>> s
lama speed 45.0
weight 200.0
length 1.2
cow speed 30.0
weight 250.0
length 1.5
falcon speed 320.0
weight 1.0
length 0.3
dtype: float64
>>> s.drop(labels='weight', level=1)
lama speed 45.0
length 1.2
cow speed 30.0
length 1.5
falcon speed 320.0
length 0.3
dtype: float64
"""
return super().drop(
labels=labels,
axis=axis,
index=index,
columns=columns,
level=level,
inplace=inplace,
errors=errors,
)
@doc(NDFrame.fillna, **_shared_doc_kwargs)
def fillna(
self,
value=None,
method=None,
axis=None,
inplace=False,
limit=None,
downcast=None,
) -> Optional["Series"]:
return super().fillna(
value=value,
method=method,
axis=axis,
inplace=inplace,
limit=limit,
downcast=downcast,
)
def pop(self, item: Label) -> Any:
"""
Return item and drops from series. Raise KeyError if not found.
Parameters
----------
item : label
Index of the element that needs to be removed.
Returns
-------
Value that is popped from series.
Examples
--------
>>> ser = pd.Series([1,2,3])
>>> ser.pop(0)
1
>>> ser
1 2
2 3
dtype: int64
"""
return super().pop(item=item)
@doc(NDFrame.replace, klass=_shared_doc_kwargs["klass"])
def replace(
self,
to_replace=None,
value=None,
inplace=False,
limit=None,
regex=False,
method="pad",
):
return super().replace(
to_replace=to_replace,
value=value,
inplace=inplace,
limit=limit,
regex=regex,
method=method,
)
@doc(NDFrame.shift, klass=_shared_doc_kwargs["klass"])
def shift(self, periods=1, freq=None, axis=0, fill_value=None) -> "Series":
return super().shift(
periods=periods, freq=freq, axis=axis, fill_value=fill_value
)
def memory_usage(self, index=True, deep=False):
"""
Return the memory usage of the Series.
The memory usage can optionally include the contribution of
the index and of elements of `object` dtype.
Parameters
----------
index : bool, default True
Specifies whether to include the memory usage of the Series index.
deep : bool, default False
If True, introspect the data deeply by interrogating
`object` dtypes for system-level memory consumption, and include
it in the returned value.
Returns
-------
int
Bytes of memory consumed.
See Also
--------
numpy.ndarray.nbytes : Total bytes consumed by the elements of the
array.
DataFrame.memory_usage : Bytes consumed by a DataFrame.
Examples
--------
>>> s = pd.Series(range(3))
>>> s.memory_usage()
152
Not including the index gives the size of the rest of the data, which
is necessarily smaller:
>>> s.memory_usage(index=False)
24
The memory footprint of `object` values is ignored by default:
>>> s = pd.Series(["a", "b"])
>>> s.values
array(['a', 'b'], dtype=object)
>>> s.memory_usage()
144
>>> s.memory_usage(deep=True)
260
"""
v = super().memory_usage(deep=deep)
if index:
v += self.index.memory_usage(deep=deep)
return v
def isin(self, values) -> "Series":
"""
Whether elements in Series are contained in `values`.
Return a boolean Series showing whether each element in the Series
matches an element in the passed sequence of `values` exactly.
Parameters
----------
values : set or list-like
The sequence of values to test. Passing in a single string will
raise a ``TypeError``. Instead, turn a single string into a
list of one element.
Returns
-------
Series
Series of booleans indicating if each element is in values.
Raises
------
TypeError
* If `values` is a string
See Also
--------
DataFrame.isin : Equivalent method on DataFrame.
Examples
--------
>>> s = pd.Series(['lama', 'cow', 'lama', 'beetle', 'lama',
... 'hippo'], name='animal')
>>> s.isin(['cow', 'lama'])
0 True
1 True
2 True
3 False
4 True
5 False
Name: animal, dtype: bool
Passing a single string as ``s.isin('lama')`` will raise an error. Use
a list of one element instead:
>>> s.isin(['lama'])
0 True
1 False
2 True
3 False
4 True
5 False
Name: animal, dtype: bool
"""
result = algorithms.isin(self, values)
return self._constructor(result, index=self.index).__finalize__(
self, method="isin"
)
def between(self, left, right, inclusive=True) -> "Series":
"""
Return boolean Series equivalent to left <= series <= right.
This function returns a boolean vector containing `True` wherever the
corresponding Series element is between the boundary values `left` and
`right`. NA values are treated as `False`.
Parameters
----------
left : scalar or list-like
Left boundary.
right : scalar or list-like
Right boundary.
inclusive : bool, default True
Include boundaries.
Returns
-------
Series
Series representing whether each element is between left and
right (inclusive).
See Also
--------
Series.gt : Greater than of series and other.
Series.lt : Less than of series and other.
Notes
-----
This function is equivalent to ``(left <= ser) & (ser <= right)``
Examples
--------
>>> s = pd.Series([2, 0, 4, 8, np.nan])
Boundary values are included by default:
>>> s.between(1, 4)
0 True
1 False
2 True
3 False
4 False
dtype: bool
With `inclusive` set to ``False`` boundary values are excluded:
>>> s.between(1, 4, inclusive=False)
0 True
1 False
2 False
3 False
4 False
dtype: bool
`left` and `right` can be any scalar value:
>>> s = pd.Series(['Alice', 'Bob', 'Carol', 'Eve'])
>>> s.between('Anna', 'Daniel')
0 False
1 True
2 True
3 False
dtype: bool
"""
if inclusive:
lmask = self >= left
rmask = self <= right
else:
lmask = self > left
rmask = self < right
return lmask & rmask
# ----------------------------------------------------------------------
# Convert to types that support pd.NA
def _convert_dtypes(
self,
infer_objects: bool = True,
convert_string: bool = True,
convert_integer: bool = True,
convert_boolean: bool = True,
) -> "Series":
input_series = self
if infer_objects:
input_series = input_series.infer_objects()
if is_object_dtype(input_series):
input_series = input_series.copy()
if convert_string or convert_integer or convert_boolean:
inferred_dtype = convert_dtypes(
input_series._values, convert_string, convert_integer, convert_boolean
)
try:
result = input_series.astype(inferred_dtype)
except TypeError:
result = input_series.copy()
else:
result = input_series.copy()
return result
@doc(NDFrame.isna, klass=_shared_doc_kwargs["klass"])
def isna(self) -> "Series":
return super().isna()
@doc(NDFrame.isna, klass=_shared_doc_kwargs["klass"])
def isnull(self) -> "Series":
return super().isnull()
@doc(NDFrame.notna, klass=_shared_doc_kwargs["klass"])
def notna(self) -> "Series":
return super().notna()
@doc(NDFrame.notna, klass=_shared_doc_kwargs["klass"])
def notnull(self) -> "Series":
return super().notnull()
def dropna(self, axis=0, inplace=False, how=None):
"""
Return a new Series with missing values removed.
See the :ref:`User Guide <missing_data>` for more on which values are
considered missing, and how to work with missing data.
Parameters
----------
axis : {0 or 'index'}, default 0
There is only one axis to drop values from.
inplace : bool, default False
If True, do operation inplace and return None.
how : str, optional
Not in use. Kept for compatibility.
Returns
-------
Series
Series with NA entries dropped from it.
See Also
--------
Series.isna: Indicate missing values.
Series.notna : Indicate existing (non-missing) values.
Series.fillna : Replace missing values.
DataFrame.dropna : Drop rows or columns which contain NA values.
Index.dropna : Drop missing indices.
Examples
--------
>>> ser = pd.Series([1., 2., np.nan])
>>> ser
0 1.0
1 2.0
2 NaN
dtype: float64
Drop NA values from a Series.
>>> ser.dropna()
0 1.0
1 2.0
dtype: float64
Keep the Series with valid entries in the same variable.
>>> ser.dropna(inplace=True)
>>> ser
0 1.0
1 2.0
dtype: float64
Empty strings are not considered NA values. ``None`` is considered an
NA value.
>>> ser = pd.Series([np.NaN, 2, pd.NaT, '', None, 'I stay'])
>>> ser
0 NaN
1 2
2 NaT
3
4 None
5 I stay
dtype: object
>>> ser.dropna()
1 2
3
5 I stay
dtype: object
"""
inplace = validate_bool_kwarg(inplace, "inplace")
# Validate the axis parameter
self._get_axis_number(axis or 0)
if self._can_hold_na:
result = remove_na_arraylike(self)
if inplace:
self._update_inplace(result)
else:
return result
else:
if inplace:
# do nothing
pass
else:
return self.copy()
# ----------------------------------------------------------------------
# Time series-oriented methods
def to_timestamp(self, freq=None, how="start", copy=True) -> "Series":
"""
Cast to DatetimeIndex of Timestamps, at *beginning* of period.
Parameters
----------
freq : str, default frequency of PeriodIndex
Desired frequency.
how : {'s', 'e', 'start', 'end'}
Convention for converting period to timestamp; start of period
vs. end.
copy : bool, default True
Whether or not to return a copy.
Returns
-------
Series with DatetimeIndex
"""
new_values = self._values
if copy:
new_values = new_values.copy()
if not isinstance(self.index, PeriodIndex):
raise TypeError(f"unsupported Type {type(self.index).__name__}")
new_index = self.index.to_timestamp(freq=freq, how=how) # type: ignore
return self._constructor(new_values, index=new_index).__finalize__(
self, method="to_timestamp"
)
def to_period(self, freq=None, copy=True) -> "Series":
"""
Convert Series from DatetimeIndex to PeriodIndex.
Parameters
----------
freq : str, default None
Frequency associated with the PeriodIndex.
copy : bool, default True
Whether or not to return a copy.
Returns
-------
Series
Series with index converted to PeriodIndex.
"""
new_values = self._values
if copy:
new_values = new_values.copy()
if not isinstance(self.index, DatetimeIndex):
raise TypeError(f"unsupported Type {type(self.index).__name__}")
new_index = self.index.to_period(freq=freq)
return self._constructor(new_values, index=new_index).__finalize__(
self, method="to_period"
)
# ----------------------------------------------------------------------
# Add index
_AXIS_ORDERS = ["index"]
_AXIS_REVERSED = False
_AXIS_LEN = len(_AXIS_ORDERS)
_info_axis_number = 0
_info_axis_name = "index"
index: "Index" = properties.AxisProperty(
axis=0, doc="The index (axis labels) of the Series."
)
# ----------------------------------------------------------------------
# Accessor Methods
# ----------------------------------------------------------------------
str = CachedAccessor("str", StringMethods)
dt = CachedAccessor("dt", CombinedDatetimelikeProperties)
cat = CachedAccessor("cat", CategoricalAccessor)
plot = CachedAccessor("plot", pandas.plotting.PlotAccessor)
sparse = CachedAccessor("sparse", SparseAccessor)
# ----------------------------------------------------------------------
# Add plotting methods to Series
hist = pandas.plotting.hist_series
Series._add_numeric_operations()
Series._add_series_or_dataframe_operations()
# Add arithmetic!
ops.add_flex_arithmetic_methods(Series)
ops.add_special_arithmetic_methods(Series)
|
the-stack_0_8495 | """
Support for Wink lights.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/light.wink/
"""
import colorsys
from homeassistant.components.light import (
ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_RGB_COLOR, SUPPORT_BRIGHTNESS,
SUPPORT_COLOR_TEMP, SUPPORT_RGB_COLOR, Light)
from homeassistant.components.wink import WinkDevice
from homeassistant.util import color as color_util
from homeassistant.util.color import \
color_temperature_mired_to_kelvin as mired_to_kelvin
DEPENDENCIES = ['wink']
SUPPORT_WINK = SUPPORT_BRIGHTNESS | SUPPORT_COLOR_TEMP | SUPPORT_RGB_COLOR
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Wink lights."""
import pywink
add_devices(WinkLight(light, hass) for light in pywink.get_bulbs())
class WinkLight(WinkDevice, Light):
"""Representation of a Wink light."""
def __init__(self, wink, hass):
"""Initialize the Wink device."""
WinkDevice.__init__(self, wink, hass)
@property
def is_on(self):
"""Return true if light is on."""
return self.wink.state()
@property
def brightness(self):
"""Return the brightness of the light."""
if self.wink.brightness() is not None:
return int(self.wink.brightness() * 255)
else:
return None
@property
def rgb_color(self):
"""Current bulb color in RGB."""
if not self.wink.supports_hue_saturation():
return None
else:
hue = self.wink.color_hue()
saturation = self.wink.color_saturation()
value = int(self.wink.brightness() * 255)
if hue is None or saturation is None or value is None:
return None
rgb = colorsys.hsv_to_rgb(hue, saturation, value)
r_value = int(round(rgb[0]))
g_value = int(round(rgb[1]))
b_value = int(round(rgb[2]))
return r_value, g_value, b_value
@property
def xy_color(self):
"""Current bulb color in CIE 1931 (XY) color space."""
if not self.wink.supports_xy_color():
return None
return self.wink.color_xy()
@property
def color_temp(self):
"""Current bulb color in degrees Kelvin."""
if not self.wink.supports_temperature():
return None
return color_util.color_temperature_kelvin_to_mired(
self.wink.color_temperature_kelvin())
@property
def supported_features(self):
"""Flag supported features."""
return SUPPORT_WINK
def turn_on(self, **kwargs):
"""Turn the switch on."""
brightness = kwargs.get(ATTR_BRIGHTNESS)
rgb_color = kwargs.get(ATTR_RGB_COLOR)
color_temp_mired = kwargs.get(ATTR_COLOR_TEMP)
state_kwargs = {
}
if rgb_color:
if self.wink.supports_xy_color():
xyb = color_util.color_RGB_to_xy(*rgb_color)
state_kwargs['color_xy'] = xyb[0], xyb[1]
state_kwargs['brightness'] = xyb[2]
elif self.wink.supports_hue_saturation():
hsv = colorsys.rgb_to_hsv(rgb_color[0],
rgb_color[1], rgb_color[2])
state_kwargs['color_hue_saturation'] = hsv[0], hsv[1]
if color_temp_mired:
state_kwargs['color_kelvin'] = mired_to_kelvin(color_temp_mired)
if brightness:
state_kwargs['brightness'] = brightness / 255.0
self.wink.set_state(True, **state_kwargs)
def turn_off(self):
"""Turn the switch off."""
self.wink.set_state(False)
|
the-stack_0_8496 | """
Django settings for healthchecks project.
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings
"""
import os
import warnings
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
def envbool(s, default):
v = os.getenv(s, default=default)
if v not in ("", "True", "False"):
msg = "Unexpected value %s=%s, use 'True' or 'False'" % (s, v)
raise Exception(msg)
return v == "True"
def envint(s, default):
v = os.getenv(s, default)
if v == "None":
return None
return int(v)
SECRET_KEY = os.getenv("SECRET_KEY", "---")
METRICS_KEY = os.getenv("METRICS_KEY")
DEBUG = envbool("DEBUG", "True")
ALLOWED_HOSTS = os.getenv("ALLOWED_HOSTS", "*").split(",")
DEFAULT_FROM_EMAIL = os.getenv("DEFAULT_FROM_EMAIL", "[email protected]")
SUPPORT_EMAIL = os.getenv("SUPPORT_EMAIL")
USE_PAYMENTS = envbool("USE_PAYMENTS", "False")
REGISTRATION_OPEN = envbool("REGISTRATION_OPEN", "True")
VERSION = ""
with open(os.path.join(BASE_DIR, "CHANGELOG.md"), encoding="utf-8") as f:
for line in f.readlines():
if line.startswith("## v"):
VERSION = line.split()[1]
break
INSTALLED_APPS = (
"hc.accounts",
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.humanize",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"compressor",
"hc.api",
"hc.front",
"hc.payments",
)
MIDDLEWARE = (
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
"django.middleware.locale.LocaleMiddleware",
"hc.accounts.middleware.TeamAccessMiddleware",
)
AUTHENTICATION_BACKENDS = (
"hc.accounts.backends.EmailBackend",
"hc.accounts.backends.ProfileBackend",
)
ROOT_URLCONF = "hc.urls"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [os.path.join(BASE_DIR, "templates")],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
"hc.front.context_processors.branding",
"hc.payments.context_processors.payments",
]
},
}
]
WSGI_APPLICATION = "hc.wsgi.application"
TEST_RUNNER = "hc.api.tests.CustomRunner"
# Default database engine is SQLite. So one can just check out code,
# install requirements.txt and do manage.py runserver and it works
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": os.getenv("DB_NAME", BASE_DIR + "/hc.sqlite"),
}
}
# You can switch database engine to postgres or mysql using environment
# variable 'DB'. Travis CI does this.
if os.getenv("DB") == "postgres":
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"HOST": os.getenv("DB_HOST", ""),
"PORT": os.getenv("DB_PORT", ""),
"NAME": os.getenv("DB_NAME", "hc"),
"USER": os.getenv("DB_USER", "postgres"),
"PASSWORD": os.getenv("DB_PASSWORD", ""),
"CONN_MAX_AGE": envint("DB_CONN_MAX_AGE", "0"),
"TEST": {"CHARSET": "UTF8"},
"OPTIONS": {
"sslmode": os.getenv("DB_SSLMODE", "prefer"),
"target_session_attrs": os.getenv(
"DB_TARGET_SESSION_ATTRS", "read-write"
),
},
}
}
if os.getenv("DB") == "mysql":
DATABASES = {
"default": {
"ENGINE": "django.db.backends.mysql",
"HOST": os.getenv("DB_HOST", ""),
"PORT": os.getenv("DB_PORT", ""),
"NAME": os.getenv("DB_NAME", "hc"),
"USER": os.getenv("DB_USER", "root"),
"PASSWORD": os.getenv("DB_PASSWORD", ""),
"TEST": {"CHARSET": "UTF8"},
}
}
USE_TZ = True
TIME_ZONE = "UTC"
USE_I18N = True
USE_L10N = False
LOCALE_PATHS = (os.path.join(BASE_DIR, "locale"),)
SITE_ROOT = os.getenv("SITE_ROOT", "http://localhost:8000")
SITE_NAME = os.getenv("SITE_NAME", "Mychecks")
MASTER_BADGE_LABEL = os.getenv("MASTER_BADGE_LABEL", SITE_NAME)
PING_ENDPOINT = os.getenv("PING_ENDPOINT", SITE_ROOT + "/ping/")
PING_EMAIL_DOMAIN = os.getenv("PING_EMAIL_DOMAIN", "localhost")
PING_BODY_LIMIT = envint("PING_BODY_LIMIT", "10000")
STATIC_URL = "/static/"
STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")]
STATIC_ROOT = os.path.join(BASE_DIR, "static-collected")
STATICFILES_FINDERS = (
"django.contrib.staticfiles.finders.FileSystemFinder",
"django.contrib.staticfiles.finders.AppDirectoriesFinder",
"compressor.finders.CompressorFinder",
)
COMPRESS_OFFLINE = True
COMPRESS_CSS_HASHING_METHOD = "content"
# Discord integration
DISCORD_CLIENT_ID = os.getenv("DISCORD_CLIENT_ID")
DISCORD_CLIENT_SECRET = os.getenv("DISCORD_CLIENT_SECRET")
# Email integration
EMAIL_HOST = os.getenv("EMAIL_HOST", "")
EMAIL_PORT = envint("EMAIL_PORT", "587")
EMAIL_HOST_USER = os.getenv("EMAIL_HOST_USER", "")
EMAIL_HOST_PASSWORD = os.getenv("EMAIL_HOST_PASSWORD", "")
EMAIL_USE_TLS = envbool("EMAIL_USE_TLS", "True")
EMAIL_USE_VERIFICATION = envbool("EMAIL_USE_VERIFICATION", "True")
# Slack integration
SLACK_CLIENT_ID = os.getenv("SLACK_CLIENT_ID")
SLACK_CLIENT_SECRET = os.getenv("SLACK_CLIENT_SECRET")
# Pushover integration
PUSHOVER_API_TOKEN = os.getenv("PUSHOVER_API_TOKEN")
PUSHOVER_SUBSCRIPTION_URL = os.getenv("PUSHOVER_SUBSCRIPTION_URL")
PUSHOVER_EMERGENCY_RETRY_DELAY = int(os.getenv("PUSHOVER_EMERGENCY_RETRY_DELAY", "300"))
PUSHOVER_EMERGENCY_EXPIRATION = int(os.getenv("PUSHOVER_EMERGENCY_EXPIRATION", "86400"))
# Pushbullet integration
PUSHBULLET_CLIENT_ID = os.getenv("PUSHBULLET_CLIENT_ID")
PUSHBULLET_CLIENT_SECRET = os.getenv("PUSHBULLET_CLIENT_SECRET")
# Telegram integration -- override in local_settings.py
TELEGRAM_BOT_NAME = os.getenv("TELEGRAM_BOT_NAME", "ExampleBot")
TELEGRAM_TOKEN = os.getenv("TELEGRAM_TOKEN")
# SMS and WhatsApp (Twilio) integration
TWILIO_ACCOUNT = os.getenv("TWILIO_ACCOUNT")
TWILIO_AUTH = os.getenv("TWILIO_AUTH")
TWILIO_FROM = os.getenv("TWILIO_FROM")
TWILIO_USE_WHATSAPP = envbool("TWILIO_USE_WHATSAPP", "False")
# PagerDuty
PD_VENDOR_KEY = os.getenv("PD_VENDOR_KEY")
# Trello
TRELLO_APP_KEY = os.getenv("TRELLO_APP_KEY")
# Matrix
MATRIX_HOMESERVER = os.getenv("MATRIX_HOMESERVER")
MATRIX_USER_ID = os.getenv("MATRIX_USER_ID")
MATRIX_ACCESS_TOKEN = os.getenv("MATRIX_ACCESS_TOKEN")
# Apprise
APPRISE_ENABLED = envbool("APPRISE_ENABLED", "False")
# Local shell commands
SHELL_ENABLED = envbool("SHELL_ENABLED", "False")
# LINE Notify
LINENOTIFY_CLIENT_ID = os.getenv("LINENOTIFY_CLIENT_ID")
LINENOTIFY_CLIENT_SECRET = os.getenv("LINENOTIFY_CLIENT_SECRET")
if os.path.exists(os.path.join(BASE_DIR, "hc/local_settings.py")):
from .local_settings import *
else:
warnings.warn("local_settings.py not found, using defaults")
|
the-stack_0_8497 | # Copyright (c) Microsoft Corporation
# Licensed under the MIT License.
"""Defines the dashboard class."""
import json
import os
import uuid
from html.parser import HTMLParser
from rai_core_flask import FlaskHelper # , environment_detector
from responsibleai.serialization_utilities import serialize_json_safe
class InLineScript(HTMLParser):
def __init__(self, load_widget_file):
HTMLParser.__init__(self)
self.content = ""
self.load_widget_file = load_widget_file
def handle_starttag(self, tag, attrs):
if tag == "script":
src = None
scriptTag = "<script "
for att in attrs:
if att[0] == "src":
src = att[1]
continue
# skip module type as it causes ipython to render widget
# with 8px height
if att[0] == "type":
continue
scriptTag += f' {att[0]}={att[1]}'
if src is not None:
content = self.load_widget_file(src)
self.content += f'{scriptTag}>\r\n{content}\r\n'
return
self.content += self.get_starttag_text()
def handle_endtag(self, tag):
self.content += f'</{tag}>'
pass
def handle_data(self, data):
self.content += data
pass
class Dashboard(object):
"""The dashboard class, wraps the dashboard component."""
def __init__(self, *,
dashboard_type,
model_data,
public_ip,
port,
locale,
no_inline_dashboard=False):
"""Initialize the dashboard."""
if model_data is None or type is None:
raise ValueError("Required parameters not provided")
try:
self._service = FlaskHelper(ip=public_ip, port=port)
except Exception as e:
self._service = None
raise e
self.id = uuid.uuid4().hex
self.config = {
'dashboardType': dashboard_type,
'id': self.id,
'baseUrl': self._service.env.base_url,
'withCredentials': self._service.with_credentials,
'locale': locale
}
self.model_data = model_data
self.add_route()
html = self.load_index()
print(f'{dashboard_type} started at {self._service.env.base_url}')
if no_inline_dashboard:
return
self._service.env.display(html)
def add_route(self):
# To enable multiple dashboards to run in the same notebook we need to
# prevent them from using the same method names (in addition to using
# dedicated ports). Below we rename the function for that purpose and
# manually add the URL rule instead of using the route decorator.
def visual():
return self.load_index()
self.add_url_rule(visual, '/', methods=["GET"])
return
@staticmethod
def get_widget_path(path):
script_path = os.path.dirname(os.path.abspath(__file__))
return os.path.join(script_path, "widget", path)
def load_index(self):
index = self.load_widget_file("index.html")
parser = InLineScript(self.load_widget_file)
parser.feed(index)
return parser.content
def load_widget_file(self, path):
js_path = Dashboard.get_widget_path(path)
with open(js_path, "r", encoding="utf-8") as f:
content = f.read()
content = content.replace(
"__rai_app_id__", f'rai_widget_{self.id}')
content = content.replace(
'"__rai_config__"', f'`{json.dumps(self.config)}`')
model_data = json.dumps(self.model_data,
default=serialize_json_safe)
content = content.replace(
'"__rai_model_data__"',
f'`{model_data}`')
return content
def add_url_rule(self, func, route, methods):
"""To enable multiple dashboards to run in the same notebook we need to
prevent them from using the same method names (in addition to using
dedicated ports). We rename the function for that purpose and
manually add the URL rule instead of using the route decorator.
"""
func.__name__ = func.__name__ + str(id(self))
self._service.app.add_url_rule(
route,
endpoint=func.__name__,
view_func=func,
methods=methods)
|
the-stack_0_8498 | import toppra
import numpy as np
from _mplib import *
import toppra as ta
import toppra.constraint as constraint
import toppra.algorithm as algo
from transforms3d.quaternions import quat2mat
from typing import Tuple
class Planner(object):
def __init__(
self,
urdf="./panda/panda.urdf",
srdf="./panda/panda.srdf",
# align the order of user links
user_link_names=['panda_link0', 'panda_link1', 'panda_link2', 'panda_link3',
'panda_link4', 'panda_link5', 'panda_link6', 'panda_link7',
'panda_link8', 'panda_hand', 'panda_leftfinger', 'panda_rightfinger'],
# align the order of user joints
user_joint_names=['panda_joint1', 'panda_joint2', 'panda_joint3', 'panda_joint4',
'panda_joint5', 'panda_joint6', 'panda_joint7',
'panda_finger_joint1', 'panda_finger_joint2'],
move_group="ee_link",
joint_vel_limits=np.ones(7),
joint_acc_limits=np.ones(7)
):
self.urdf = urdf
self.srdf = srdf
self.user_link_names = user_link_names
self.user_joint_names = user_joint_names
self.joint_name_2_idx = {}
for i, joint in enumerate(self.user_joint_names):
self.joint_name_2_idx[joint] = i
self.link_name_2_idx = {}
for i, link in enumerate(self.user_link_names):
self.link_name_2_idx[link] = i
self.robot = articulation.ArticulatedModel(urdf, srdf, [0, 0, -9.81], self.user_joint_names,
self.user_link_names, verbose=False, convex=True)
self.planning_world = planning_world.PlanningWorld([self.robot], ["robot"], [], [])
self.move_group = move_group
self.robot.set_move_group(self.move_group)
self.move_group_joint_indices = self.robot.get_move_group_joint_indices()
self.pinocchio_model = self.robot.get_pinocchio_model()
self.joint_types = self.pinocchio_model.get_joint_types()
self.joint_limits = np.concatenate(self.pinocchio_model.get_joint_limits())
self.planner = ompl.OMPLPlanner(world=self.planning_world)
self.joint_vel_limits = joint_vel_limits
self.joint_acc_limits = joint_acc_limits
self.move_group_link_id = self.link_name_2_idx[self.move_group]
assert(len(self.joint_vel_limits) == len(self.move_group_joint_indices))
assert(len(self.joint_acc_limits) == len(self.move_group_joint_indices))
def distance_6D(self, p1, q1, p2, q2):
return np.linalg.norm(p1 - p2) + min(np.linalg.norm(q1 - q2), np.linalg.norm(q1 + q2))
def check_joint_limit(self, q):
n = len(q)
flag = True
for i in range(n):
if self.joint_types[i].startswith("JointModelR"):
if (np.abs(q[i] - self.joint_limits[i][0]) < 1e-3):
continue
q[i] -= 2 * np.pi * np.floor((q[i] - self.joint_limits[i][0]) / (2 * np.pi))
if q[i] > self.joint_limits[i][1] + 1e-3:
flag = False
else:
if q[i] < self.joint_limits[i][0] - 1e-3 or q[i] > self.joint_limits[i][1] + 1e-3:
flag = False
return flag
def IK(self, goal_pose, start_qpos, n_init_qpos = 20, threshold = 1e-3):
index = self.link_name_2_idx[self.move_group]
min_dis = 1e9
result = np.zeros(len(self.user_joint_names))
for i in range(n_init_qpos):
ik_results = self.pinocchio_model.compute_IK_CLIK(index, goal_pose, start_qpos)
flag = self.check_joint_limit(np.copy(ik_results[0]))
if flag:
self.pinocchio_model.compute_forward_kinematics(ik_results[0])
new_pose = self.pinocchio_model.get_link_pose(index)
tmp_dis = self.distance_6D(goal_pose[:3], goal_pose[3:], new_pose[:3], new_pose[3:])
if tmp_dis < min_dis:
min_dis = tmp_dis
result = ik_results[0]
if min_dis < threshold:
return "Success", result
start_qpos = self.pinocchio_model.get_random_configuration()
if min_dis != 1e9:
status = "IK Failed! Distance %lf is greater than threshold %lf." % (min_dis, threshold)
else:
status = "IK Failed! Cannot find valid solution."
return status, result
def TOPP(self, path, step = 0.1, verbose = False):
N_samples = path.shape[0]
dof = path.shape[1]
assert(dof == len(self.joint_vel_limits))
assert(dof == len(self.joint_acc_limits))
ss = np.linspace(0, 1, N_samples)
path = ta.SplineInterpolator(ss, path)
pc_vel = constraint.JointVelocityConstraint(self.joint_vel_limits)
pc_acc = constraint.JointAccelerationConstraint(self.joint_acc_limits)
instance = algo.TOPPRA([pc_vel, pc_acc], path, parametrizer="ParametrizeConstAccel")
jnt_traj = instance.compute_trajectory()
ts_sample = np.linspace(0, jnt_traj.duration, int(jnt_traj.duration / step))
qs_sample = jnt_traj(ts_sample)
qds_sample = jnt_traj(ts_sample, 1)
qdds_sample = jnt_traj(ts_sample, 2)
return ts_sample, qs_sample, qds_sample, qdds_sample, jnt_traj.duration
def update_point_cloud(self, pc, resolution = 1e-3):
self.planning_world.update_point_cloud(pc, resolution)
def update_attached_box(self, size, pose, link_id = -1):
if link_id == -1:
link_id = self.move_group_link_id
self.planning_world.update_attached_box(size, link_id, pose)
def plan(self, goal_pose, current_qpos, time_step = 0.1, rrt_range = 0.1, planning_time = 1, fix_joint_limits = True, use_point_cloud = False, use_attach = False, verbose = False):
self.planning_world.set_use_point_cloud(use_point_cloud)
self.planning_world.set_use_attach(use_attach)
n = current_qpos.shape[0]
if fix_joint_limits:
for i in range(n):
if current_qpos[i] < self.joint_limits[i][0]:
current_qpos[i] = self.joint_limits[i][0] + 1e-3
if current_qpos[i] > self.joint_limits[i][1]:
current_qpos[i] = self.joint_limits[i][1] - 1e-3
idx = self.move_group_joint_indices
ik_status, goal_qpos = self.IK(goal_pose, current_qpos)
if ik_status != "Success":
return {"status": ik_status}
self.robot.set_qpos(current_qpos, True)
status, path = self.planner.plan(current_qpos[idx], goal_qpos[idx], range = rrt_range, verbose = verbose, time = planning_time)
if status == "Exact solution":
if verbose:
ta.setup_logging("INFO")
else:
ta.setup_logging("WARNING")
times, pos, vel, acc, duration = self.TOPP(path, time_step)
return {"status": "Success",
"time": times,
"position": pos,
"velocity": vel,
"acceleration": acc,
"duration": duration}
else:
return {"status": "RRT Failed. %s" % status}
def plan_screw(self, target_pose, qpos, qpos_step = 0.1, time_step = 0.1, use_point_cloud = False, use_attach = False, verbose = False):
self.planning_world.set_use_point_cloud(use_point_cloud)
self.planning_world.set_use_attach(use_attach)
qpos = np.copy(qpos)
self.robot.set_qpos(qpos, True)
def pose7D2mat(pose):
mat = np.eye(4)
mat[0:3, 3] = pose[:3]
mat[0:3, 0:3] = quat2mat(pose[3:])
return mat
def skew(vec):
return np.array([[0, -vec[2], vec[1]],
[vec[2], 0, -vec[0]],
[-vec[1], vec[0], 0]])
def pose2exp_coordinate(pose: np.ndarray) -> Tuple[np.ndarray, float]:
def rot2so3(rotation: np.ndarray):
assert rotation.shape == (3, 3)
if np.isclose(rotation.trace(), 3):
return np.zeros(3), 1
if np.isclose(rotation.trace(), -1):
return np.zeros(3), -1e6
theta = np.arccos((rotation.trace() - 1) / 2)
omega = 1 / 2 / np.sin(theta) * np.array(
[rotation[2, 1] - rotation[1, 2], rotation[0, 2] - rotation[2, 0], rotation[1, 0] - rotation[0, 1]]).T
return omega, theta
omega, theta = rot2so3(pose[:3, :3])
if theta < -1e5:
return omega, theta
ss = skew(omega)
inv_left_jacobian = np.eye(3) / theta - 0.5 * ss + (
1.0 / theta - 0.5 / np.tan(theta / 2)) * ss @ ss
v = inv_left_jacobian @ pose[:3, 3]
return np.concatenate([v, omega]), theta
self.pinocchio_model.compute_forward_kinematics(qpos)
ee_index = self.link_name_2_idx[self.move_group]
current_p = pose7D2mat(self.pinocchio_model.get_link_pose(ee_index))
target_p = pose7D2mat(target_pose)
relative_transform = target_p @ np.linalg.inv(current_p)
omega, theta = pose2exp_coordinate(relative_transform)
if theta < -1e4:
return {"status": "screw plan failed."}
omega = omega.reshape((-1, 1)) * theta
index = self.move_group_joint_indices
path = [np.copy(qpos[index])]
while True:
self.pinocchio_model.compute_full_jacobian(qpos)
J = self.pinocchio_model.get_link_jacobian(ee_index, local = False)
delta_q = np.linalg.pinv(J) @ omega
delta_q *= qpos_step / (np.linalg.norm(delta_q))
delta_twist = J @ delta_q
flag = False
if np.linalg.norm(delta_twist) > np.linalg.norm(omega):
ratio = np.linalg.norm(omega) / np.linalg.norm(delta_twist)
delta_q = delta_q * ratio
delta_twist = delta_twist * ratio
flag = True
qpos += delta_q.reshape(-1)
omega -= delta_twist
def check_joint_limit(q):
n = len(q)
for i in range(n):
if q[i] < self.joint_limits[i][0] - 1e-3 or q[i] > self.joint_limits[i][1] + 1e-3:
return False
return True
within_joint_limit = check_joint_limit(qpos)
self.planning_world.set_qpos_all(qpos[index])
collide = self.planning_world.collide()
if np.linalg.norm(delta_twist) < 1e-4 or collide or within_joint_limit == False:
return {"status": "screw plan failed"}
path.append(np.copy(qpos[index]))
if flag:
if verbose:
ta.setup_logging("INFO")
else:
ta.setup_logging("WARNING")
times, pos, vel, acc, duration = self.TOPP(np.vstack(path), time_step)
return {"status": "Success",
"time": times,
"position": pos,
"velocity": vel,
"acceleration": acc,
"duration": duration}
|
the-stack_0_8499 | from __future__ import division
import argparse
import copy
import os
import os.path as osp
import time
import mmcv
import torch
from mmcv import Config
from mmcv.runner import init_dist
from mmdet import __version__
from mmdet.apis import set_random_seed, train_detector
from mmdet.datasets import build_dataset
from mmdet.models import build_detector
from mmdet.utils import collect_env, get_root_logger
def parse_args():
parser = argparse.ArgumentParser(description='Train a detector')
parser.add_argument('config', help='train config file path')
parser.add_argument('--work_dir', help='the dir to save logs and models')
parser.add_argument(
'--resume_from', help='the checkpoint file to resume from')
parser.add_argument(
'--validate',
action='store_true',
help='whether to evaluate the checkpoint during training')
parser.add_argument(
'--gpus',
type=int,
default=1,
help='number of gpus to use '
'(only applicable to non-distributed training)')
parser.add_argument('--seed', type=int, default=None, help='random seed')
parser.add_argument(
'--deterministic',
action='store_true',
help='whether to set deterministic options for CUDNN backend.')
parser.add_argument(
'--launcher',
choices=['none', 'pytorch', 'slurm', 'mpi'],
default='none',
help='job launcher')
parser.add_argument('--local_rank', type=int, default=0)
parser.add_argument(
'--autoscale-lr',
action='store_true',
help='automatically scale lr with the number of gpus')
args = parser.parse_args()
if 'LOCAL_RANK' not in os.environ:
os.environ['LOCAL_RANK'] = str(args.local_rank)
return args
def main():
args = parse_args()
cfg = Config.fromfile(args.config)
# set cudnn_benchmark
if cfg.get('cudnn_benchmark', False):
torch.backends.cudnn.benchmark = True
# update configs according to CLI args
if args.work_dir is not None:
cfg.work_dir = args.work_dir
if args.resume_from is not None:
cfg.resume_from = args.resume_from
cfg.gpus = args.gpus
if args.autoscale_lr:
# apply the linear scaling rule (https://arxiv.org/abs/1706.02677)
cfg.optimizer['lr'] = cfg.optimizer['lr'] * cfg.gpus / 8
# init distributed env first, since logger depends on the dist info.
if args.launcher == 'none':
distributed = False
else:
distributed = True
init_dist(args.launcher, **cfg.dist_params)
# create work_dir
mmcv.mkdir_or_exist(osp.abspath(cfg.work_dir))
# init the logger before other steps
timestamp = time.strftime('%Y%m%d_%H%M%S', time.localtime())
log_file = osp.join(cfg.work_dir, '{}.log'.format(timestamp))
logger = get_root_logger(log_file=log_file, log_level=cfg.log_level)
# init the meta dict to record some important information such as
# environment info and seed, which will be logged
meta = dict()
# log env info
env_info_dict = collect_env()
env_info = '\n'.join([('{}: {}'.format(k, v))
for k, v in env_info_dict.items()])
dash_line = '-' * 60 + '\n'
logger.info('Environment info:\n' + dash_line + env_info + '\n' +
dash_line)
meta['env_info'] = env_info
# log some basic info
logger.info('Distributed training: {}'.format(distributed))
logger.info('Config:\n{}'.format(cfg.text))
# set random seeds
if args.seed is not None:
logger.info('Set random seed to {}, deterministic: {}'.format(
args.seed, args.deterministic))
set_random_seed(args.seed, deterministic=args.deterministic)
cfg.seed = args.seed
meta['seed'] = args.seed
model = build_detector(
cfg.model, train_cfg=cfg.train_cfg, test_cfg=cfg.test_cfg)
datasets = [build_dataset(cfg.data.train)]
if len(cfg.workflow) == 2:
val_dataset = copy.deepcopy(cfg.data.val)
val_dataset.pipeline = cfg.data.train.pipeline
datasets.append(build_dataset(val_dataset))
if cfg.checkpoint_config is not None:
# save mmdet version, config file content and class names in
# checkpoints as meta data
cfg.checkpoint_config.meta = dict(
mmdet_version=__version__,
config=cfg.text,
CLASSES=datasets[0].CLASSES)
# add an attribute for visualization convenience
model.CLASSES = datasets[0].CLASSES
train_detector(
model,
datasets,
cfg,
distributed=distributed,
validate=args.validate,
timestamp=timestamp,
meta=meta)
if __name__ == '__main__':
main()
|
the-stack_0_8504 | from recipe_scrapers.heb import HEB
from tests import ScraperTest
class TestHEBScraper(ScraperTest):
scraper_class = HEB
def test_host(self):
self.assertEqual("heb.com", self.harvester_class.host())
def test_canonical_url(self):
self.assertEqual(
"https://www.heb.com/recipe/recipe-item/truffled-spaghetti-squash/1398755977632",
self.harvester_class.canonical_url(),
)
def test_title(self):
self.assertEqual("Truffled Spaghetti Squash", self.harvester_class.title())
def test_total_time(self):
self.assertEqual(60, self.harvester_class.total_time())
def test_yields(self):
self.assertEqual("8 servings", self.harvester_class.yields())
def test_ingredients(self):
self.assertEqual(
[
"1 large spaghetti squash",
"1 Tsp Sabatino Truffle salt",
"4 Tbsp unsalted butter",
"1 Tbsp Rustico Truffle Oil",
],
self.harvester_class.ingredients(),
)
def test_instructions(self):
self.assertEqual(
"\n".join(
[
"Preheat oven to 400˚F. Cut spaghetti squash in half from top to bottom (lengthwise).",
"Place the spaghetti squash halves, cut side down onto a sheet pan. Roast for 30-45 minutes or until a knife can pierce the outside of skin easily, like a baked potato.",
"Once Squash is fully cooked and soft remove it from oven and let it cool for 10 minutes before scooping out meat of squash. In a serving bowl scoop or with a fork scrape out squash and add truffle salt, butter and truffle oil.",
"Toss all ingredients together until butter is fully melted. Season to taste if needed and serve warm.",
]
),
self.harvester_class.instructions(),
)
def test_image(self):
self.assertEqual(
"https://images.heb.com/is/image/HEBGrocery/rcp-thumbnail/spicy-spaghetti-squash-boats-recipe.jpg",
self.harvester_class.image(),
)
|
the-stack_0_8505 | import cStringIO
import logging
from datetime import datetime
from clarity_ext_scripts.covid.controls import controls_barcode_generator
from clarity_ext_scripts.covid.services.knm_service import KNMClientFromExtension
from clarity_ext_scripts.covid.create_samples.common import (
BaseRawSampleListFile, ValidatedSampleListFile,
BaseValidateRawSampleListExtension, BUTTON_TEXT_ASSIGN_UNREGISTERED_TO_ANONYMOUS
)
logger = logging.getLogger(__name__)
class RawSampleListColumns(object):
COLUMN_REFERENCE = "Sample Id"
COLUMN_POSITION = "Position"
COLUMN_USER_DEFINED1 = "USERDEFINED1"
COLUMN_USER_DEFINED5 = "USERDEFINED5"
HEADERS = ["Rack Id", "Cavity Id",
COLUMN_POSITION, COLUMN_REFERENCE,
"CONCENTRATION", "CONCENTRATIONUNIT", "VOLUME",
COLUMN_USER_DEFINED1,
"USERDEFINED2", "USERDEFINED3", "USERDEFINED4",
COLUMN_USER_DEFINED5, # Contains a control name or the integration test knm status
"PlateErrors", "SampleErrors", "SAMPLEINSTANCEID", "SAMPLEID"]
# The column from which we can get the fake status in integration tests
COLUMN_FAKE_STATUS = COLUMN_USER_DEFINED5
class RawSampleListFile(RawSampleListColumns, BaseRawSampleListFile):
"""
Describes the CSV file that hangs on the 'Raw sample list' file handle.
"""
@staticmethod
def filter_before_parse(file_like):
filtered = cStringIO.StringIO()
# Ignore everything at or after the line that contains this text:
stop_condition = "Sample Tracking Report Name"
for line in file_like:
if stop_condition in line:
break
filtered.write(line + "\n")
filtered.seek(0)
return filtered
class Extension(BaseValidateRawSampleListExtension):
"""
Validates all samples in a sample creation list.
Before execution of this script, a research engineer has uploaded a raw csv on the format:
barcode;well
to the `Raw sample list` file handle.
This script generates a new sample list. It's equivalent to the original sample
list, but also adds three new fields:
```
barcode: <barcode from csv>
well: <well from csv>
*status: <error | success>
*service_request_id: <the service request ID from KNM>
*comment: <details about the error, if any>
```
This will be the input for creating samples later on. That extension must require that there
are no errors in any of the rows. If there is an error, no sample should be created.
In the case of an error, the research engineer has these options:
* Edit the raw sample list and run validate again.
* Edit this script or request changes at KNM.
* In an extreme case, e.g. given manual confirmation, the research engineer can upload a new
validated file with manually edited information.
"""
def execute(self):
# Validate the 'Raw biobank file' exists and is in concordance with the 'Raw sample list'
# if not, abort script execution
from clarity_ext_scripts.covid.fetch_biobank_barcodes import FetchBiobankBarcodes
validator = FetchBiobankBarcodes(self.context)
validator.validate()
# 1. Get the ordering organizations URI
try:
ordering_org = self.context.current_step.udf_ordering_organization
except AttributeError:
self.usage_error("You must select an ordering organization")
# 2. Create an API client
# Make sure that there is a config at ~/.config/clarity-ext/clarity-ext.config
client = KNMClientFromExtension(self)
# 3. Read the raw sample list.
raw_sample_list = RawSampleListFile.create_from_context(self.context)
validated_sample_list = raw_sample_list.ValidatedSampleListFile()
# 4. Create the validated list
unregistered = list()
for ix, row in validated_sample_list.csv.iterrows():
barcode = row[validated_sample_list.COLUMN_REFERENCE]
well = row[validated_sample_list.COLUMN_POSITION]
# NOTE: The well is in the format "A01" etc
if len(well) != 3:
raise AssertionError(
"Expected the Position in the raw sample list to be on the format A01. "
"Got: {}".format(well))
plate_row = well[0]
plate_col = int(well[1:])
well = "{}:{}".format(plate_row, plate_col)
# TODO It seems that we always need controls here, which
# we need to check if that will always be the case.
is_control = controls_barcode_generator.parse(barcode)
if not is_control:
service_request_id, status, comment, org_uri = self._search_for_id(
validated_sample_list, client, ordering_org, row)
if status == "unregistered":
unregistered.append(barcode)
validated_sample_list.csv.loc[ix,
validated_sample_list.COLUMN_ORG_URI] = org_uri
else:
service_request_id = ""
status = ValidatedSampleListFile.STATUS_OK
comment = ""
validated_sample_list.csv.loc[ix,
validated_sample_list.COLUMN_SERVICE_REQUEST_ID] = service_request_id
validated_sample_list.csv.loc[ix,
validated_sample_list.COLUMN_STATUS] = status
validated_sample_list.csv.loc[ix, validated_sample_list.COLUMN_COMMENT] = comment.replace(
",", "<SC>") # If we have the separator in the comment
validated_sample_list_content = validated_sample_list.csv.to_csv(
index=False, sep=",")
timestamp = datetime.now().strftime("%y%m%dT%H%M%S")
file_name = "validated_sample_list_{}.csv".format(timestamp)
self.context.file_service.upload(
"Validated sample list", file_name, validated_sample_list_content,
self.context.file_service.FILE_PREFIX_NONE)
if len(unregistered) > 0:
self.usage_warning("The following sample are unregistered '{}'. Press '{}' "
"to change the 'Status' to anonymous"
"".format(unregistered, BUTTON_TEXT_ASSIGN_UNREGISTERED_TO_ANONYMOUS))
def integration_tests(self):
yield self.test("24-47136", commit=False)
|
the-stack_0_8506 | #!/usr/bin/env python3
# Copyright (c) 2015-2016 The Deft developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test processing of unrequested blocks.
Setup: two nodes, node0+node1, not connected to each other. Node1 will have
nMinimumChainWork set to 0x10, so it won't process low-work unrequested blocks.
We have one NodeConn connection to node0 called test_node, and one to node1
called min_work_node.
The test:
1. Generate one block on each node, to leave IBD.
2. Mine a new block on each tip, and deliver to each node from node's peer.
The tip should advance for node0, but node1 should skip processing due to
nMinimumChainWork.
Node1 is unused in tests 3-7:
3. Mine a block that forks from the genesis block, and deliver to test_node.
Node0 should not process this block (just accept the header), because it
is unrequested and doesn't have more or equal work to the tip.
4a,b. Send another two blocks that build on the forking block.
Node0 should process the second block but be stuck on the shorter chain,
because it's missing an intermediate block.
4c.Send 288 more blocks on the longer chain (the number of blocks ahead
we currently store).
Node0 should process all but the last block (too far ahead in height).
5. Send a duplicate of the block in #3 to Node0.
Node0 should not process the block because it is unrequested, and stay on
the shorter chain.
6. Send Node0 an inv for the height 3 block produced in #4 above.
Node0 should figure out that Node0 has the missing height 2 block and send a
getdata.
7. Send Node0 the missing block again.
Node0 should process and the tip should advance.
8. Create a fork which is invalid at a height longer than the current chain
(ie to which the node will try to reorg) but which has headers built on top
of the invalid block. Check that we get disconnected if we send more headers
on the chain the node now knows to be invalid.
9. Test Node1 is able to sync when connected to node0 (which should have sufficient
work on its chain).
"""
from test_framework.mininode import *
from test_framework.test_framework import DeftTestFramework
from test_framework.util import *
import time
from test_framework.blocktools import create_block, create_coinbase, create_transaction
class AcceptBlockTest(DeftTestFramework):
def add_options(self, parser):
parser.add_option("--testbinary", dest="testbinary",
default=os.getenv("LITECOIND", "deftd"),
help="deftd binary to test")
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 2
self.extra_args = [[], ["-minimumchainwork=0x10"]]
def setup_network(self):
# Node0 will be used to test behavior of processing unrequested blocks
# from peers which are not whitelisted, while Node1 will be used for
# the whitelisted case.
# Node2 will be used for non-whitelisted peers to test the interaction
# with nMinimumChainWork.
self.setup_nodes()
def run_test(self):
# Setup the p2p connections and start up the network thread.
test_node = NodeConnCB() # connects to node0
min_work_node = NodeConnCB() # connects to node1
connections = []
connections.append(NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], test_node))
connections.append(NodeConn('127.0.0.1', p2p_port(1), self.nodes[1], min_work_node))
test_node.add_connection(connections[0])
min_work_node.add_connection(connections[1])
NetworkThread().start() # Start up network handling in another thread
# Test logic begins here
test_node.wait_for_verack()
min_work_node.wait_for_verack()
# 1. Have nodes mine a block (leave IBD)
[ n.generate(1) for n in self.nodes ]
tips = [ int("0x" + n.getbestblockhash(), 0) for n in self.nodes ]
# 2. Send one block that builds on each tip.
# This should be accepted by node0
blocks_h2 = [] # the height 2 blocks on each node's chain
block_time = int(time.time()) + 1
for i in range(2):
blocks_h2.append(create_block(tips[i], create_coinbase(2), block_time))
blocks_h2[i].solve()
block_time += 1
test_node.send_message(msg_block(blocks_h2[0]))
min_work_node.send_message(msg_block(blocks_h2[1]))
for x in [test_node, min_work_node]:
x.sync_with_ping()
assert_equal(self.nodes[0].getblockcount(), 2)
assert_equal(self.nodes[1].getblockcount(), 1)
self.log.info("First height 2 block accepted by node0; correctly rejected by node1")
# 3. Send another block that builds on genesis.
block_h1f = create_block(int("0x" + self.nodes[0].getblockhash(0), 0), create_coinbase(1), block_time)
block_time += 1
block_h1f.solve()
test_node.send_message(msg_block(block_h1f))
test_node.sync_with_ping()
tip_entry_found = False
for x in self.nodes[0].getchaintips():
if x['hash'] == block_h1f.hash:
assert_equal(x['status'], "headers-only")
tip_entry_found = True
assert(tip_entry_found)
assert_raises_rpc_error(-1, "Block not found on disk", self.nodes[0].getblock, block_h1f.hash)
# 4. Send another two block that build on the fork.
block_h2f = create_block(block_h1f.sha256, create_coinbase(2), block_time)
block_time += 1
block_h2f.solve()
test_node.send_message(msg_block(block_h2f))
test_node.sync_with_ping()
# Since the earlier block was not processed by node, the new block
# can't be fully validated.
tip_entry_found = False
for x in self.nodes[0].getchaintips():
if x['hash'] == block_h2f.hash:
assert_equal(x['status'], "headers-only")
tip_entry_found = True
assert(tip_entry_found)
# But this block should be accepted by node since it has equal work.
self.nodes[0].getblock(block_h2f.hash)
self.log.info("Second height 2 block accepted, but not reorg'ed to")
# 4b. Now send another block that builds on the forking chain.
block_h3 = create_block(block_h2f.sha256, create_coinbase(3), block_h2f.nTime+1)
block_h3.solve()
test_node.send_message(msg_block(block_h3))
test_node.sync_with_ping()
# Since the earlier block was not processed by node, the new block
# can't be fully validated.
tip_entry_found = False
for x in self.nodes[0].getchaintips():
if x['hash'] == block_h3.hash:
assert_equal(x['status'], "headers-only")
tip_entry_found = True
assert(tip_entry_found)
self.nodes[0].getblock(block_h3.hash)
# But this block should be accepted by node since it has more work.
self.nodes[0].getblock(block_h3.hash)
self.log.info("Unrequested more-work block accepted")
# 4c. Now mine 288 more blocks and deliver; all should be processed but
# the last (height-too-high) on node (as long as its not missing any headers)
tip = block_h3
all_blocks = []
for i in range(288):
next_block = create_block(tip.sha256, create_coinbase(i + 4), tip.nTime+1)
next_block.solve()
all_blocks.append(next_block)
tip = next_block
# Now send the block at height 5 and check that it wasn't accepted (missing header)
test_node.send_message(msg_block(all_blocks[1]))
test_node.sync_with_ping()
assert_raises_rpc_error(-5, "Block not found", self.nodes[0].getblock, all_blocks[1].hash)
assert_raises_rpc_error(-5, "Block not found", self.nodes[0].getblockheader, all_blocks[1].hash)
# The block at height 5 should be accepted if we provide the missing header, though
headers_message = msg_headers()
headers_message.headers.append(CBlockHeader(all_blocks[0]))
test_node.send_message(headers_message)
test_node.send_message(msg_block(all_blocks[1]))
test_node.sync_with_ping()
self.nodes[0].getblock(all_blocks[1].hash)
# Now send the blocks in all_blocks
for i in range(288):
test_node.send_message(msg_block(all_blocks[i]))
test_node.sync_with_ping()
# Blocks 1-287 should be accepted, block 288 should be ignored because it's too far ahead
for x in all_blocks[:-1]:
self.nodes[0].getblock(x.hash)
assert_raises_rpc_error(-1, "Block not found on disk", self.nodes[0].getblock, all_blocks[-1].hash)
# 5. Test handling of unrequested block on the node that didn't process
# Should still not be processed (even though it has a child that has more
# work).
# The node should have requested the blocks at some point, so
# disconnect/reconnect first
connections[0].disconnect_node()
test_node.wait_for_disconnect()
test_node = NodeConnCB() # connects to node (not whitelisted)
connections[0] = NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], test_node)
test_node.add_connection(connections[0])
test_node.wait_for_verack()
test_node.send_message(msg_block(block_h1f))
test_node.sync_with_ping()
assert_equal(self.nodes[0].getblockcount(), 2)
self.log.info("Unrequested block that would complete more-work chain was ignored")
# 6. Try to get node to request the missing block.
# Poke the node with an inv for block at height 3 and see if that
# triggers a getdata on block 2 (it should if block 2 is missing).
with mininode_lock:
# Clear state so we can check the getdata request
test_node.last_message.pop("getdata", None)
test_node.send_message(msg_inv([CInv(2, block_h3.sha256)]))
test_node.sync_with_ping()
with mininode_lock:
getdata = test_node.last_message["getdata"]
# Check that the getdata includes the right block
assert_equal(getdata.inv[0].hash, block_h1f.sha256)
self.log.info("Inv at tip triggered getdata for unprocessed block")
# 7. Send the missing block for the third time (now it is requested)
test_node.send_message(msg_block(block_h1f))
test_node.sync_with_ping()
assert_equal(self.nodes[0].getblockcount(), 290)
self.nodes[0].getblock(all_blocks[286].hash)
assert_equal(self.nodes[0].getbestblockhash(), all_blocks[286].hash)
assert_raises_rpc_error(-1, "Block not found on disk", self.nodes[0].getblock, all_blocks[287].hash)
self.log.info("Successfully reorged to longer chain from non-whitelisted peer")
# 8. Create a chain which is invalid at a height longer than the
# current chain, but which has more blocks on top of that
block_289f = create_block(all_blocks[284].sha256, create_coinbase(289), all_blocks[284].nTime+1)
block_289f.solve()
block_290f = create_block(block_289f.sha256, create_coinbase(290), block_289f.nTime+1)
block_290f.solve()
block_291 = create_block(block_290f.sha256, create_coinbase(291), block_290f.nTime+1)
# block_291 spends a coinbase below maturity!
block_291.vtx.append(create_transaction(block_290f.vtx[0], 0, b"42", 1))
block_291.hashMerkleRoot = block_291.calc_merkle_root()
block_291.solve()
block_292 = create_block(block_291.sha256, create_coinbase(292), block_291.nTime+1)
block_292.solve()
# Now send all the headers on the chain and enough blocks to trigger reorg
headers_message = msg_headers()
headers_message.headers.append(CBlockHeader(block_289f))
headers_message.headers.append(CBlockHeader(block_290f))
headers_message.headers.append(CBlockHeader(block_291))
headers_message.headers.append(CBlockHeader(block_292))
test_node.send_message(headers_message)
test_node.sync_with_ping()
tip_entry_found = False
for x in self.nodes[0].getchaintips():
if x['hash'] == block_292.hash:
assert_equal(x['status'], "headers-only")
tip_entry_found = True
assert(tip_entry_found)
assert_raises_rpc_error(-1, "Block not found on disk", self.nodes[0].getblock, block_292.hash)
test_node.send_message(msg_block(block_289f))
test_node.send_message(msg_block(block_290f))
test_node.sync_with_ping()
self.nodes[0].getblock(block_289f.hash)
self.nodes[0].getblock(block_290f.hash)
test_node.send_message(msg_block(block_291))
# At this point we've sent an obviously-bogus block, wait for full processing
# without assuming whether we will be disconnected or not
try:
# Only wait a short while so the test doesn't take forever if we do get
# disconnected
test_node.sync_with_ping(timeout=1)
except AssertionError:
test_node.wait_for_disconnect()
test_node = NodeConnCB() # connects to node (not whitelisted)
connections[0] = NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], test_node)
test_node.add_connection(connections[0])
NetworkThread().start() # Start up network handling in another thread
test_node.wait_for_verack()
# We should have failed reorg and switched back to 290 (but have block 291)
assert_equal(self.nodes[0].getblockcount(), 290)
assert_equal(self.nodes[0].getbestblockhash(), all_blocks[286].hash)
assert_equal(self.nodes[0].getblock(block_291.hash)["confirmations"], -1)
# Now send a new header on the invalid chain, indicating we're forked off, and expect to get disconnected
block_293 = create_block(block_292.sha256, create_coinbase(293), block_292.nTime+1)
block_293.solve()
headers_message = msg_headers()
headers_message.headers.append(CBlockHeader(block_293))
test_node.send_message(headers_message)
test_node.wait_for_disconnect()
# 9. Connect node1 to node0 and ensure it is able to sync
connect_nodes(self.nodes[0], 1)
sync_blocks([self.nodes[0], self.nodes[1]])
self.log.info("Successfully synced nodes 1 and 0")
[ c.disconnect_node() for c in connections ]
if __name__ == '__main__':
AcceptBlockTest().main()
|
the-stack_0_8512 | import ntpath
from lead2gold.tools.tool import Tool
from lead2gold.util import pwm2consensus
from lead2gold.util import sequence2pwm
from lead2gold.motif import Motif
class EMD(Tool):
"""Class implementing a EMD search tool motif convertor.
"""
toolName = "EMD"
def __init__(self):
"""Initialize all class attributes with their default values.
"""
super(self.__class__, self).__init__(self.toolName)
def parse(self, motif_file, type=None):
"""Loads the searcher parameters specified in the configuration file.
Args:
motif_file: file containing one or more EMD motifs.
Returns:
[Motif()]
"""
basename=ntpath.basename(motif_file.name)
def get_section(line, section, order):
if len(line) < 2:
return "stop", 1
if "Motif " in line[0:8]:
return "name", 2
return section, order
def get_template():
return {
"start": [],
"stop": [],
"name": []
}
motifs = []
section = "start"
order = 0
t_motif = get_template()
for line in motif_file:
clean_line = line.strip()
section, order_new = get_section(line, section, order)
if order_new < order:
motifs.append(self._parse_motif(t_motif))
t_motif = get_template()
order = order_new
t_motif[section].append(clean_line)
motifs.append(self._parse_motif(t_motif))
return list(filter(None, motifs))
def _parse_motif(self, t_motif):
name = t_motif["name"].pop(0)
sequences = []
for row in t_motif["name"]:
row_values = row.split()
if len(row_values) == 4:
sequences.append(row_values[0])
counters, _ = sequence2pwm(sequences)
motif = Motif(identifier=name, counters=counters)
consensus = pwm2consensus(motif.get_PPM())
motif.set_number_of_sites(len(sequences))
motif.set_alternate_name(consensus)
return motif
|
the-stack_0_8513 | # copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# 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 writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from paddle.optimizer import lr
from paddle.optimizer.lr import LRScheduler
from ppcls.utils import logger
class Linear(object):
"""
Linear learning rate decay
Args:
lr (float): The initial learning rate. It is a python float number.
epochs(int): The decay step size. It determines the decay cycle.
end_lr(float, optional): The minimum final learning rate. Default: 0.0001.
power(float, optional): Power of polynomial. Default: 1.0.
warmup_epoch(int): The epoch numbers for LinearWarmup. Default: 0.
warmup_start_lr(float): Initial learning rate of warm up. Default: 0.0.
last_epoch (int, optional): The index of last epoch. Can be set to restart training. Default: -1, means initial learning rate.
"""
def __init__(self,
learning_rate,
epochs,
step_each_epoch,
end_lr=0.0,
power=1.0,
warmup_epoch=0,
warmup_start_lr=0.0,
last_epoch=-1,
**kwargs):
super().__init__()
if warmup_epoch >= epochs:
msg = f"When using warm up, the value of \"Global.epochs\" must be greater than value of \"Optimizer.lr.warmup_epoch\". The value of \"Optimizer.lr.warmup_epoch\" has been set to {epochs}."
logger.warning(msg)
warmup_epoch = epochs
self.learning_rate = learning_rate
self.steps = (epochs - warmup_epoch) * step_each_epoch
self.end_lr = end_lr
self.power = power
self.last_epoch = last_epoch
self.warmup_steps = round(warmup_epoch * step_each_epoch)
self.warmup_start_lr = warmup_start_lr
def __call__(self):
learning_rate = lr.PolynomialDecay(
learning_rate=self.learning_rate,
decay_steps=self.steps,
end_lr=self.end_lr,
power=self.power,
last_epoch=self.
last_epoch) if self.steps > 0 else self.learning_rate
if self.warmup_steps > 0:
learning_rate = lr.LinearWarmup(
learning_rate=learning_rate,
warmup_steps=self.warmup_steps,
start_lr=self.warmup_start_lr,
end_lr=self.learning_rate,
last_epoch=self.last_epoch)
return learning_rate
class Constant(LRScheduler):
"""
Constant learning rate
Args:
lr (float): The initial learning rate. It is a python float number.
last_epoch (int, optional): The index of last epoch. Can be set to restart training. Default: -1, means initial learning rate.
"""
def __init__(self, learning_rate, last_epoch=-1, **kwargs):
self.learning_rate = learning_rate
self.last_epoch = last_epoch
super().__init__()
def get_lr(self):
return self.learning_rate
class Cosine(object):
"""
Cosine learning rate decay
lr = 0.05 * (math.cos(epoch * (math.pi / epochs)) + 1)
Args:
lr(float): initial learning rate
step_each_epoch(int): steps each epoch
epochs(int): total training epochs
eta_min(float): Minimum learning rate. Default: 0.0.
warmup_epoch(int): The epoch numbers for LinearWarmup. Default: 0.
warmup_start_lr(float): Initial learning rate of warm up. Default: 0.0.
last_epoch (int, optional): The index of last epoch. Can be set to restart training. Default: -1, means initial learning rate.
"""
def __init__(self,
learning_rate,
step_each_epoch,
epochs,
eta_min=0.0,
warmup_epoch=0,
warmup_start_lr=0.0,
last_epoch=-1,
**kwargs):
super().__init__()
if warmup_epoch >= epochs:
msg = f"When using warm up, the value of \"Global.epochs\" must be greater than value of \"Optimizer.lr.warmup_epoch\". The value of \"Optimizer.lr.warmup_epoch\" has been set to {epochs}."
logger.warning(msg)
warmup_epoch = epochs
self.learning_rate = learning_rate
self.T_max = (epochs - warmup_epoch) * step_each_epoch
self.eta_min = eta_min
self.last_epoch = last_epoch
self.warmup_steps = round(warmup_epoch * step_each_epoch)
self.warmup_start_lr = warmup_start_lr
def __call__(self):
learning_rate = lr.CosineAnnealingDecay(
learning_rate=self.learning_rate,
T_max=self.T_max,
eta_min=self.eta_min,
last_epoch=self.
last_epoch) if self.T_max > 0 else self.learning_rate
if self.warmup_steps > 0:
learning_rate = lr.LinearWarmup(
learning_rate=learning_rate,
warmup_steps=self.warmup_steps,
start_lr=self.warmup_start_lr,
end_lr=self.learning_rate,
last_epoch=self.last_epoch)
return learning_rate
class Step(object):
"""
Piecewise learning rate decay
Args:
step_each_epoch(int): steps each epoch
learning_rate (float): The initial learning rate. It is a python float number.
step_size (int): the interval to update.
gamma (float, optional): The Ratio that the learning rate will be reduced. ``new_lr = origin_lr * gamma`` .
It should be less than 1.0. Default: 0.1.
warmup_epoch(int): The epoch numbers for LinearWarmup. Default: 0.
warmup_start_lr(float): Initial learning rate of warm up. Default: 0.0.
last_epoch (int, optional): The index of last epoch. Can be set to restart training. Default: -1, means initial learning rate.
"""
def __init__(self,
learning_rate,
step_size,
step_each_epoch,
epochs,
gamma,
warmup_epoch=0,
warmup_start_lr=0.0,
last_epoch=-1,
**kwargs):
super().__init__()
if warmup_epoch >= epochs:
msg = f"When using warm up, the value of \"Global.epochs\" must be greater than value of \"Optimizer.lr.warmup_epoch\". The value of \"Optimizer.lr.warmup_epoch\" has been set to {epochs}."
logger.warning(msg)
warmup_epoch = epochs
self.step_size = step_each_epoch * step_size
self.learning_rate = learning_rate
self.gamma = gamma
self.last_epoch = last_epoch
self.warmup_steps = round(warmup_epoch * step_each_epoch)
self.warmup_start_lr = warmup_start_lr
def __call__(self):
learning_rate = lr.StepDecay(
learning_rate=self.learning_rate,
step_size=self.step_size,
gamma=self.gamma,
last_epoch=self.last_epoch)
if self.warmup_steps > 0:
learning_rate = lr.LinearWarmup(
learning_rate=learning_rate,
warmup_steps=self.warmup_steps,
start_lr=self.warmup_start_lr,
end_lr=self.learning_rate,
last_epoch=self.last_epoch)
return learning_rate
class Piecewise(object):
"""
Piecewise learning rate decay
Args:
boundaries(list): A list of steps numbers. The type of element in the list is python int.
values(list): A list of learning rate values that will be picked during different epoch boundaries.
The type of element in the list is python float.
warmup_epoch(int): The epoch numbers for LinearWarmup. Default: 0.
warmup_start_lr(float): Initial learning rate of warm up. Default: 0.0.
by_epoch(bool): Whether lr decay by epoch. Default: False.
last_epoch (int, optional): The index of last epoch. Can be set to restart training. Default: -1, means initial learning rate.
"""
def __init__(self,
step_each_epoch,
decay_epochs,
values,
epochs,
warmup_epoch=0,
warmup_start_lr=0.0,
by_epoch=False,
last_epoch=-1,
**kwargs):
super().__init__()
if warmup_epoch >= epochs:
msg = f"When using warm up, the value of \"Global.epochs\" must be greater than value of \"Optimizer.lr.warmup_epoch\". The value of \"Optimizer.lr.warmup_epoch\" has been set to {epochs}."
logger.warning(msg)
warmup_epoch = epochs
self.boundaries_steps = [step_each_epoch * e for e in decay_epochs]
self.boundaries_epoch = decay_epochs
self.values = values
self.last_epoch = last_epoch
self.warmup_steps = round(warmup_epoch * step_each_epoch)
self.warmup_epoch = warmup_epoch
self.warmup_start_lr = warmup_start_lr
self.by_epoch = by_epoch
def __call__(self):
if self.by_epoch:
learning_rate = lr.PiecewiseDecay(
boundaries=self.boundaries_epoch,
values=self.values,
last_epoch=self.last_epoch)
if self.warmup_epoch > 0:
learning_rate = lr.LinearWarmup(
learning_rate=learning_rate,
warmup_steps=self.warmup_epoch,
start_lr=self.warmup_start_lr,
end_lr=self.values[0],
last_epoch=self.last_epoch)
else:
learning_rate = lr.PiecewiseDecay(
boundaries=self.boundaries_steps,
values=self.values,
last_epoch=self.last_epoch)
if self.warmup_steps > 0:
learning_rate = lr.LinearWarmup(
learning_rate=learning_rate,
warmup_steps=self.warmup_steps,
start_lr=self.warmup_start_lr,
end_lr=self.values[0],
last_epoch=self.last_epoch)
setattr(learning_rate, "by_epoch", self.by_epoch)
return learning_rate
class MultiStepDecay(LRScheduler):
"""
Update the learning rate by ``gamma`` once ``epoch`` reaches one of the milestones.
The algorithm can be described as the code below.
.. code-block:: text
learning_rate = 0.5
milestones = [30, 50]
gamma = 0.1
if epoch < 30:
learning_rate = 0.5
elif epoch < 50:
learning_rate = 0.05
else:
learning_rate = 0.005
Args:
learning_rate (float): The initial learning rate. It is a python float number.
milestones (tuple|list): List or tuple of each boundaries. Must be increasing.
gamma (float, optional): The Ratio that the learning rate will be reduced. ``new_lr = origin_lr * gamma`` .
It should be less than 1.0. Default: 0.1.
last_epoch (int, optional): The index of last epoch. Can be set to restart training. Default: -1, means initial learning rate.
verbose (bool, optional): If ``True``, prints a message to stdout for each update. Default: ``False`` .
Returns:
``MultiStepDecay`` instance to schedule learning rate.
Examples:
.. code-block:: python
import paddle
import numpy as np
# train on default dynamic graph mode
linear = paddle.nn.Linear(10, 10)
scheduler = paddle.optimizer.lr.MultiStepDecay(learning_rate=0.5, milestones=[2, 4, 6], gamma=0.8, verbose=True)
sgd = paddle.optimizer.SGD(learning_rate=scheduler, parameters=linear.parameters())
for epoch in range(20):
for batch_id in range(5):
x = paddle.uniform([10, 10])
out = linear(x)
loss = paddle.mean(out)
loss.backward()
sgd.step()
sgd.clear_gradients()
scheduler.step() # If you update learning rate each step
# scheduler.step() # If you update learning rate each epoch
# train on static graph mode
paddle.enable_static()
main_prog = paddle.static.Program()
start_prog = paddle.static.Program()
with paddle.static.program_guard(main_prog, start_prog):
x = paddle.static.data(name='x', shape=[None, 4, 5])
y = paddle.static.data(name='y', shape=[None, 4, 5])
z = paddle.static.nn.fc(x, 100)
loss = paddle.mean(z)
scheduler = paddle.optimizer.lr.MultiStepDecay(learning_rate=0.5, milestones=[2, 4, 6], gamma=0.8, verbose=True)
sgd = paddle.optimizer.SGD(learning_rate=scheduler)
sgd.minimize(loss)
exe = paddle.static.Executor()
exe.run(start_prog)
for epoch in range(20):
for batch_id in range(5):
out = exe.run(
main_prog,
feed={
'x': np.random.randn(3, 4, 5).astype('float32'),
'y': np.random.randn(3, 4, 5).astype('float32')
},
fetch_list=loss.name)
scheduler.step() # If you update learning rate each step
# scheduler.step() # If you update learning rate each epoch
"""
def __init__(self,
learning_rate,
milestones,
epochs,
step_each_epoch,
gamma=0.1,
last_epoch=-1,
verbose=False):
if not isinstance(milestones, (tuple, list)):
raise TypeError(
"The type of 'milestones' in 'MultiStepDecay' must be 'tuple, list', but received %s."
% type(milestones))
if not all([
milestones[i] < milestones[i + 1]
for i in range(len(milestones) - 1)
]):
raise ValueError('The elements of milestones must be incremented')
if gamma >= 1.0:
raise ValueError('gamma should be < 1.0.')
self.milestones = [x * step_each_epoch for x in milestones]
self.gamma = gamma
super().__init__(learning_rate, last_epoch, verbose)
def get_lr(self):
for i in range(len(self.milestones)):
if self.last_epoch < self.milestones[i]:
return self.base_lr * (self.gamma**i)
return self.base_lr * (self.gamma**len(self.milestones))
|
the-stack_0_8516 | #!/usr/bin/env python
import rospy
import actionlib
from actionlib_msgs.msg import *
from geometry_msgs.msg import Pose, Point, Quaternion, Twist
from move_base_msgs.msg import MoveBaseAction, MoveBaseGoal
from tf.transformations import quaternion_from_euler
from visualization_msgs.msg import Marker
from math import radians, pi
class MoveBaseSquare():
def __init__(self):
rospy.init_node('box_client', anonymous=False)
rospy.on_shutdown(self.shutdown)
# Create a list to hold the waypoint poses
waypoints = list()
# Append each of the four waypoints to the list. Each waypoint
# is a pose consisting of a position and orientation in the map frame.
waypoints.append(Pose(Point(10.0, 0.62, 0.0), Quaternion(0,0,0,1)))
# Initialize the visualization markers for RViz
self.init_markers()
# Set a visualization marker at each waypoint
for waypoint in waypoints:
p = Point()
p = waypoint.position
self.markers.points.append(p)
# Subscribe to the move_base action server
self.move_base = actionlib.SimpleActionClient("move_base", MoveBaseAction)
rospy.loginfo("Waiting for move_base action server...")
# Wait 60 seconds for the action server to become available
self.move_base.wait_for_server(rospy.Duration(60))
rospy.loginfo("Connected to move base server")
rospy.loginfo("Starting navigation test")
# Initialize a counter to track waypoints
i = 0
# Cycle through the four waypoints
while i < len(waypoints) and not rospy.is_shutdown():
# Update the marker display
self.marker_pub.publish(self.markers)
# Intialize the waypoint goal
goal = MoveBaseGoal()
# Use the map frame to define goal poses
goal.target_pose.header.frame_id = 'map'
# Set the time stamp to "now"
goal.target_pose.header.stamp = rospy.Time.now()
# Set the goal pose to the i-th waypoint
goal.target_pose.pose = waypoints[i]
# Start the robot moving toward the goal
self.move(goal)
i += 1
def move(self, goal):
# Send the goal pose to the MoveBaseAction server
self.move_base.send_goal(goal)
# Allow 1 minute to get there
finished_within_time = self.move_base.wait_for_result(rospy.Duration(60))
# If we don't get there in time, abort the goal
if not finished_within_time:
self.move_base.cancel_goal()
rospy.loginfo("Timed out achieving goal")
else:
# We made it!
state = self.move_base.get_state()
if state == GoalStatus.SUCCEEDED:
rospy.loginfo("Goal succeeded!")
def init_markers(self):
# Set up our waypoint markers
marker_scale = 0.2
marker_lifetime = 0 # 0 is forever
marker_ns = 'waypoints'
marker_id = 0
marker_color = {'r': 1.0, 'g': 0.7, 'b': 1.0, 'a': 1.0}
# Define a marker publisher.
self.marker_pub = rospy.Publisher('waypoint_markers', Marker, queue_size=1)
# Initialize the marker points list.
self.markers = Marker()
self.markers.ns = marker_ns
self.markers.id = marker_id
self.markers.type = Marker.SPHERE_LIST
self.markers.action = Marker.ADD
self.markers.lifetime = rospy.Duration(marker_lifetime)
self.markers.scale.x = marker_scale
self.markers.scale.y = marker_scale
self.markers.color.r = marker_color['r']
self.markers.color.g = marker_color['g']
self.markers.color.b = marker_color['b']
self.markers.color.a = marker_color['a']
self.markers.header.frame_id = 'map'
self.markers.header.stamp = rospy.Time.now()
self.markers.points = list()
def shutdown(self):
rospy.loginfo("Stopping the robot...")
# Cancel any active goals
self.move_base.cancel_goal()
rospy.sleep(2)
if __name__ == '__main__':
try:
MoveBaseSquare()
except rospy.ROSInterruptException:
rospy.loginfo("Navigation test finished.")
|
the-stack_0_8517 | #!/usr/bin/env python
import sys
import logging
import argparse
import json
from pds_pipelines.db import db_connect
from pds_pipelines.models.pds_models import Files
from pds_pipelines.RedisQueue import RedisQueue
from pds_pipelines.config import pds_log, pds_info, pds_db
class Args:
def __init__(self):
pass
def parse_args(self):
parser = argparse.ArgumentParser(description='UPC Queueing')
parser.add_argument('--archive', '-a', dest="archive", required=True,
help="Enter archive - archive to ingest")
parser.add_argument('--volume', '-v', dest="volume",
help="Enter volume to Ingest")
parser.add_argument('--search', '-s', dest="search",
help="Enter string to search for")
args = parser.parse_args()
self.archive = args.archive
self.volume = args.volume
self.search = args.search
def main():
# pdb.set_trace()
args = Args()
args.parse_args()
logger = logging.getLogger('UPC_Queueing.' + args.archive)
logger.setLevel(logging.INFO)
# logFileHandle = logging.FileHandler('/usgs/cdev/PDS/logs/Process.log')
logFileHandle = logging.FileHandler(pds_log + 'Process.log')
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s, %(message)s')
logFileHandle.setFormatter(formatter)
logger.addHandler(logFileHandle)
logger.info('Starting Process')
PDSinfoDICT = json.load(open(pds_info, 'r'))
try:
archiveID = PDSinfoDICT[args.archive]['archiveid']
except KeyError:
print("\nArchive '{}' not found in {}\n".format(args.archive, pds_info))
print("The following archives are available:")
for k in PDSinfoDICT.keys():
print("\t{}".format(k))
exit()
RQ = RedisQueue('UPC_ReadyQueue')
try:
session, _ = db_connect(pds_db)
print('Database Connection Success')
except Exception as e:
print(e)
print('Database Connection Error')
if args.volume:
volstr = '%' + args.volume + '%'
qOBJ = session.query(Files).filter(Files.archiveid == archiveID,
Files.filename.like(volstr),
Files.upc_required == 't')
else:
qOBJ = session.query(Files).filter(Files.archiveid == archiveID,
Files.upc_required == 't')
if qOBJ:
addcount = 0
for element in qOBJ:
fname = PDSinfoDICT[args.archive]['path'] + element.filename
fid = element.fileid
RQ.QueueAdd((fname, fid, args.archive))
addcount = addcount + 1
logger.info('Files Added to UPC Queue: %s', addcount)
print("Done")
if __name__ == "__main__":
sys.exit(main())
|
the-stack_0_8518 | # -*- coding: utf-8 -*-
"""
requests.utils
~~~~~~~~~~~~~~
This module provides utlity functions that are used within Requests
that are also useful for external consumption.
"""
import cgi
import codecs
import http.cookiejar
import os
import random
import re
import zlib
from urllib2 import parse_http_list as _parse_list_header
def guess_filename(obj):
"""Tries to guess the filename of the given object."""
name = getattr(obj, 'name', None)
if name and name[0] != '<' and name[-1] != '>':
return name
# From mitsuhiko/werkzeug (used with permission).
def parse_list_header(value):
"""Parse lists as described by RFC 2068 Section 2.
In particular, parse comma-separated lists where the elements of
the list may include quoted-strings. A quoted-string could
contain a comma. A non-quoted string could have quotes in the
middle. Quotes are removed automatically after parsing.
It basically works like :func:`parse_set_header` just that items
may appear multiple times and case sensitivity is preserved.
The return value is a standard :class:`list`:
>>> parse_list_header('token, "quoted value"')
['token', 'quoted value']
To create a header from the :class:`list` again, use the
:func:`dump_header` function.
:param value: a string with a list header.
:return: :class:`list`
"""
result = []
for item in _parse_list_header(value):
if item[:1] == item[-1:] == '"':
item = unquote_header_value(item[1:-1])
result.append(item)
return result
# From mitsuhiko/werkzeug (used with permission).
def parse_dict_header(value):
"""Parse lists of key, value pairs as described by RFC 2068 Section 2 and
convert them into a python dict:
>>> d = parse_dict_header('foo="is a fish", bar="as well"')
>>> type(d) is dict
True
>>> sorted(d.items())
[('bar', 'as well'), ('foo', 'is a fish')]
If there is no value for a key it will be `None`:
>>> parse_dict_header('key_without_value')
{'key_without_value': None}
To create a header from the :class:`dict` again, use the
:func:`dump_header` function.
:param value: a string with a dict header.
:return: :class:`dict`
"""
result = {}
for item in _parse_list_header(value):
if '=' not in item:
result[item] = None
continue
name, value = item.split('=', 1)
if value[:1] == value[-1:] == '"':
value = unquote_header_value(value[1:-1])
result[name] = value
return result
# From mitsuhiko/werkzeug (used with permission).
def unquote_header_value(value, is_filename=False):
r"""Unquotes a header value. (Reversal of :func:`quote_header_value`).
This does not use the real unquoting but what browsers are actually
using for quoting.
:param value: the header value to unquote.
"""
if value and value[0] == value[-1] == '"':
# this is not the real unquoting, but fixing this so that the
# RFC is met will result in bugs with internet explorer and
# probably some other browsers as well. IE for example is
# uploading files with "C:\foo\bar.txt" as filename
value = value[1:-1]
# if this is a filename and the starting characters look like
# a UNC path, then just return the value without quotes. Using the
# replace sequence below on a UNC path has the effect of turning
# the leading double slash into a single slash and then
# _fix_ie_filename() doesn't work correctly. See #458.
if not is_filename or value[:2] != '\\\\':
return value.replace('\\\\', '\\').replace('\\"', '"')
return value
def header_expand(headers):
"""Returns an HTTP Header value string from a dictionary.
Example expansion::
{'text/x-dvi': {'q': '.8', 'mxb': '100000', 'mxt': '5.0'}, 'text/x-c': {}}
# Accept: text/x-dvi; q=.8; mxb=100000; mxt=5.0, text/x-c
(('text/x-dvi', {'q': '.8', 'mxb': '100000', 'mxt': '5.0'}), ('text/x-c', {}))
# Accept: text/x-dvi; q=.8; mxb=100000; mxt=5.0, text/x-c
"""
collector = []
if isinstance(headers, dict):
headers = list(headers.items())
elif isinstance(headers, str):
return headers
for i, (value, params) in enumerate(headers):
_params = []
for (p_k, p_v) in list(params.items()):
_params.append('%s=%s' % (p_k, p_v))
collector.append(value)
collector.append('; ')
if len(params):
collector.append('; '.join(_params))
if not len(headers) == i+1:
collector.append(', ')
# Remove trailing separators.
if collector[-1] in (', ', '; '):
del collector[-1]
return ''.join(collector)
def randombytes(n):
"""Return n random bytes."""
# Use /dev/urandom if it is available. Fall back to random module
# if not. It might be worthwhile to extend this function to use
# other platform-specific mechanisms for getting random bytes.
if os.path.exists("/dev/urandom"):
f = open("/dev/urandom")
s = f.read(n)
f.close()
return s
else:
L = [chr(random.randrange(0, 256)) for i in range(n)]
return "".join(L)
def dict_from_cookiejar(cj):
"""Returns a key/value dictionary from a CookieJar.
:param cj: CookieJar object to extract cookies from.
"""
cookie_dict = {}
for _, cookies in list(cj._cookies.items()):
for _, cookies in list(cookies.items()):
for cookie in list(cookies.values()):
# print cookie
cookie_dict[cookie.name] = cookie.value
return cookie_dict
def cookiejar_from_dict(cookie_dict):
"""Returns a CookieJar from a key/value dictionary.
:param cookie_dict: Dict of key/values to insert into CookieJar.
"""
# return cookiejar if one was passed in
if isinstance(cookie_dict, http.cookiejar.CookieJar):
return cookie_dict
# create cookiejar
cj = http.cookiejar.CookieJar()
cj = add_dict_to_cookiejar(cj, cookie_dict)
return cj
def add_dict_to_cookiejar(cj, cookie_dict):
"""Returns a CookieJar from a key/value dictionary.
:param cj: CookieJar to insert cookies into.
:param cookie_dict: Dict of key/values to insert into CookieJar.
"""
for k, v in list(cookie_dict.items()):
cookie = http.cookiejar.Cookie(
version=0,
name=k,
value=v,
port=None,
port_specified=False,
domain='',
domain_specified=False,
domain_initial_dot=False,
path='/',
path_specified=True,
secure=False,
expires=None,
discard=True,
comment=None,
comment_url=None,
rest={'HttpOnly': None},
rfc2109=False
)
# add cookie to cookiejar
cj.set_cookie(cookie)
return cj
def get_encodings_from_content(content):
"""Returns encodings from given content string.
:param content: bytestring to extract encodings from.
"""
charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I)
return charset_re.findall(content)
def get_encoding_from_headers(headers):
"""Returns encodings from given HTTP Header Dict.
:param headers: dictionary to extract encoding from.
"""
content_type = headers.get('content-type')
if not content_type:
return None
content_type, params = cgi.parse_header(content_type)
if 'charset' in params:
return params['charset'].strip("'\"")
def unicode_from_html(content):
"""Attempts to decode an HTML string into unicode.
If unsuccessful, the original content is returned.
"""
encodings = get_encodings_from_content(content)
for encoding in encodings:
try:
return str(content, encoding)
except (UnicodeError, TypeError):
pass
return content
def stream_decode_response_unicode(iterator, r):
"""Stream decodes a iterator."""
encoding = get_encoding_from_headers(r.headers)
if encoding is None:
for item in iterator:
yield item
return
decoder = codecs.getincrementaldecoder(encoding)(errors='replace')
for chunk in iterator:
rv = decoder.decode(chunk)
if rv:
yield rv
rv = decoder.decode('', final=True)
if rv:
yield rv
def get_unicode_from_response(r):
"""Returns the requested content back in unicode.
:param r: Response object to get unicode content from.
Tried:
1. charset from content-type
2. every encodings from ``<meta ... charset=XXX>``
3. fall back and replace all unicode characters
"""
tried_encodings = []
# Try charset from content-type
encoding = get_encoding_from_headers(r.headers)
if encoding:
try:
return str(r.content, encoding)
except UnicodeError:
tried_encodings.append(encoding)
# Fall back:
try:
return str(r.content, encoding, errors='replace')
except TypeError:
return r.content
def decode_gzip(content):
"""Return gzip-decoded string.
:param content: bytestring to gzip-decode.
"""
return zlib.decompress(content, 16 + zlib.MAX_WBITS)
def stream_decode_gzip(iterator):
"""Stream decodes a gzip-encoded iterator"""
try:
dec = zlib.decompressobj(16 + zlib.MAX_WBITS)
for chunk in iterator:
rv = dec.decompress(chunk)
if rv:
yield rv
buf = dec.decompress('')
rv = buf + dec.flush()
if rv:
yield rv
except zlib.error:
pass
|
the-stack_0_8520 | from enum import Enum
import random
import pampy
class Case(Enum):
Nominative = 1
Accusative = 2
Genitive = 3
Dative = 4
class Gender(Enum):
Female = 1
Masculine = 2
Neutral = 3
class Declension(Enum):
First = 1
Second = 2
Third = 3
class Number(Enum):
Single = 1
Dual = 2
Plural = 3
def decline_noun(stem: str, genitiveEnding: str, declension: Declension, gender: Gender, number: Number, case: Case) -> str:
input = [declension, gender, number]
return pampy.match(
input,
[Declension.First, Gender.Female, Number.Single],
decline_first_decl_female_singular(stem, genitiveEnding, case),
[Declension.First, Gender.Female, Number.Dual],
decline_first_decl_female_dual(stem, case),
[Declension.First, Gender.Female, Number.Plural],
decline_first_decl_female_dual(stem, case),
[str, str, Declension, Gender, Number, Case], ''
)
def decline_first_decl_female_singular(stem: str, genitiveEnding: str, case: Case):
return pampy.match(
case,
Case.Nominative, stem + 'α',
Case.Accusative, stem + 'αν',
Case.Genitive, stem + 'ᾱς',
Case.Dative, stem + 'ᾳ'
)
def decline_first_decl_female_plural(stem: str, case: Case):
return pampy.match(
case,
Case.Nominative, stem + 'αι',
Case.Accusative, stem + 'ᾱς',
Case.Genitive, stem + 'ων',
Case.Dative, stem + 'αις'
)
def decline_first_decl_female_dual(stem: str, case: Case):
return pampy.match(
case,
Case.Nominative, stem + 'ᾱ',
Case.Accusative, stem + 'ᾱ',
Case.Genitive, stem + 'αιν',
Case.Dative, stem + 'αιν'
)
all_cases = list(set(Case))
all_non_nominative_cases = list(set(all_cases) - set([Case.Nominative]))
all_genders = list(set(Gender))
all_declensions = list(set(Declension))
all_numbers = list(set(Number))
class Noun:
def __init__(self, stem: str, genitiveEnding: str, declension: Declension, gender: Gender):
self.stem = stem
self.genitiveEnding = genitiveEnding
self.declension = declension
self.gender = gender
def decline(self, number: Number, case: Case) -> str:
return decline_noun(self.stem, self.genitiveEnding, self.declension, self.gender, number, case)
def create_initial_form(self) -> str:
return self.decline(Number.Single, Case.Nominative)
def create_random_form(self) -> (str, Number, Case):
random_number = random.choice(all_numbers)
random_case = random.choice(all_non_nominative_cases)
declined_word = self.decline(random_number, random_case)
return (declined_word, random_number, random_case)
class Answer:
def __init__(self, value: str, isValid: bool) -> None:
self.value = value
self.isValid = isValid
class Question:
def __init__(self, question: str, answers: list) -> None:
self.question = question
self.answers = answers
def strNum(number: Number) -> str:
return pampy.match(number,
Number.Plural, 'множественном числе',
Number.Dual, 'двойственном числе',
Number.Single, 'единственном числе',
)
def strCase(c: Case) -> str:
return pampy.match(c,
Case.Nominative, 'номинативе',
Case.Accusative, 'аккузативе',
Case.Genitive, 'генитиве',
Case.Dative, 'дативе',
)
def create_question(word: Noun) -> Question:
(correct_form, number, case) = word.create_random_form()
forms = [correct_form]
while len(forms) < 4:
(new_answer, _, _) = word.create_random_form()
if new_answer not in forms:
forms.append(new_answer)
random.shuffle(forms)
answers = list(map(lambda x: Answer(x, x == correct_form), forms))
return Question(
question = f'{word.create_initial_form().capitalize()} в {strNum(number)} {strCase(case)}?',
answers = answers
)
|
the-stack_0_8521 | from __future__ import print_function
import time
class Looper(object):
"""Represents the state of a loop of events."""
RECORD, PAUSE, PLAY = 'record', 'pause', 'play'
def __init__(self, state=PAUSE, events=None, loop_length=0):
self.state = state
if state == Looper.RECORD:
self.state = Looper.PAUSE
self.events = events or []
self.loop_length = loop_length
self.loop_start = 0
self.loop_index = 0
def event(self, key):
if self.state == Looper.RECORD:
self.events.append((time.time() - self.loop_start, key))
def clear(self):
self.state = Looper.PAUSE
self.events = []
def set_state(self, state):
if state != self.state:
t = time.time()
if self.state == Looper.RECORD:
self.loop_length = t - self.loop_start
self.loop_start = 0
self.loop_index = 0
elif self.state == Looper.PLAY:
self.loop_start = t - self.loop_start
self.state = state
if self.state == Looper.PLAY:
self.loop_start = t - self.loop_start
if self.state == Looper.RECORD:
self.events = []
self.loop_start = t
print('Entering state', self.state)
def record(self):
"""Toggle record."""
self.set_state(Looper.PLAY if self.state == Looper.RECORD
else Looper.RECORD)
def play(self):
self.set_state(Looper.PLAY if self.state == Looper.PAUSE
else Looper.PAUSE)
def step(self, callback):
def emit(dt):
while self.loop_index < len(self.events):
etime, key = self.events[self.loop_index]
if etime > dt:
break
callback(key)
self.loop_index += 1
if self.state == Looper.PLAY:
t = time.time()
dt = t - self.loop_start
emit(min(dt, self.loop_length))
if dt >= self.loop_length:
self.loop_index = 0
dt -= self.loop_length
self.loop_start = t - dt
emit(dt)
|
the-stack_0_8522 | from . import BaseAction
from ..db.controllers import ServerController
class SetAdminRoleAction(BaseAction):
action_name = "imdb_tv_shows"
admin = True
controller = ServerController()
async def action(self, msg):
toggle_value = self.get_message_data(msg)
if not toggle_value:
await msg.channel.send(
"Must give value of on or off for imdb_tv_shows command"
)
return
toggle_value = toggle_value.lower()
if toggle_value == "on":
allow_tv_shows = True
elif toggle_value == "off":
allow_tv_shows = False
else:
await msg.channel.send(
f"Unknown value given. Value must be on or off, got {toggle_value}."
)
return
with self.controller.transaction():
server_row = self.controller.get_by_id(msg.guild.id)
server_row.allow_tv_shows = allow_tv_shows
self.controller.update(server_row)
await msg.channel.send(f"Allow IMDB tv show search turned {toggle_value}")
@property
def help_text(self):
return "Toggles whether to allow tv shows in the IMDB search results (on) or not (off)."
@property
def help_options(self):
return ["(on|off)"]
|
the-stack_0_8523 | #!/usr/bin/env python
import unittest
import socket
from framework import VppTestCase, VppTestRunner
from vpp_ip_route import VppIpRoute, VppRoutePath, VppMplsRoute, \
VppMplsTable, VppIpMRoute, VppMRoutePath, VppIpTable, \
MRouteEntryFlags, MRouteItfFlags, MPLS_LABEL_INVALID, DpoProto
from vpp_bier import *
from scapy.packet import Raw
from scapy.layers.l2 import Ether
from scapy.layers.inet import IP, UDP, ICMP
from scapy.layers.inet6 import IPv6
from scapy.contrib.mpls import MPLS
from scapy.contrib.bier import *
class TestBFIB(VppTestCase):
""" BIER FIB Test Case """
def test_bfib(self):
""" BFIB Unit Tests """
error = self.vapi.cli("test bier")
if error:
self.logger.critical(error)
self.assertEqual(error.find("Failed"), -1)
class TestBier(VppTestCase):
""" BIER Test Case """
def setUp(self):
super(TestBier, self).setUp()
# create 2 pg interfaces
self.create_pg_interfaces(range(3))
# create the default MPLS table
self.tables = []
tbl = VppMplsTable(self, 0)
tbl.add_vpp_config()
self.tables.append(tbl)
tbl = VppIpTable(self, 10)
tbl.add_vpp_config()
self.tables.append(tbl)
# setup both interfaces
for i in self.pg_interfaces:
if i == self.pg2:
i.set_table_ip4(10)
i.admin_up()
i.config_ip4()
i.resolve_arp()
i.enable_mpls()
def tearDown(self):
for i in self.pg_interfaces:
i.disable_mpls()
i.unconfig_ip4()
i.set_table_ip4(0)
i.admin_down()
super(TestBier, self).tearDown()
def send_and_assert_no_replies(self, intf, pkts, remark):
intf.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
for i in self.pg_interfaces:
i.assert_nothing_captured(remark=remark)
def send_and_expect(self, input, pkts, output):
self.vapi.cli("trace add bier-mpls-lookup 10")
input.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
rx = output.get_capture(len(pkts))
def test_bier_midpoint(self):
"""BIER midpoint"""
#
# Add a BIER table for sub-domain 0, set 0, and BSL 256
#
bti = VppBierTableID(0, 0, BIERLength.BIER_LEN_256)
bt = VppBierTable(self, bti, 77)
bt.add_vpp_config()
#
# A packet with no bits set gets dropped
#
p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
MPLS(label=77, ttl=255) /
BIER(length=BIERLength.BIER_LEN_256,
BitString=chr(0)*64) /
IPv6(src=self.pg0.remote_ip6, dst=self.pg0.remote_ip6) /
UDP(sport=1234, dport=1234) /
Raw())
pkts = [p]
self.send_and_assert_no_replies(self.pg0, pkts,
"Empty Bit-String")
#
# Add a BIER route for each bit-position in the table via a different
# next-hop. Testing whether the BIER walk and replicate forwarding
# function works for all bit posisitons.
#
nh_routes = []
bier_routes = []
for i in range(1, 256):
nh = "10.0.%d.%d" % (i / 255, i % 255)
nh_routes.append(VppIpRoute(self, nh, 32,
[VppRoutePath(self.pg1.remote_ip4,
self.pg1.sw_if_index,
labels=[2000+i])]))
nh_routes[-1].add_vpp_config()
bier_routes.append(VppBierRoute(self, bti, i, nh, 100+i))
bier_routes[-1].add_vpp_config()
#
# A packet with all bits set gets spat out to BP:1
#
p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
MPLS(label=77, ttl=255) /
BIER(length=BIERLength.BIER_LEN_256) /
IPv6(src=self.pg0.remote_ip6, dst=self.pg0.remote_ip6) /
UDP(sport=1234, dport=1234) /
Raw())
pkts = [p]
self.pg0.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
rx = self.pg1.get_capture(255)
for rxp in rx:
#
# The packets are not required to be sent in bit-position order
# when we setup the routes above we used the bit-position to
# construct the out-label. so use that here to determine the BP
#
olabel = rxp[MPLS]
bp = olabel.label - 2000
blabel = olabel[MPLS].payload
self.assertEqual(blabel.label, 100+bp)
bier_hdr = blabel[MPLS].payload
self.assertEqual(bier_hdr.id, 5)
self.assertEqual(bier_hdr.version, 0)
self.assertEqual(bier_hdr.length, BIERLength.BIER_LEN_256)
self.assertEqual(bier_hdr.entropy, 0)
self.assertEqual(bier_hdr.OAM, 0)
self.assertEqual(bier_hdr.RSV, 0)
self.assertEqual(bier_hdr.DSCP, 0)
self.assertEqual(bier_hdr.Proto, 5)
# The bit-string should consist only of the BP given by i.
i = 0
bitstring = ""
bpi = bp - 1
while (i < bpi/8):
bitstring = chr(0) + bitstring
i += 1
bitstring = chr(1 << bpi % 8) + bitstring
while len(bitstring) < 32:
bitstring = chr(0) + bitstring
self.assertEqual(len(bitstring), len(bier_hdr.BitString))
self.assertEqual(bitstring, bier_hdr.BitString)
def test_bier_head(self):
"""BIER head"""
#
# Add a BIER table for sub-domain 0, set 0, and BSL 256
#
bti = VppBierTableID(0, 0, BIERLength.BIER_LEN_256)
bt = VppBierTable(self, bti, 77)
bt.add_vpp_config()
#
# 2 bit positions via two next hops
#
nh1 = "10.0.0.1"
nh2 = "10.0.0.2"
ip_route_1 = VppIpRoute(self, nh1, 32,
[VppRoutePath(self.pg1.remote_ip4,
self.pg1.sw_if_index,
labels=[2001])])
ip_route_2 = VppIpRoute(self, nh2, 32,
[VppRoutePath(self.pg1.remote_ip4,
self.pg1.sw_if_index,
labels=[2002])])
ip_route_1.add_vpp_config()
ip_route_2.add_vpp_config()
bier_route_1 = VppBierRoute(self, bti, 1, nh1, 101)
bier_route_2 = VppBierRoute(self, bti, 2, nh2, 102)
bier_route_1.add_vpp_config()
bier_route_2.add_vpp_config()
#
# An imposition object with both bit-positions set
#
bi = VppBierImp(self, bti, 333, chr(0x3) * 32)
bi.add_vpp_config()
#
# Add a multicast route that will forward into the BIER doamin
#
route_ing_232_1_1_1 = VppIpMRoute(
self,
"0.0.0.0",
"232.1.1.1", 32,
MRouteEntryFlags.MFIB_ENTRY_FLAG_NONE,
paths=[VppMRoutePath(self.pg0.sw_if_index,
MRouteItfFlags.MFIB_ITF_FLAG_ACCEPT),
VppMRoutePath(0xffffffff,
MRouteItfFlags.MFIB_ITF_FLAG_FORWARD,
proto=DpoProto.DPO_PROTO_BIER,
bier_imp=bi.bi_index)])
route_ing_232_1_1_1.add_vpp_config()
#
# inject a packet an IP. We expect it to be BIER encapped,
# replicated.
#
p = (Ether(dst=self.pg0.local_mac,
src=self.pg0.remote_mac) /
IP(src="1.1.1.1", dst="232.1.1.1") /
UDP(sport=1234, dport=1234))
self.pg0.add_stream([p])
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
rx = self.pg1.get_capture(2)
def test_bier_tail(self):
"""BIER Tail"""
#
# Add a BIER table for sub-domain 0, set 0, and BSL 256
#
bti = VppBierTableID(0, 0, BIERLength.BIER_LEN_256)
bt = VppBierTable(self, bti, 77)
bt.add_vpp_config()
#
# disposition table
#
bdt = VppBierDispTable(self, 8)
bdt.add_vpp_config()
#
# BIER route in table that's for-us
#
bier_route_1 = VppBierRoute(self, bti, 1, "0.0.0.0", 0,
disp_table=8)
bier_route_1.add_vpp_config()
#
# An entry in the disposition table
#
bier_de_1 = VppBierDispEntry(self, bdt.id, 99,
BIER_HDR_PAYLOAD.BIER_HDR_PROTO_IPV4,
"0.0.0.0", 0, rpf_id=8192)
bier_de_1.add_vpp_config()
#
# A multicast route to forward post BIER disposition
#
route_eg_232_1_1_1 = VppIpMRoute(
self,
"0.0.0.0",
"232.1.1.1", 32,
MRouteEntryFlags.MFIB_ENTRY_FLAG_NONE,
paths=[VppMRoutePath(self.pg1.sw_if_index,
MRouteItfFlags.MFIB_ITF_FLAG_FORWARD)])
route_eg_232_1_1_1.add_vpp_config()
route_eg_232_1_1_1.update_rpf_id(8192)
#
# A packet with all bits set gets spat out to BP:1
#
p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
MPLS(label=77, ttl=255) /
BIER(length=BIERLength.BIER_LEN_256, BFRID=99) /
IP(src="1.1.1.1", dst="232.1.1.1") /
UDP(sport=1234, dport=1234) /
Raw())
self.send_and_expect(self.pg0, [p], self.pg1)
def test_bier_e2e(self):
""" BIER end-to-end """
#
# Add a BIER table for sub-domain 0, set 0, and BSL 256
#
bti = VppBierTableID(0, 0, BIERLength.BIER_LEN_256)
bt = VppBierTable(self, bti, 77)
bt.add_vpp_config()
#
# Impostion Sets bit string 101010101....
# sender 333
#
bi = VppBierImp(self, bti, 333, chr(0x5) * 32)
bi.add_vpp_config()
#
# Add a multicast route that will forward into the BIER doamin
#
route_ing_232_1_1_1 = VppIpMRoute(
self,
"0.0.0.0",
"232.1.1.1", 32,
MRouteEntryFlags.MFIB_ENTRY_FLAG_NONE,
paths=[VppMRoutePath(self.pg0.sw_if_index,
MRouteItfFlags.MFIB_ITF_FLAG_ACCEPT),
VppMRoutePath(0xffffffff,
MRouteItfFlags.MFIB_ITF_FLAG_FORWARD,
proto=DpoProto.DPO_PROTO_BIER,
bier_imp=bi.bi_index)])
route_ing_232_1_1_1.add_vpp_config()
#
# disposition table 8
#
bdt = VppBierDispTable(self, 8)
bdt.add_vpp_config()
#
# BIER route in table that's for-us, resolving through
# disp table 8.
#
bier_route_1 = VppBierRoute(self, bti, 1, "0.0.0.0",
MPLS_LABEL_INVALID,
disp_table=8)
bier_route_1.add_vpp_config()
#
# An entry in the disposition table for sender 333
# lookup in VRF 10
#
bier_de_1 = VppBierDispEntry(self, bdt.id, 333,
BIER_HDR_PAYLOAD.BIER_HDR_PROTO_IPV4,
"0.0.0.0", 10, rpf_id=8192)
bier_de_1.add_vpp_config()
#
# Add a multicast route that will forward the traffic
# post-disposition
#
route_eg_232_1_1_1 = VppIpMRoute(
self,
"0.0.0.0",
"232.1.1.1", 32,
MRouteEntryFlags.MFIB_ENTRY_FLAG_NONE,
table_id=10,
paths=[VppMRoutePath(self.pg1.sw_if_index,
MRouteItfFlags.MFIB_ITF_FLAG_FORWARD)])
route_eg_232_1_1_1.add_vpp_config()
route_eg_232_1_1_1.update_rpf_id(8192)
#
# inject a packet in VRF-0. We expect it to be BIER encapped,
# replicated, then hit the disposition and be forwarded
# out of VRF 10, i.e. on pg1
#
p = (Ether(dst=self.pg0.local_mac,
src=self.pg0.remote_mac) /
IP(src="1.1.1.1", dst="232.1.1.1") /
UDP(sport=1234, dport=1234))
self.send_and_expect(self.pg0, p*65, self.pg1)
if __name__ == '__main__':
unittest.main(testRunner=VppTestRunner)
|
the-stack_0_8524 | from __future__ import unicode_literals
import arrow
import json
import unittest
import sys
from httmock import HTTMock
from nose.tools import eq_
from misfit import Misfit, MisfitGoal, MisfitSummary
from misfit.exceptions import MisfitException
from .mocks import MisfitHttMock
class TestMisfitAPI(unittest.TestCase):
def setUp(self):
self.misfit = Misfit('FAKE_ID', 'FAKE_SECRET', 'FAKE_TOKEN')
def test_goal(self):
""" Test retrieving a goal by date range """
goal_dict = {
"id": "51a4189acf12e53f81000001",
"date": "2014-10-05",
"points": 500,
"targetPoints": 1000,
"timeZoneOffset": -8
}
end_date = '2014-10-07'
with HTTMock(MisfitHttMock('goal').json_http):
goal_list = self.misfit.goal(start_date=goal_dict['date'],
end_date=end_date)
eq_(len(goal_list), 3)
goal = goal_list[0]
eq_(type(goal), MisfitGoal)
self.assert_misfit_string(goal, goal_dict)
eq_(goal_list[2].date, arrow.get(end_date))
eq_(goal.id, goal_dict['id'])
eq_(goal.date, arrow.get(goal_dict['date']))
eq_(goal.points, goal_dict['points'])
eq_(goal.targetPoints, goal_dict['targetPoints'])
eq_(goal.timeZoneOffset, goal_dict['timeZoneOffset'])
self.assertAlmostEqual(goal.percent_complete(), 50)
# Check that percent_complete is None if targetPoints is 0
goal.targetPoints = 0
assert goal.percent_complete() is None
def test_goal_single(self):
""" Test retrieving a goal by object_id """
goal_dict = {
"id": "51a4189acf12e53f81000001",
"date": "2014-10-05",
"points": 500,
"targetPoints": 1000,
"timeZoneOffset": -8
}
with HTTMock(MisfitHttMock('goal_single').json_http):
goal = self.misfit.goal(object_id=goal_dict['id'])
eq_(type(goal), MisfitGoal)
self.assert_misfit_string(goal, goal_dict)
eq_(goal.id, goal_dict['id'])
eq_(goal.date, arrow.get(goal_dict['date']))
eq_(goal.points, goal_dict['points'])
eq_(goal.targetPoints, goal_dict['targetPoints'])
eq_(goal.timeZoneOffset, goal_dict['timeZoneOffset'])
self.assertAlmostEqual(goal.percent_complete(), 50)
# Check that percent_complete is None if targetPoints is 0
goal.targetPoints = 0
assert goal.percent_complete() is None
def test_goal_object_date_exception(self):
"""
Check that an exception is raised when no date range or object id is
supplied to goal
"""
self.assertRaises(MisfitException, self.misfit.goal)
def test_summary(self):
""" Test retrieving a non-detail summary """
date_range = {'start_date': '2014-12-10', 'end_date': '2014-12-17'}
with HTTMock(MisfitHttMock('summary').json_http):
summary = self.misfit.summary(start_date='2014-12-10',
end_date='2014-12-17')
summ_dict = {
'activityCalories': 1449.2,
'calories': 16310.24,
'distance': 13.5227,
'points': 3550,
'steps': 34030
}
eq_(type(summary), MisfitSummary)
self.assert_misfit_string(summary, summ_dict)
eq_(summary.data, summ_dict)
eq_(summary.activityCalories, summ_dict['activityCalories'])
eq_(summary.calories, summ_dict['calories'])
eq_(summary.distance, summ_dict['distance'])
eq_(summary.points, summ_dict['points'])
eq_(summary.steps, summ_dict['steps'])
def test_summary_detail(self):
summ_dict = {
"date": "2014-10-05",
"points": 394.4,
"steps": 3650,
"calories": 1687.4735,
"activityCalories": 412.3124,
"distance": 1.18
}
end_date = "2014-10-07"
with HTTMock(MisfitHttMock('summary_detail').json_http):
summary_list = self.misfit.summary(
start_date=summ_dict['date'], end_date=end_date, detail=True)
eq_(len(summary_list), 3)
summary = summary_list[0]
eq_(type(summary), MisfitSummary)
self.assert_misfit_string(summary, summ_dict)
eq_(summary_list[2].date, arrow.get(end_date))
eq_(summary.data, summ_dict)
eq_(summary.date, arrow.get(summ_dict['date']))
eq_(summary.points, summ_dict['points'])
eq_(summary.steps, summ_dict['steps'])
eq_(summary.calories, summ_dict['calories'])
eq_(summary.activityCalories, summ_dict['activityCalories'])
eq_(summary.distance, summ_dict['distance'])
def assert_misfit_string(self, obj, data):
"""
The string representing the misfit object should be the classname,
followed by a ":", followed by the json data
"""
parts = ('%s' % obj).split(': ', 1)
eq_(parts[0], '%s' % type(obj))
eq_(json.loads(parts[1]), data)
|
the-stack_0_8528 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# keplerian documentation build configuration file, created by
# sphinx-quickstart on Fri Jun 9 13:47:02 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
# If extensions (or modules to document with autodoc) are in another
# directory, add these directories to sys.path here. If the directory is
# relative to the documentation root, use os.path.abspath to make it
# absolute, like shown here.
#
import os
import sys
sys.path.insert(0, os.path.abspath('..'))
import keplerian
# -- General configuration ---------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'keplerian'
copyright = u"2018, João Faria"
author = u"João Faria"
# The version info for the project you're documenting, acts as replacement
# for |version| and |release|, also used in various other places throughout
# the built documents.
#
# The short X.Y version.
version = keplerian.__version__
# The full version, including alpha/beta/rc tags.
release = keplerian.__version__
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output -------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'alabaster'
# Theme options are theme-specific and customize the look and feel of a
# theme further. For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# -- Options for HTMLHelp output ---------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'kepleriandoc'
# -- Options for LaTeX output ------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass
# [howto, manual, or own class]).
latex_documents = [
(master_doc, 'keplerian.tex',
u'keplerian Documentation',
u'João Faria', 'manual'),
]
# -- Options for manual page output ------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'keplerian',
u'keplerian Documentation',
[author], 1)
]
# -- Options for Texinfo output ----------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'keplerian',
u'keplerian Documentation',
author,
'keplerian',
'One line description of project.',
'Miscellaneous'),
]
|
the-stack_0_8532 | import time, traceback, json
import rethinkdb as r
TIX = 'tix' # DB
VENU = 'venu' # TABLE
ID = 'id' # COLUMN
TS = 'ts' # COLUMN
SMAP = 'smap' # COLUMN
UMAP = 'umap' # COLUMN
MAX = 'max' # COLUMN
CNT = 20 # number of seats
def init(conn, event):
# try to drop table (may or may not exist)
rv = ''
try:
r.db_drop(TIX).run(conn)
rv = 'dropped, then created'
except:
rv = 'created'
r.db_create(TIX).run(conn)
r.db(TIX).table_create(VENU).run(conn)
r.db(TIX).table(VENU).index_create(TS).run(conn)
smap = {}
umap = {}
for x in range(1, CNT + 1):
smap[str(x)] = 'free'
umap[str(x)] = ''
rv += str(r.db(TIX).table(VENU).insert({
ID: 0,
SMAP: smap,
UMAP: umap,
MAX: CNT,
TS: time.time()
}).run(conn))
return rv
def hold(conn, event):
snum = str(event.get('snum'))
unum = str(event.get('unum'))
smap = {}
umap = {}
smap = r.db(TIX).table(VENU).get(0).get_field(SMAP).run(conn)
umap = r.db(TIX).table(VENU).get(0).get_field(UMAP).run(conn)
smap[snum] = 'held'
umap[snum] = unum
result = r.db(TIX).table(VENU).get(0).update(lambda VENU:
r.branch(
VENU[SMAP][snum] == 'free',
{SMAP: smap, UMAP: umap, TS: time.time()},
{}
)
).run(conn)
if result:
return result
def book(conn, event):
unum = str(event.get('unum'))
smap = {}
umap = {}
smap = r.db(TIX).table(VENU).get(0).get_field(SMAP).run(conn)
umap = r.db(TIX).table(VENU).get(0).get_field(UMAP).run(conn)
for x in range (1, CNT + 1):
if smap[str(x)] == 'held' and umap[str(x)] == unum:
smap[str(x)] = 'booked'
result = r.db(TIX).table(VENU).get(0).update({
SMAP: smap,
TS: time.time()
}).run(conn)
if result:
return result
def updates(conn, event):
ts = event.get('ts', 0)
for row in (r.db(TIX).table(VENU).filter(r.row[TS] > ts).
changes(include_initial=True).run(conn)):
return row['new_val']
def handler(conn, event):
fn = {'init': init,
'hold': hold,
'book': book,
'updates': updates}.get(event['op'], None)
if fn != None:
try:
result = fn(conn, event)
return {'result': result}
except Exception:
return {'error': traceback.format_exc()}
else:
return {'error': 'bad op'}
|
the-stack_0_8534 | # Copyright 2002 Gary Strangman. All rights reserved
# Copyright 2002-2016 The SciPy Developers
#
# The original code from Gary Strangman was heavily adapted for
# use in SciPy by Travis Oliphant. The original code came with the
# following disclaimer:
#
# This software is provided "as-is". There are no expressed or implied
# warranties of any kind, including, but not limited to, the warranties
# of merchantability and fitness for a given application. In no event
# shall Gary Strangman be liable for any direct, indirect, incidental,
# special, exemplary or consequential damages (including, but not limited
# to, loss of use, data or profits, or business interruption) however
# caused and on any theory of liability, whether in contract, strict
# liability or tort (including negligence or otherwise) arising in any way
# out of the use of this software, even if advised of the possibility of
# such damage.
"""
A collection of basic statistical functions for Python. The function
names appear below.
Some scalar functions defined here are also available in the scipy.special
package where they work on arbitrary sized arrays.
Disclaimers: The function list is obviously incomplete and, worse, the
functions are not optimized. All functions have been tested (some more
so than others), but they are far from bulletproof. Thus, as with any
free software, no warranty or guarantee is expressed or implied. :-) A
few extra functions that don't appear in the list below can be found by
interested treasure-hunters. These functions don't necessarily have
both list and array versions but were deemed useful.
Central Tendency
----------------
.. autosummary::
:toctree: generated/
gmean
hmean
mode
Moments
-------
.. autosummary::
:toctree: generated/
moment
variation
skew
kurtosis
normaltest
Altered Versions
----------------
.. autosummary::
:toctree: generated/
tmean
tvar
tstd
tsem
describe
Frequency Stats
---------------
.. autosummary::
:toctree: generated/
itemfreq
scoreatpercentile
percentileofscore
cumfreq
relfreq
Variability
-----------
.. autosummary::
:toctree: generated/
obrientransform
sem
zmap
zscore
gstd
iqr
median_abs_deviation
Trimming Functions
------------------
.. autosummary::
:toctree: generated/
trimboth
trim1
Correlation Functions
---------------------
.. autosummary::
:toctree: generated/
pearsonr
fisher_exact
spearmanr
pointbiserialr
kendalltau
weightedtau
linregress
theilslopes
multiscale_graphcorr
Inferential Stats
-----------------
.. autosummary::
:toctree: generated/
ttest_1samp
ttest_ind
ttest_ind_from_stats
ttest_rel
chisquare
power_divergence
kstest
ks_1samp
ks_2samp
epps_singleton_2samp
mannwhitneyu
ranksums
wilcoxon
kruskal
friedmanchisquare
brunnermunzel
combine_pvalues
Statistical Distances
---------------------
.. autosummary::
:toctree: generated/
wasserstein_distance
energy_distance
ANOVA Functions
---------------
.. autosummary::
:toctree: generated/
f_oneway
Support Functions
-----------------
.. autosummary::
:toctree: generated/
rankdata
rvs_ratio_uniforms
References
----------
.. [CRCProbStat2000] Zwillinger, D. and Kokoska, S. (2000). CRC Standard
Probability and Statistics Tables and Formulae. Chapman & Hall: New
York. 2000.
"""
import warnings
import math
from math import gcd
from collections import namedtuple
from itertools import permutations
import numpy as np
from numpy import array, asarray, ma
from scipy.spatial.distance import cdist
from scipy.ndimage import measurements
from scipy._lib._util import (_lazywhere, check_random_state, MapWrapper,
rng_integers, float_factorial)
import scipy.special as special
from scipy import linalg
from . import distributions
from . import mstats_basic
from ._stats_mstats_common import (_find_repeats, linregress, theilslopes,
siegelslopes)
from ._stats import (_kendall_dis, _toint64, _weightedrankedtau,
_local_correlations)
from ._rvs_sampling import rvs_ratio_uniforms
from ._hypotests import epps_singleton_2samp, cramervonmises
__all__ = ['find_repeats', 'gmean', 'hmean', 'mode', 'tmean', 'tvar',
'tmin', 'tmax', 'tstd', 'tsem', 'moment', 'variation',
'skew', 'kurtosis', 'describe', 'skewtest', 'kurtosistest',
'normaltest', 'jarque_bera', 'itemfreq',
'scoreatpercentile', 'percentileofscore',
'cumfreq', 'relfreq', 'obrientransform',
'sem', 'zmap', 'zscore', 'iqr', 'gstd', 'median_absolute_deviation',
'median_abs_deviation',
'sigmaclip', 'trimboth', 'trim1', 'trim_mean',
'f_oneway', 'F_onewayConstantInputWarning',
'F_onewayBadInputSizesWarning',
'PearsonRConstantInputWarning', 'PearsonRNearConstantInputWarning',
'pearsonr', 'fisher_exact', 'SpearmanRConstantInputWarning',
'spearmanr', 'pointbiserialr',
'kendalltau', 'weightedtau', 'multiscale_graphcorr',
'linregress', 'siegelslopes', 'theilslopes', 'ttest_1samp',
'ttest_ind', 'ttest_ind_from_stats', 'ttest_rel',
'kstest', 'ks_1samp', 'ks_2samp',
'chisquare', 'power_divergence', 'mannwhitneyu',
'tiecorrect', 'ranksums', 'kruskal', 'friedmanchisquare',
'rankdata', 'rvs_ratio_uniforms',
'combine_pvalues', 'wasserstein_distance', 'energy_distance',
'brunnermunzel', 'epps_singleton_2samp', 'cramervonmises']
def _contains_nan(a, nan_policy='propagate'):
policies = ['propagate', 'raise', 'omit']
if nan_policy not in policies:
raise ValueError("nan_policy must be one of {%s}" %
', '.join("'%s'" % s for s in policies))
try:
# Calling np.sum to avoid creating a huge array into memory
# e.g. np.isnan(a).any()
with np.errstate(invalid='ignore'):
contains_nan = np.isnan(np.sum(a))
except TypeError:
# This can happen when attempting to sum things which are not
# numbers (e.g. as in the function `mode`). Try an alternative method:
try:
contains_nan = np.nan in set(a.ravel())
except TypeError:
# Don't know what to do. Fall back to omitting nan values and
# issue a warning.
contains_nan = False
nan_policy = 'omit'
warnings.warn("The input array could not be properly checked for nan "
"values. nan values will be ignored.", RuntimeWarning)
if contains_nan and nan_policy == 'raise':
raise ValueError("The input contains nan values")
return contains_nan, nan_policy
def _chk_asarray(a, axis):
if axis is None:
a = np.ravel(a)
outaxis = 0
else:
a = np.asarray(a)
outaxis = axis
if a.ndim == 0:
a = np.atleast_1d(a)
return a, outaxis
def _chk2_asarray(a, b, axis):
if axis is None:
a = np.ravel(a)
b = np.ravel(b)
outaxis = 0
else:
a = np.asarray(a)
b = np.asarray(b)
outaxis = axis
if a.ndim == 0:
a = np.atleast_1d(a)
if b.ndim == 0:
b = np.atleast_1d(b)
return a, b, outaxis
def _shape_with_dropped_axis(a, axis):
"""
Given an array `a` and an integer `axis`, return the shape
of `a` with the `axis` dimension removed.
Examples
--------
>>> a = np.zeros((3, 5, 2))
>>> _shape_with_dropped_axis(a, 1)
(3, 2)
"""
shp = list(a.shape)
try:
del shp[axis]
except IndexError:
raise np.AxisError(axis, a.ndim) from None
return tuple(shp)
def _broadcast_shapes(shape1, shape2):
"""
Given two shapes (i.e. tuples of integers), return the shape
that would result from broadcasting two arrays with the given
shapes.
Examples
--------
>>> _broadcast_shapes((2, 1), (4, 1, 3))
(4, 2, 3)
"""
d = len(shape1) - len(shape2)
if d <= 0:
shp1 = (1,)*(-d) + shape1
shp2 = shape2
elif d > 0:
shp1 = shape1
shp2 = (1,)*d + shape2
shape = []
for n1, n2 in zip(shp1, shp2):
if n1 == 1:
n = n2
elif n2 == 1 or n1 == n2:
n = n1
else:
raise ValueError(f'shapes {shape1} and {shape2} could not be '
'broadcast together')
shape.append(n)
return tuple(shape)
def _broadcast_shapes_with_dropped_axis(a, b, axis):
"""
Given two arrays `a` and `b` and an integer `axis`, find the
shape of the broadcast result after dropping `axis` from the
shapes of `a` and `b`.
Examples
--------
>>> a = np.zeros((5, 2, 1))
>>> b = np.zeros((1, 9, 3))
>>> _broadcast_shapes_with_dropped_axis(a, b, 1)
(5, 3)
"""
shp1 = _shape_with_dropped_axis(a, axis)
shp2 = _shape_with_dropped_axis(b, axis)
try:
shp = _broadcast_shapes(shp1, shp2)
except ValueError:
raise ValueError(f'non-axis shapes {shp1} and {shp2} could not be '
'broadcast together') from None
return shp
def gmean(a, axis=0, dtype=None, weights=None):
"""
Compute the geometric mean along the specified axis.
Return the geometric average of the array elements.
That is: n-th root of (x1 * x2 * ... * xn)
Parameters
----------
a : array_like
Input array or object that can be converted to an array.
axis : int or None, optional
Axis along which the geometric mean is computed. Default is 0.
If None, compute over the whole array `a`.
dtype : dtype, optional
Type of the returned array and of the accumulator in which the
elements are summed. If dtype is not specified, it defaults to the
dtype of a, unless a has an integer dtype with a precision less than
that of the default platform integer. In that case, the default
platform integer is used.
weights : array_like, optional
The weights array can either be 1-D (in which case its length must be
the size of `a` along the given `axis`) or of the same shape as `a`.
Default is None, which gives each value a weight of 1.0.
Returns
-------
gmean : ndarray
See `dtype` parameter above.
See Also
--------
numpy.mean : Arithmetic average
numpy.average : Weighted average
hmean : Harmonic mean
Notes
-----
The geometric average is computed over a single dimension of the input
array, axis=0 by default, or all values in the array if axis=None.
float64 intermediate and return values are used for integer inputs.
Use masked arrays to ignore any non-finite values in the input or that
arise in the calculations such as Not a Number and infinity because masked
arrays automatically mask any non-finite values.
References
----------
.. [1] "Weighted Geometric Mean", *Wikipedia*, https://en.wikipedia.org/wiki/Weighted_geometric_mean.
Examples
--------
>>> from scipy.stats import gmean
>>> gmean([1, 4])
2.0
>>> gmean([1, 2, 3, 4, 5, 6, 7])
3.3800151591412964
"""
if not isinstance(a, np.ndarray):
# if not an ndarray object attempt to convert it
log_a = np.log(np.array(a, dtype=dtype))
elif dtype:
# Must change the default dtype allowing array type
if isinstance(a, np.ma.MaskedArray):
log_a = np.log(np.ma.asarray(a, dtype=dtype))
else:
log_a = np.log(np.asarray(a, dtype=dtype))
else:
log_a = np.log(a)
if weights is not None:
weights = np.asanyarray(weights, dtype=dtype)
return np.exp(np.average(log_a, axis=axis, weights=weights))
def hmean(a, axis=0, dtype=None):
"""
Calculate the harmonic mean along the specified axis.
That is: n / (1/x1 + 1/x2 + ... + 1/xn)
Parameters
----------
a : array_like
Input array, masked array or object that can be converted to an array.
axis : int or None, optional
Axis along which the harmonic mean is computed. Default is 0.
If None, compute over the whole array `a`.
dtype : dtype, optional
Type of the returned array and of the accumulator in which the
elements are summed. If `dtype` is not specified, it defaults to the
dtype of `a`, unless `a` has an integer `dtype` with a precision less
than that of the default platform integer. In that case, the default
platform integer is used.
Returns
-------
hmean : ndarray
See `dtype` parameter above.
See Also
--------
numpy.mean : Arithmetic average
numpy.average : Weighted average
gmean : Geometric mean
Notes
-----
The harmonic mean is computed over a single dimension of the input
array, axis=0 by default, or all values in the array if axis=None.
float64 intermediate and return values are used for integer inputs.
Use masked arrays to ignore any non-finite values in the input or that
arise in the calculations such as Not a Number and infinity.
Examples
--------
>>> from scipy.stats import hmean
>>> hmean([1, 4])
1.6000000000000001
>>> hmean([1, 2, 3, 4, 5, 6, 7])
2.6997245179063363
"""
if not isinstance(a, np.ndarray):
a = np.array(a, dtype=dtype)
if np.all(a >= 0):
# Harmonic mean only defined if greater than or equal to to zero.
if isinstance(a, np.ma.MaskedArray):
size = a.count(axis)
else:
if axis is None:
a = a.ravel()
size = a.shape[0]
else:
size = a.shape[axis]
with np.errstate(divide='ignore'):
return size / np.sum(1.0 / a, axis=axis, dtype=dtype)
else:
raise ValueError("Harmonic mean only defined if all elements greater "
"than or equal to zero")
ModeResult = namedtuple('ModeResult', ('mode', 'count'))
def mode(a, axis=0, nan_policy='propagate'):
"""
Return an array of the modal (most common) value in the passed array.
If there is more than one such value, only the smallest is returned.
The bin-count for the modal bins is also returned.
Parameters
----------
a : array_like
n-dimensional array of which to find mode(s).
axis : int or None, optional
Axis along which to operate. Default is 0. If None, compute over
the whole array `a`.
nan_policy : {'propagate', 'raise', 'omit'}, optional
Defines how to handle when input contains nan.
The following options are available (default is 'propagate'):
* 'propagate': returns nan
* 'raise': throws an error
* 'omit': performs the calculations ignoring nan values
Returns
-------
mode : ndarray
Array of modal values.
count : ndarray
Array of counts for each mode.
Examples
--------
>>> a = np.array([[6, 8, 3, 0],
... [3, 2, 1, 7],
... [8, 1, 8, 4],
... [5, 3, 0, 5],
... [4, 7, 5, 9]])
>>> from scipy import stats
>>> stats.mode(a)
ModeResult(mode=array([[3, 1, 0, 0]]), count=array([[1, 1, 1, 1]]))
To get mode of whole array, specify ``axis=None``:
>>> stats.mode(a, axis=None)
ModeResult(mode=array([3]), count=array([3]))
"""
a, axis = _chk_asarray(a, axis)
if a.size == 0:
return ModeResult(np.array([]), np.array([]))
contains_nan, nan_policy = _contains_nan(a, nan_policy)
if contains_nan and nan_policy == 'omit':
a = ma.masked_invalid(a)
return mstats_basic.mode(a, axis)
if a.dtype == object and np.nan in set(a.ravel()):
# Fall back to a slower method since np.unique does not work with NaN
scores = set(np.ravel(a)) # get ALL unique values
testshape = list(a.shape)
testshape[axis] = 1
oldmostfreq = np.zeros(testshape, dtype=a.dtype)
oldcounts = np.zeros(testshape, dtype=int)
for score in scores:
template = (a == score)
counts = np.sum(template, axis, keepdims=True)
mostfrequent = np.where(counts > oldcounts, score, oldmostfreq)
oldcounts = np.maximum(counts, oldcounts)
oldmostfreq = mostfrequent
return ModeResult(mostfrequent, oldcounts)
def _mode1D(a):
vals, cnts = np.unique(a, return_counts=True)
return vals[cnts.argmax()], cnts.max()
# np.apply_along_axis will convert the _mode1D tuples to a numpy array, casting types in the process
# This recreates the results without that issue
# View of a, rotated so the requested axis is last
in_dims = list(range(a.ndim))
a_view = np.transpose(a, in_dims[:axis] + in_dims[axis+1:] + [axis])
inds = np.ndindex(a_view.shape[:-1])
modes = np.empty(a_view.shape[:-1], dtype=a.dtype)
counts = np.empty(a_view.shape[:-1], dtype=np.int_)
for ind in inds:
modes[ind], counts[ind] = _mode1D(a_view[ind])
newshape = list(a.shape)
newshape[axis] = 1
return ModeResult(modes.reshape(newshape), counts.reshape(newshape))
def _mask_to_limits(a, limits, inclusive):
"""Mask an array for values outside of given limits.
This is primarily a utility function.
Parameters
----------
a : array
limits : (float or None, float or None)
A tuple consisting of the (lower limit, upper limit). Values in the
input array less than the lower limit or greater than the upper limit
will be masked out. None implies no limit.
inclusive : (bool, bool)
A tuple consisting of the (lower flag, upper flag). These flags
determine whether values exactly equal to lower or upper are allowed.
Returns
-------
A MaskedArray.
Raises
------
A ValueError if there are no values within the given limits.
"""
lower_limit, upper_limit = limits
lower_include, upper_include = inclusive
am = ma.MaskedArray(a)
if lower_limit is not None:
if lower_include:
am = ma.masked_less(am, lower_limit)
else:
am = ma.masked_less_equal(am, lower_limit)
if upper_limit is not None:
if upper_include:
am = ma.masked_greater(am, upper_limit)
else:
am = ma.masked_greater_equal(am, upper_limit)
if am.count() == 0:
raise ValueError("No array values within given limits")
return am
def tmean(a, limits=None, inclusive=(True, True), axis=None):
"""
Compute the trimmed mean.
This function finds the arithmetic mean of given values, ignoring values
outside the given `limits`.
Parameters
----------
a : array_like
Array of values.
limits : None or (lower limit, upper limit), optional
Values in the input array less than the lower limit or greater than the
upper limit will be ignored. When limits is None (default), then all
values are used. Either of the limit values in the tuple can also be
None representing a half-open interval.
inclusive : (bool, bool), optional
A tuple consisting of the (lower flag, upper flag). These flags
determine whether values exactly equal to the lower or upper limits
are included. The default value is (True, True).
axis : int or None, optional
Axis along which to compute test. Default is None.
Returns
-------
tmean : float
Trimmed mean.
See Also
--------
trim_mean : Returns mean after trimming a proportion from both tails.
Examples
--------
>>> from scipy import stats
>>> x = np.arange(20)
>>> stats.tmean(x)
9.5
>>> stats.tmean(x, (3,17))
10.0
"""
a = asarray(a)
if limits is None:
return np.mean(a, None)
am = _mask_to_limits(a.ravel(), limits, inclusive)
return am.mean(axis=axis)
def tvar(a, limits=None, inclusive=(True, True), axis=0, ddof=1):
"""
Compute the trimmed variance.
This function computes the sample variance of an array of values,
while ignoring values which are outside of given `limits`.
Parameters
----------
a : array_like
Array of values.
limits : None or (lower limit, upper limit), optional
Values in the input array less than the lower limit or greater than the
upper limit will be ignored. When limits is None, then all values are
used. Either of the limit values in the tuple can also be None
representing a half-open interval. The default value is None.
inclusive : (bool, bool), optional
A tuple consisting of the (lower flag, upper flag). These flags
determine whether values exactly equal to the lower or upper limits
are included. The default value is (True, True).
axis : int or None, optional
Axis along which to operate. Default is 0. If None, compute over the
whole array `a`.
ddof : int, optional
Delta degrees of freedom. Default is 1.
Returns
-------
tvar : float
Trimmed variance.
Notes
-----
`tvar` computes the unbiased sample variance, i.e. it uses a correction
factor ``n / (n - 1)``.
Examples
--------
>>> from scipy import stats
>>> x = np.arange(20)
>>> stats.tvar(x)
35.0
>>> stats.tvar(x, (3,17))
20.0
"""
a = asarray(a)
a = a.astype(float)
if limits is None:
return a.var(ddof=ddof, axis=axis)
am = _mask_to_limits(a, limits, inclusive)
amnan = am.filled(fill_value=np.nan)
return np.nanvar(amnan, ddof=ddof, axis=axis)
def tmin(a, lowerlimit=None, axis=0, inclusive=True, nan_policy='propagate'):
"""
Compute the trimmed minimum.
This function finds the miminum value of an array `a` along the
specified axis, but only considering values greater than a specified
lower limit.
Parameters
----------
a : array_like
Array of values.
lowerlimit : None or float, optional
Values in the input array less than the given limit will be ignored.
When lowerlimit is None, then all values are used. The default value
is None.
axis : int or None, optional
Axis along which to operate. Default is 0. If None, compute over the
whole array `a`.
inclusive : {True, False}, optional
This flag determines whether values exactly equal to the lower limit
are included. The default value is True.
nan_policy : {'propagate', 'raise', 'omit'}, optional
Defines how to handle when input contains nan.
The following options are available (default is 'propagate'):
* 'propagate': returns nan
* 'raise': throws an error
* 'omit': performs the calculations ignoring nan values
Returns
-------
tmin : float, int or ndarray
Trimmed minimum.
Examples
--------
>>> from scipy import stats
>>> x = np.arange(20)
>>> stats.tmin(x)
0
>>> stats.tmin(x, 13)
13
>>> stats.tmin(x, 13, inclusive=False)
14
"""
a, axis = _chk_asarray(a, axis)
am = _mask_to_limits(a, (lowerlimit, None), (inclusive, False))
contains_nan, nan_policy = _contains_nan(am, nan_policy)
if contains_nan and nan_policy == 'omit':
am = ma.masked_invalid(am)
res = ma.minimum.reduce(am, axis).data
if res.ndim == 0:
return res[()]
return res
def tmax(a, upperlimit=None, axis=0, inclusive=True, nan_policy='propagate'):
"""
Compute the trimmed maximum.
This function computes the maximum value of an array along a given axis,
while ignoring values larger than a specified upper limit.
Parameters
----------
a : array_like
Array of values.
upperlimit : None or float, optional
Values in the input array greater than the given limit will be ignored.
When upperlimit is None, then all values are used. The default value
is None.
axis : int or None, optional
Axis along which to operate. Default is 0. If None, compute over the
whole array `a`.
inclusive : {True, False}, optional
This flag determines whether values exactly equal to the upper limit
are included. The default value is True.
nan_policy : {'propagate', 'raise', 'omit'}, optional
Defines how to handle when input contains nan.
The following options are available (default is 'propagate'):
* 'propagate': returns nan
* 'raise': throws an error
* 'omit': performs the calculations ignoring nan values
Returns
-------
tmax : float, int or ndarray
Trimmed maximum.
Examples
--------
>>> from scipy import stats
>>> x = np.arange(20)
>>> stats.tmax(x)
19
>>> stats.tmax(x, 13)
13
>>> stats.tmax(x, 13, inclusive=False)
12
"""
a, axis = _chk_asarray(a, axis)
am = _mask_to_limits(a, (None, upperlimit), (False, inclusive))
contains_nan, nan_policy = _contains_nan(am, nan_policy)
if contains_nan and nan_policy == 'omit':
am = ma.masked_invalid(am)
res = ma.maximum.reduce(am, axis).data
if res.ndim == 0:
return res[()]
return res
def tstd(a, limits=None, inclusive=(True, True), axis=0, ddof=1):
"""
Compute the trimmed sample standard deviation.
This function finds the sample standard deviation of given values,
ignoring values outside the given `limits`.
Parameters
----------
a : array_like
Array of values.
limits : None or (lower limit, upper limit), optional
Values in the input array less than the lower limit or greater than the
upper limit will be ignored. When limits is None, then all values are
used. Either of the limit values in the tuple can also be None
representing a half-open interval. The default value is None.
inclusive : (bool, bool), optional
A tuple consisting of the (lower flag, upper flag). These flags
determine whether values exactly equal to the lower or upper limits
are included. The default value is (True, True).
axis : int or None, optional
Axis along which to operate. Default is 0. If None, compute over the
whole array `a`.
ddof : int, optional
Delta degrees of freedom. Default is 1.
Returns
-------
tstd : float
Trimmed sample standard deviation.
Notes
-----
`tstd` computes the unbiased sample standard deviation, i.e. it uses a
correction factor ``n / (n - 1)``.
Examples
--------
>>> from scipy import stats
>>> x = np.arange(20)
>>> stats.tstd(x)
5.9160797830996161
>>> stats.tstd(x, (3,17))
4.4721359549995796
"""
return np.sqrt(tvar(a, limits, inclusive, axis, ddof))
def tsem(a, limits=None, inclusive=(True, True), axis=0, ddof=1):
"""
Compute the trimmed standard error of the mean.
This function finds the standard error of the mean for given
values, ignoring values outside the given `limits`.
Parameters
----------
a : array_like
Array of values.
limits : None or (lower limit, upper limit), optional
Values in the input array less than the lower limit or greater than the
upper limit will be ignored. When limits is None, then all values are
used. Either of the limit values in the tuple can also be None
representing a half-open interval. The default value is None.
inclusive : (bool, bool), optional
A tuple consisting of the (lower flag, upper flag). These flags
determine whether values exactly equal to the lower or upper limits
are included. The default value is (True, True).
axis : int or None, optional
Axis along which to operate. Default is 0. If None, compute over the
whole array `a`.
ddof : int, optional
Delta degrees of freedom. Default is 1.
Returns
-------
tsem : float
Trimmed standard error of the mean.
Notes
-----
`tsem` uses unbiased sample standard deviation, i.e. it uses a
correction factor ``n / (n - 1)``.
Examples
--------
>>> from scipy import stats
>>> x = np.arange(20)
>>> stats.tsem(x)
1.3228756555322954
>>> stats.tsem(x, (3,17))
1.1547005383792515
"""
a = np.asarray(a).ravel()
if limits is None:
return a.std(ddof=ddof) / np.sqrt(a.size)
am = _mask_to_limits(a, limits, inclusive)
sd = np.sqrt(np.ma.var(am, ddof=ddof, axis=axis))
return sd / np.sqrt(am.count())
#####################################
# MOMENTS #
#####################################
def moment(a, moment=1, axis=0, nan_policy='propagate'):
r"""
Calculate the nth moment about the mean for a sample.
A moment is a specific quantitative measure of the shape of a set of
points. It is often used to calculate coefficients of skewness and kurtosis
due to its close relationship with them.
Parameters
----------
a : array_like
Input array.
moment : int or array_like of ints, optional
Order of central moment that is returned. Default is 1.
axis : int or None, optional
Axis along which the central moment is computed. Default is 0.
If None, compute over the whole array `a`.
nan_policy : {'propagate', 'raise', 'omit'}, optional
Defines how to handle when input contains nan.
The following options are available (default is 'propagate'):
* 'propagate': returns nan
* 'raise': throws an error
* 'omit': performs the calculations ignoring nan values
Returns
-------
n-th central moment : ndarray or float
The appropriate moment along the given axis or over all values if axis
is None. The denominator for the moment calculation is the number of
observations, no degrees of freedom correction is done.
See Also
--------
kurtosis, skew, describe
Notes
-----
The k-th central moment of a data sample is:
.. math::
m_k = \frac{1}{n} \sum_{i = 1}^n (x_i - \bar{x})^k
Where n is the number of samples and x-bar is the mean. This function uses
exponentiation by squares [1]_ for efficiency.
References
----------
.. [1] https://eli.thegreenplace.net/2009/03/21/efficient-integer-exponentiation-algorithms
Examples
--------
>>> from scipy.stats import moment
>>> moment([1, 2, 3, 4, 5], moment=1)
0.0
>>> moment([1, 2, 3, 4, 5], moment=2)
2.0
"""
a, axis = _chk_asarray(a, axis)
contains_nan, nan_policy = _contains_nan(a, nan_policy)
if contains_nan and nan_policy == 'omit':
a = ma.masked_invalid(a)
return mstats_basic.moment(a, moment, axis)
if a.size == 0:
# empty array, return nan(s) with shape matching `moment`
if np.isscalar(moment):
return np.nan
else:
return np.full(np.asarray(moment).shape, np.nan, dtype=np.float64)
# for array_like moment input, return a value for each.
if not np.isscalar(moment):
mmnt = [_moment(a, i, axis) for i in moment]
return np.array(mmnt)
else:
return _moment(a, moment, axis)
def _moment(a, moment, axis):
if np.abs(moment - np.round(moment)) > 0:
raise ValueError("All moment parameters must be integers")
if moment == 0:
# When moment equals 0, the result is 1, by definition.
shape = list(a.shape)
del shape[axis]
if shape:
# return an actual array of the appropriate shape
return np.ones(shape, dtype=float)
else:
# the input was 1D, so return a scalar instead of a rank-0 array
return 1.0
elif moment == 1:
# By definition the first moment about the mean is 0.
shape = list(a.shape)
del shape[axis]
if shape:
# return an actual array of the appropriate shape
return np.zeros(shape, dtype=float)
else:
# the input was 1D, so return a scalar instead of a rank-0 array
return np.float64(0.0)
else:
# Exponentiation by squares: form exponent sequence
n_list = [moment]
current_n = moment
while current_n > 2:
if current_n % 2:
current_n = (current_n - 1) / 2
else:
current_n /= 2
n_list.append(current_n)
# Starting point for exponentiation by squares
a_zero_mean = a - np.mean(a, axis, keepdims=True)
if n_list[-1] == 1:
s = a_zero_mean.copy()
else:
s = a_zero_mean**2
# Perform multiplications
for n in n_list[-2::-1]:
s = s**2
if n % 2:
s *= a_zero_mean
return np.mean(s, axis)
def variation(a, axis=0, nan_policy='propagate', ddof=0):
"""
Compute the coefficient of variation.
The coefficient of variation is the standard deviation divided by the
mean. This function is equivalent to::
np.std(x, axis=axis, ddof=ddof) / np.mean(x)
The default for ``ddof`` is 0, but many definitions of the coefficient
of variation use the square root of the unbiased sample variance
for the sample standard deviation, which corresponds to ``ddof=1``.
Parameters
----------
a : array_like
Input array.
axis : int or None, optional
Axis along which to calculate the coefficient of variation. Default
is 0. If None, compute over the whole array `a`.
nan_policy : {'propagate', 'raise', 'omit'}, optional
Defines how to handle when input contains nan.
The following options are available (default is 'propagate'):
* 'propagate': returns nan
* 'raise': throws an error
* 'omit': performs the calculations ignoring nan values
ddof : int, optional
Delta degrees of freedom. Default is 0.
Returns
-------
variation : ndarray
The calculated variation along the requested axis.
References
----------
.. [1] Zwillinger, D. and Kokoska, S. (2000). CRC Standard
Probability and Statistics Tables and Formulae. Chapman & Hall: New
York. 2000.
Examples
--------
>>> from scipy.stats import variation
>>> variation([1, 2, 3, 4, 5])
0.47140452079103173
"""
a, axis = _chk_asarray(a, axis)
contains_nan, nan_policy = _contains_nan(a, nan_policy)
if contains_nan and nan_policy == 'omit':
a = ma.masked_invalid(a)
return mstats_basic.variation(a, axis, ddof)
return a.std(axis, ddof=ddof) / a.mean(axis)
def skew(a, axis=0, bias=True, nan_policy='propagate'):
r"""
Compute the sample skewness of a data set.
For normally distributed data, the skewness should be about zero. For
unimodal continuous distributions, a skewness value greater than zero means
that there is more weight in the right tail of the distribution. The
function `skewtest` can be used to determine if the skewness value
is close enough to zero, statistically speaking.
Parameters
----------
a : ndarray
Input array.
axis : int or None, optional
Axis along which skewness is calculated. Default is 0.
If None, compute over the whole array `a`.
bias : bool, optional
If False, then the calculations are corrected for statistical bias.
nan_policy : {'propagate', 'raise', 'omit'}, optional
Defines how to handle when input contains nan.
The following options are available (default is 'propagate'):
* 'propagate': returns nan
* 'raise': throws an error
* 'omit': performs the calculations ignoring nan values
Returns
-------
skewness : ndarray
The skewness of values along an axis, returning 0 where all values are
equal.
Notes
-----
The sample skewness is computed as the Fisher-Pearson coefficient
of skewness, i.e.
.. math::
g_1=\frac{m_3}{m_2^{3/2}}
where
.. math::
m_i=\frac{1}{N}\sum_{n=1}^N(x[n]-\bar{x})^i
is the biased sample :math:`i\texttt{th}` central moment, and :math:`\bar{x}` is
the sample mean. If ``bias`` is False, the calculations are
corrected for bias and the value computed is the adjusted
Fisher-Pearson standardized moment coefficient, i.e.
.. math::
G_1=\frac{k_3}{k_2^{3/2}}=
\frac{\sqrt{N(N-1)}}{N-2}\frac{m_3}{m_2^{3/2}}.
References
----------
.. [1] Zwillinger, D. and Kokoska, S. (2000). CRC Standard
Probability and Statistics Tables and Formulae. Chapman & Hall: New
York. 2000.
Section 2.2.24.1
Examples
--------
>>> from scipy.stats import skew
>>> skew([1, 2, 3, 4, 5])
0.0
>>> skew([2, 8, 0, 4, 1, 9, 9, 0])
0.2650554122698573
"""
a, axis = _chk_asarray(a, axis)
n = a.shape[axis]
contains_nan, nan_policy = _contains_nan(a, nan_policy)
if contains_nan and nan_policy == 'omit':
a = ma.masked_invalid(a)
return mstats_basic.skew(a, axis, bias)
m2 = moment(a, 2, axis)
m3 = moment(a, 3, axis)
with np.errstate(all='ignore'):
zero = (m2 <= (np.finfo(m2.dtype).resolution * a.mean(axis))**2)
vals = np.where(zero, 0, m3 / m2**1.5)
if not bias:
can_correct = ~zero & (n > 2)
if can_correct.any():
m2 = np.extract(can_correct, m2)
m3 = np.extract(can_correct, m3)
nval = np.sqrt((n - 1.0) * n) / (n - 2.0) * m3 / m2**1.5
np.place(vals, can_correct, nval)
if vals.ndim == 0:
return vals.item()
return vals
def kurtosis(a, axis=0, fisher=True, bias=True, nan_policy='propagate'):
"""
Compute the kurtosis (Fisher or Pearson) of a dataset.
Kurtosis is the fourth central moment divided by the square of the
variance. If Fisher's definition is used, then 3.0 is subtracted from
the result to give 0.0 for a normal distribution.
If bias is False then the kurtosis is calculated using k statistics to
eliminate bias coming from biased moment estimators
Use `kurtosistest` to see if result is close enough to normal.
Parameters
----------
a : array
Data for which the kurtosis is calculated.
axis : int or None, optional
Axis along which the kurtosis is calculated. Default is 0.
If None, compute over the whole array `a`.
fisher : bool, optional
If True, Fisher's definition is used (normal ==> 0.0). If False,
Pearson's definition is used (normal ==> 3.0).
bias : bool, optional
If False, then the calculations are corrected for statistical bias.
nan_policy : {'propagate', 'raise', 'omit'}, optional
Defines how to handle when input contains nan. 'propagate' returns nan,
'raise' throws an error, 'omit' performs the calculations ignoring nan
values. Default is 'propagate'.
Returns
-------
kurtosis : array
The kurtosis of values along an axis. If all values are equal,
return -3 for Fisher's definition and 0 for Pearson's definition.
References
----------
.. [1] Zwillinger, D. and Kokoska, S. (2000). CRC Standard
Probability and Statistics Tables and Formulae. Chapman & Hall: New
York. 2000.
Examples
--------
In Fisher's definiton, the kurtosis of the normal distribution is zero.
In the following example, the kurtosis is close to zero, because it was
calculated from the dataset, not from the continuous distribution.
>>> from scipy.stats import norm, kurtosis
>>> data = norm.rvs(size=1000, random_state=3)
>>> kurtosis(data)
-0.06928694200380558
The distribution with a higher kurtosis has a heavier tail.
The zero valued kurtosis of the normal distribution in Fisher's definition
can serve as a reference point.
>>> import matplotlib.pyplot as plt
>>> import scipy.stats as stats
>>> from scipy.stats import kurtosis
>>> x = np.linspace(-5, 5, 100)
>>> ax = plt.subplot()
>>> distnames = ['laplace', 'norm', 'uniform']
>>> for distname in distnames:
... if distname == 'uniform':
... dist = getattr(stats, distname)(loc=-2, scale=4)
... else:
... dist = getattr(stats, distname)
... data = dist.rvs(size=1000)
... kur = kurtosis(data, fisher=True)
... y = dist.pdf(x)
... ax.plot(x, y, label="{}, {}".format(distname, round(kur, 3)))
... ax.legend()
The Laplace distribution has a heavier tail than the normal distribution.
The uniform distribution (which has negative kurtosis) has the thinnest
tail.
"""
a, axis = _chk_asarray(a, axis)
contains_nan, nan_policy = _contains_nan(a, nan_policy)
if contains_nan and nan_policy == 'omit':
a = ma.masked_invalid(a)
return mstats_basic.kurtosis(a, axis, fisher, bias)
n = a.shape[axis]
m2 = moment(a, 2, axis)
m4 = moment(a, 4, axis)
with np.errstate(all='ignore'):
zero = (m2 <= (np.finfo(m2.dtype).resolution * a.mean(axis))**2)
vals = np.where(zero, 0, m4 / m2**2.0)
if not bias:
can_correct = ~zero & (n > 3)
if can_correct.any():
m2 = np.extract(can_correct, m2)
m4 = np.extract(can_correct, m4)
nval = 1.0/(n-2)/(n-3) * ((n**2-1.0)*m4/m2**2.0 - 3*(n-1)**2.0)
np.place(vals, can_correct, nval + 3.0)
if vals.ndim == 0:
vals = vals.item() # array scalar
return vals - 3 if fisher else vals
DescribeResult = namedtuple('DescribeResult',
('nobs', 'minmax', 'mean', 'variance', 'skewness',
'kurtosis'))
def describe(a, axis=0, ddof=1, bias=True, nan_policy='propagate'):
"""
Compute several descriptive statistics of the passed array.
Parameters
----------
a : array_like
Input data.
axis : int or None, optional
Axis along which statistics are calculated. Default is 0.
If None, compute over the whole array `a`.
ddof : int, optional
Delta degrees of freedom (only for variance). Default is 1.
bias : bool, optional
If False, then the skewness and kurtosis calculations are corrected
for statistical bias.
nan_policy : {'propagate', 'raise', 'omit'}, optional
Defines how to handle when input contains nan.
The following options are available (default is 'propagate'):
* 'propagate': returns nan
* 'raise': throws an error
* 'omit': performs the calculations ignoring nan values
Returns
-------
nobs : int or ndarray of ints
Number of observations (length of data along `axis`).
When 'omit' is chosen as nan_policy, the length along each axis
slice is counted separately.
minmax: tuple of ndarrays or floats
Minimum and maximum value of `a` along the given axis.
mean : ndarray or float
Arithmetic mean of `a` along the given axis.
variance : ndarray or float
Unbiased variance of `a` along the given axis; denominator is number
of observations minus one.
skewness : ndarray or float
Skewness of `a` along the given axis, based on moment calculations
with denominator equal to the number of observations, i.e. no degrees
of freedom correction.
kurtosis : ndarray or float
Kurtosis (Fisher) of `a` along the given axis. The kurtosis is
normalized so that it is zero for the normal distribution. No
degrees of freedom are used.
See Also
--------
skew, kurtosis
Examples
--------
>>> from scipy import stats
>>> a = np.arange(10)
>>> stats.describe(a)
DescribeResult(nobs=10, minmax=(0, 9), mean=4.5,
variance=9.166666666666666, skewness=0.0,
kurtosis=-1.2242424242424244)
>>> b = [[1, 2], [3, 4]]
>>> stats.describe(b)
DescribeResult(nobs=2, minmax=(array([1, 2]), array([3, 4])),
mean=array([2., 3.]), variance=array([2., 2.]),
skewness=array([0., 0.]), kurtosis=array([-2., -2.]))
"""
a, axis = _chk_asarray(a, axis)
contains_nan, nan_policy = _contains_nan(a, nan_policy)
if contains_nan and nan_policy == 'omit':
a = ma.masked_invalid(a)
return mstats_basic.describe(a, axis, ddof, bias)
if a.size == 0:
raise ValueError("The input must not be empty.")
n = a.shape[axis]
mm = (np.min(a, axis=axis), np.max(a, axis=axis))
m = np.mean(a, axis=axis)
v = np.var(a, axis=axis, ddof=ddof)
sk = skew(a, axis, bias=bias)
kurt = kurtosis(a, axis, bias=bias)
return DescribeResult(n, mm, m, v, sk, kurt)
#####################################
# NORMALITY TESTS #
#####################################
SkewtestResult = namedtuple('SkewtestResult', ('statistic', 'pvalue'))
def skewtest(a, axis=0, nan_policy='propagate'):
"""
Test whether the skew is different from the normal distribution.
This function tests the null hypothesis that the skewness of
the population that the sample was drawn from is the same
as that of a corresponding normal distribution.
Parameters
----------
a : array
The data to be tested.
axis : int or None, optional
Axis along which statistics are calculated. Default is 0.
If None, compute over the whole array `a`.
nan_policy : {'propagate', 'raise', 'omit'}, optional
Defines how to handle when input contains nan.
The following options are available (default is 'propagate'):
* 'propagate': returns nan
* 'raise': throws an error
* 'omit': performs the calculations ignoring nan values
Returns
-------
statistic : float
The computed z-score for this test.
pvalue : float
Two-sided p-value for the hypothesis test.
Notes
-----
The sample size must be at least 8.
References
----------
.. [1] R. B. D'Agostino, A. J. Belanger and R. B. D'Agostino Jr.,
"A suggestion for using powerful and informative tests of
normality", American Statistician 44, pp. 316-321, 1990.
Examples
--------
>>> from scipy.stats import skewtest
>>> skewtest([1, 2, 3, 4, 5, 6, 7, 8])
SkewtestResult(statistic=1.0108048609177787, pvalue=0.3121098361421897)
>>> skewtest([2, 8, 0, 4, 1, 9, 9, 0])
SkewtestResult(statistic=0.44626385374196975, pvalue=0.6554066631275459)
>>> skewtest([1, 2, 3, 4, 5, 6, 7, 8000])
SkewtestResult(statistic=3.571773510360407, pvalue=0.0003545719905823133)
>>> skewtest([100, 100, 100, 100, 100, 100, 100, 101])
SkewtestResult(statistic=3.5717766638478072, pvalue=0.000354567720281634)
"""
a, axis = _chk_asarray(a, axis)
contains_nan, nan_policy = _contains_nan(a, nan_policy)
if contains_nan and nan_policy == 'omit':
a = ma.masked_invalid(a)
return mstats_basic.skewtest(a, axis)
if axis is None:
a = np.ravel(a)
axis = 0
b2 = skew(a, axis)
n = a.shape[axis]
if n < 8:
raise ValueError(
"skewtest is not valid with less than 8 samples; %i samples"
" were given." % int(n))
y = b2 * math.sqrt(((n + 1) * (n + 3)) / (6.0 * (n - 2)))
beta2 = (3.0 * (n**2 + 27*n - 70) * (n+1) * (n+3) /
((n-2.0) * (n+5) * (n+7) * (n+9)))
W2 = -1 + math.sqrt(2 * (beta2 - 1))
delta = 1 / math.sqrt(0.5 * math.log(W2))
alpha = math.sqrt(2.0 / (W2 - 1))
y = np.where(y == 0, 1, y)
Z = delta * np.log(y / alpha + np.sqrt((y / alpha)**2 + 1))
return SkewtestResult(Z, 2 * distributions.norm.sf(np.abs(Z)))
KurtosistestResult = namedtuple('KurtosistestResult', ('statistic', 'pvalue'))
def kurtosistest(a, axis=0, nan_policy='propagate'):
"""
Test whether a dataset has normal kurtosis.
This function tests the null hypothesis that the kurtosis
of the population from which the sample was drawn is that
of the normal distribution: ``kurtosis = 3(n-1)/(n+1)``.
Parameters
----------
a : array
Array of the sample data.
axis : int or None, optional
Axis along which to compute test. Default is 0. If None,
compute over the whole array `a`.
nan_policy : {'propagate', 'raise', 'omit'}, optional
Defines how to handle when input contains nan.
The following options are available (default is 'propagate'):
* 'propagate': returns nan
* 'raise': throws an error
* 'omit': performs the calculations ignoring nan values
Returns
-------
statistic : float
The computed z-score for this test.
pvalue : float
The two-sided p-value for the hypothesis test.
Notes
-----
Valid only for n>20. This function uses the method described in [1]_.
References
----------
.. [1] see e.g. F. J. Anscombe, W. J. Glynn, "Distribution of the kurtosis
statistic b2 for normal samples", Biometrika, vol. 70, pp. 227-234, 1983.
Examples
--------
>>> from scipy.stats import kurtosistest
>>> kurtosistest(list(range(20)))
KurtosistestResult(statistic=-1.7058104152122062, pvalue=0.08804338332528348)
>>> np.random.seed(28041990)
>>> s = np.random.normal(0, 1, 1000)
>>> kurtosistest(s)
KurtosistestResult(statistic=1.2317590987707365, pvalue=0.21803908613450895)
"""
a, axis = _chk_asarray(a, axis)
contains_nan, nan_policy = _contains_nan(a, nan_policy)
if contains_nan and nan_policy == 'omit':
a = ma.masked_invalid(a)
return mstats_basic.kurtosistest(a, axis)
n = a.shape[axis]
if n < 5:
raise ValueError(
"kurtosistest requires at least 5 observations; %i observations"
" were given." % int(n))
if n < 20:
warnings.warn("kurtosistest only valid for n>=20 ... continuing "
"anyway, n=%i" % int(n))
b2 = kurtosis(a, axis, fisher=False)
E = 3.0*(n-1) / (n+1)
varb2 = 24.0*n*(n-2)*(n-3) / ((n+1)*(n+1.)*(n+3)*(n+5)) # [1]_ Eq. 1
x = (b2-E) / np.sqrt(varb2) # [1]_ Eq. 4
# [1]_ Eq. 2:
sqrtbeta1 = 6.0*(n*n-5*n+2)/((n+7)*(n+9)) * np.sqrt((6.0*(n+3)*(n+5)) /
(n*(n-2)*(n-3)))
# [1]_ Eq. 3:
A = 6.0 + 8.0/sqrtbeta1 * (2.0/sqrtbeta1 + np.sqrt(1+4.0/(sqrtbeta1**2)))
term1 = 1 - 2/(9.0*A)
denom = 1 + x*np.sqrt(2/(A-4.0))
term2 = np.sign(denom) * np.where(denom == 0.0, np.nan,
np.power((1-2.0/A)/np.abs(denom), 1/3.0))
if np.any(denom == 0):
msg = "Test statistic not defined in some cases due to division by " \
"zero. Return nan in that case..."
warnings.warn(msg, RuntimeWarning)
Z = (term1 - term2) / np.sqrt(2/(9.0*A)) # [1]_ Eq. 5
if Z.ndim == 0:
Z = Z[()]
# zprob uses upper tail, so Z needs to be positive
return KurtosistestResult(Z, 2 * distributions.norm.sf(np.abs(Z)))
NormaltestResult = namedtuple('NormaltestResult', ('statistic', 'pvalue'))
def normaltest(a, axis=0, nan_policy='propagate'):
"""
Test whether a sample differs from a normal distribution.
This function tests the null hypothesis that a sample comes
from a normal distribution. It is based on D'Agostino and
Pearson's [1]_, [2]_ test that combines skew and kurtosis to
produce an omnibus test of normality.
Parameters
----------
a : array_like
The array containing the sample to be tested.
axis : int or None, optional
Axis along which to compute test. Default is 0. If None,
compute over the whole array `a`.
nan_policy : {'propagate', 'raise', 'omit'}, optional
Defines how to handle when input contains nan.
The following options are available (default is 'propagate'):
* 'propagate': returns nan
* 'raise': throws an error
* 'omit': performs the calculations ignoring nan values
Returns
-------
statistic : float or array
``s^2 + k^2``, where ``s`` is the z-score returned by `skewtest` and
``k`` is the z-score returned by `kurtosistest`.
pvalue : float or array
A 2-sided chi squared probability for the hypothesis test.
References
----------
.. [1] D'Agostino, R. B. (1971), "An omnibus test of normality for
moderate and large sample size", Biometrika, 58, 341-348
.. [2] D'Agostino, R. and Pearson, E. S. (1973), "Tests for departure from
normality", Biometrika, 60, 613-622
Examples
--------
>>> from scipy import stats
>>> pts = 1000
>>> np.random.seed(28041990)
>>> a = np.random.normal(0, 1, size=pts)
>>> b = np.random.normal(2, 1, size=pts)
>>> x = np.concatenate((a, b))
>>> k2, p = stats.normaltest(x)
>>> alpha = 1e-3
>>> print("p = {:g}".format(p))
p = 3.27207e-11
>>> if p < alpha: # null hypothesis: x comes from a normal distribution
... print("The null hypothesis can be rejected")
... else:
... print("The null hypothesis cannot be rejected")
The null hypothesis can be rejected
"""
a, axis = _chk_asarray(a, axis)
contains_nan, nan_policy = _contains_nan(a, nan_policy)
if contains_nan and nan_policy == 'omit':
a = ma.masked_invalid(a)
return mstats_basic.normaltest(a, axis)
s, _ = skewtest(a, axis)
k, _ = kurtosistest(a, axis)
k2 = s*s + k*k
return NormaltestResult(k2, distributions.chi2.sf(k2, 2))
Jarque_beraResult = namedtuple('Jarque_beraResult', ('statistic', 'pvalue'))
def jarque_bera(x):
"""
Perform the Jarque-Bera goodness of fit test on sample data.
The Jarque-Bera test tests whether the sample data has the skewness and
kurtosis matching a normal distribution.
Note that this test only works for a large enough number of data samples
(>2000) as the test statistic asymptotically has a Chi-squared distribution
with 2 degrees of freedom.
Parameters
----------
x : array_like
Observations of a random variable.
Returns
-------
jb_value : float
The test statistic.
p : float
The p-value for the hypothesis test.
References
----------
.. [1] Jarque, C. and Bera, A. (1980) "Efficient tests for normality,
homoscedasticity and serial independence of regression residuals",
6 Econometric Letters 255-259.
Examples
--------
>>> from scipy import stats
>>> np.random.seed(987654321)
>>> x = np.random.normal(0, 1, 100000)
>>> jarque_bera_test = stats.jarque_bera(x)
>>> jarque_bera_test
Jarque_beraResult(statistic=4.716570798957913, pvalue=0.0945822550304295)
>>> jarque_bera_test.statistic
4.716570798957913
>>> jarque_bera_test.pvalue
0.0945822550304295
"""
x = np.asarray(x)
n = x.size
if n == 0:
raise ValueError('At least one observation is required.')
mu = x.mean()
diffx = x - mu
skewness = (1 / n * np.sum(diffx**3)) / (1 / n * np.sum(diffx**2))**(3 / 2.)
kurtosis = (1 / n * np.sum(diffx**4)) / (1 / n * np.sum(diffx**2))**2
jb_value = n / 6 * (skewness**2 + (kurtosis - 3)**2 / 4)
p = 1 - distributions.chi2.cdf(jb_value, 2)
return Jarque_beraResult(jb_value, p)
#####################################
# FREQUENCY FUNCTIONS #
#####################################
# deindent to work around numpy/gh-16202
@np.deprecate(
message="`itemfreq` is deprecated and will be removed in a "
"future version. Use instead `np.unique(..., return_counts=True)`")
def itemfreq(a):
"""
Return a 2-D array of item frequencies.
Parameters
----------
a : (N,) array_like
Input array.
Returns
-------
itemfreq : (K, 2) ndarray
A 2-D frequency table. Column 1 contains sorted, unique values from
`a`, column 2 contains their respective counts.
Examples
--------
>>> from scipy import stats
>>> a = np.array([1, 1, 5, 0, 1, 2, 2, 0, 1, 4])
>>> stats.itemfreq(a)
array([[ 0., 2.],
[ 1., 4.],
[ 2., 2.],
[ 4., 1.],
[ 5., 1.]])
>>> np.bincount(a)
array([2, 4, 2, 0, 1, 1])
>>> stats.itemfreq(a/10.)
array([[ 0. , 2. ],
[ 0.1, 4. ],
[ 0.2, 2. ],
[ 0.4, 1. ],
[ 0.5, 1. ]])
"""
items, inv = np.unique(a, return_inverse=True)
freq = np.bincount(inv)
return np.array([items, freq]).T
def scoreatpercentile(a, per, limit=(), interpolation_method='fraction',
axis=None):
"""
Calculate the score at a given percentile of the input sequence.
For example, the score at `per=50` is the median. If the desired quantile
lies between two data points, we interpolate between them, according to
the value of `interpolation`. If the parameter `limit` is provided, it
should be a tuple (lower, upper) of two values.
Parameters
----------
a : array_like
A 1-D array of values from which to extract score.
per : array_like
Percentile(s) at which to extract score. Values should be in range
[0,100].
limit : tuple, optional
Tuple of two scalars, the lower and upper limits within which to
compute the percentile. Values of `a` outside
this (closed) interval will be ignored.
interpolation_method : {'fraction', 'lower', 'higher'}, optional
Specifies the interpolation method to use,
when the desired quantile lies between two data points `i` and `j`
The following options are available (default is 'fraction'):
* 'fraction': ``i + (j - i) * fraction`` where ``fraction`` is the
fractional part of the index surrounded by ``i`` and ``j``
* 'lower': ``i``
* 'higher': ``j``
axis : int, optional
Axis along which the percentiles are computed. Default is None. If
None, compute over the whole array `a`.
Returns
-------
score : float or ndarray
Score at percentile(s).
See Also
--------
percentileofscore, numpy.percentile
Notes
-----
This function will become obsolete in the future.
For NumPy 1.9 and higher, `numpy.percentile` provides all the functionality
that `scoreatpercentile` provides. And it's significantly faster.
Therefore it's recommended to use `numpy.percentile` for users that have
numpy >= 1.9.
Examples
--------
>>> from scipy import stats
>>> a = np.arange(100)
>>> stats.scoreatpercentile(a, 50)
49.5
"""
# adapted from NumPy's percentile function. When we require numpy >= 1.8,
# the implementation of this function can be replaced by np.percentile.
a = np.asarray(a)
if a.size == 0:
# empty array, return nan(s) with shape matching `per`
if np.isscalar(per):
return np.nan
else:
return np.full(np.asarray(per).shape, np.nan, dtype=np.float64)
if limit:
a = a[(limit[0] <= a) & (a <= limit[1])]
sorted_ = np.sort(a, axis=axis)
if axis is None:
axis = 0
return _compute_qth_percentile(sorted_, per, interpolation_method, axis)
# handle sequence of per's without calling sort multiple times
def _compute_qth_percentile(sorted_, per, interpolation_method, axis):
if not np.isscalar(per):
score = [_compute_qth_percentile(sorted_, i,
interpolation_method, axis)
for i in per]
return np.array(score)
if not (0 <= per <= 100):
raise ValueError("percentile must be in the range [0, 100]")
indexer = [slice(None)] * sorted_.ndim
idx = per / 100. * (sorted_.shape[axis] - 1)
if int(idx) != idx:
# round fractional indices according to interpolation method
if interpolation_method == 'lower':
idx = int(np.floor(idx))
elif interpolation_method == 'higher':
idx = int(np.ceil(idx))
elif interpolation_method == 'fraction':
pass # keep idx as fraction and interpolate
else:
raise ValueError("interpolation_method can only be 'fraction', "
"'lower' or 'higher'")
i = int(idx)
if i == idx:
indexer[axis] = slice(i, i + 1)
weights = array(1)
sumval = 1.0
else:
indexer[axis] = slice(i, i + 2)
j = i + 1
weights = array([(j - idx), (idx - i)], float)
wshape = [1] * sorted_.ndim
wshape[axis] = 2
weights.shape = wshape
sumval = weights.sum()
# Use np.add.reduce (== np.sum but a little faster) to coerce data type
return np.add.reduce(sorted_[tuple(indexer)] * weights, axis=axis) / sumval
def percentileofscore(a, score, kind='rank'):
"""
Compute the percentile rank of a score relative to a list of scores.
A `percentileofscore` of, for example, 80% means that 80% of the
scores in `a` are below the given score. In the case of gaps or
ties, the exact definition depends on the optional keyword, `kind`.
Parameters
----------
a : array_like
Array of scores to which `score` is compared.
score : int or float
Score that is compared to the elements in `a`.
kind : {'rank', 'weak', 'strict', 'mean'}, optional
Specifies the interpretation of the resulting score.
The following options are available (default is 'rank'):
* 'rank': Average percentage ranking of score. In case of multiple
matches, average the percentage rankings of all matching scores.
* 'weak': This kind corresponds to the definition of a cumulative
distribution function. A percentileofscore of 80% means that 80%
of values are less than or equal to the provided score.
* 'strict': Similar to "weak", except that only values that are
strictly less than the given score are counted.
* 'mean': The average of the "weak" and "strict" scores, often used
in testing. See https://en.wikipedia.org/wiki/Percentile_rank
Returns
-------
pcos : float
Percentile-position of score (0-100) relative to `a`.
See Also
--------
numpy.percentile
Examples
--------
Three-quarters of the given values lie below a given score:
>>> from scipy import stats
>>> stats.percentileofscore([1, 2, 3, 4], 3)
75.0
With multiple matches, note how the scores of the two matches, 0.6
and 0.8 respectively, are averaged:
>>> stats.percentileofscore([1, 2, 3, 3, 4], 3)
70.0
Only 2/5 values are strictly less than 3:
>>> stats.percentileofscore([1, 2, 3, 3, 4], 3, kind='strict')
40.0
But 4/5 values are less than or equal to 3:
>>> stats.percentileofscore([1, 2, 3, 3, 4], 3, kind='weak')
80.0
The average between the weak and the strict scores is:
>>> stats.percentileofscore([1, 2, 3, 3, 4], 3, kind='mean')
60.0
"""
if np.isnan(score):
return np.nan
a = np.asarray(a)
n = len(a)
if n == 0:
return 100.0
if kind == 'rank':
left = np.count_nonzero(a < score)
right = np.count_nonzero(a <= score)
pct = (right + left + (1 if right > left else 0)) * 50.0/n
return pct
elif kind == 'strict':
return np.count_nonzero(a < score) / n * 100
elif kind == 'weak':
return np.count_nonzero(a <= score) / n * 100
elif kind == 'mean':
pct = (np.count_nonzero(a < score) + np.count_nonzero(a <= score)) / n * 50
return pct
else:
raise ValueError("kind can only be 'rank', 'strict', 'weak' or 'mean'")
HistogramResult = namedtuple('HistogramResult',
('count', 'lowerlimit', 'binsize', 'extrapoints'))
def _histogram(a, numbins=10, defaultlimits=None, weights=None, printextras=False):
"""
Create a histogram.
Separate the range into several bins and return the number of instances
in each bin.
Parameters
----------
a : array_like
Array of scores which will be put into bins.
numbins : int, optional
The number of bins to use for the histogram. Default is 10.
defaultlimits : tuple (lower, upper), optional
The lower and upper values for the range of the histogram.
If no value is given, a range slightly larger than the range of the
values in a is used. Specifically ``(a.min() - s, a.max() + s)``,
where ``s = (1/2)(a.max() - a.min()) / (numbins - 1)``.
weights : array_like, optional
The weights for each value in `a`. Default is None, which gives each
value a weight of 1.0
printextras : bool, optional
If True, if there are extra points (i.e. the points that fall outside
the bin limits) a warning is raised saying how many of those points
there are. Default is False.
Returns
-------
count : ndarray
Number of points (or sum of weights) in each bin.
lowerlimit : float
Lowest value of histogram, the lower limit of the first bin.
binsize : float
The size of the bins (all bins have the same size).
extrapoints : int
The number of points outside the range of the histogram.
See Also
--------
numpy.histogram
Notes
-----
This histogram is based on numpy's histogram but has a larger range by
default if default limits is not set.
"""
a = np.ravel(a)
if defaultlimits is None:
if a.size == 0:
# handle empty arrays. Undetermined range, so use 0-1.
defaultlimits = (0, 1)
else:
# no range given, so use values in `a`
data_min = a.min()
data_max = a.max()
# Have bins extend past min and max values slightly
s = (data_max - data_min) / (2. * (numbins - 1.))
defaultlimits = (data_min - s, data_max + s)
# use numpy's histogram method to compute bins
hist, bin_edges = np.histogram(a, bins=numbins, range=defaultlimits,
weights=weights)
# hist are not always floats, convert to keep with old output
hist = np.array(hist, dtype=float)
# fixed width for bins is assumed, as numpy's histogram gives
# fixed width bins for int values for 'bins'
binsize = bin_edges[1] - bin_edges[0]
# calculate number of extra points
extrapoints = len([v for v in a
if defaultlimits[0] > v or v > defaultlimits[1]])
if extrapoints > 0 and printextras:
warnings.warn("Points outside given histogram range = %s"
% extrapoints)
return HistogramResult(hist, defaultlimits[0], binsize, extrapoints)
CumfreqResult = namedtuple('CumfreqResult',
('cumcount', 'lowerlimit', 'binsize',
'extrapoints'))
def cumfreq(a, numbins=10, defaultreallimits=None, weights=None):
"""
Return a cumulative frequency histogram, using the histogram function.
A cumulative histogram is a mapping that counts the cumulative number of
observations in all of the bins up to the specified bin.
Parameters
----------
a : array_like
Input array.
numbins : int, optional
The number of bins to use for the histogram. Default is 10.
defaultreallimits : tuple (lower, upper), optional
The lower and upper values for the range of the histogram.
If no value is given, a range slightly larger than the range of the
values in `a` is used. Specifically ``(a.min() - s, a.max() + s)``,
where ``s = (1/2)(a.max() - a.min()) / (numbins - 1)``.
weights : array_like, optional
The weights for each value in `a`. Default is None, which gives each
value a weight of 1.0
Returns
-------
cumcount : ndarray
Binned values of cumulative frequency.
lowerlimit : float
Lower real limit
binsize : float
Width of each bin.
extrapoints : int
Extra points.
Examples
--------
>>> import matplotlib.pyplot as plt
>>> from scipy import stats
>>> x = [1, 4, 2, 1, 3, 1]
>>> res = stats.cumfreq(x, numbins=4, defaultreallimits=(1.5, 5))
>>> res.cumcount
array([ 1., 2., 3., 3.])
>>> res.extrapoints
3
Create a normal distribution with 1000 random values
>>> rng = np.random.RandomState(seed=12345)
>>> samples = stats.norm.rvs(size=1000, random_state=rng)
Calculate cumulative frequencies
>>> res = stats.cumfreq(samples, numbins=25)
Calculate space of values for x
>>> x = res.lowerlimit + np.linspace(0, res.binsize*res.cumcount.size,
... res.cumcount.size)
Plot histogram and cumulative histogram
>>> fig = plt.figure(figsize=(10, 4))
>>> ax1 = fig.add_subplot(1, 2, 1)
>>> ax2 = fig.add_subplot(1, 2, 2)
>>> ax1.hist(samples, bins=25)
>>> ax1.set_title('Histogram')
>>> ax2.bar(x, res.cumcount, width=res.binsize)
>>> ax2.set_title('Cumulative histogram')
>>> ax2.set_xlim([x.min(), x.max()])
>>> plt.show()
"""
h, l, b, e = _histogram(a, numbins, defaultreallimits, weights=weights)
cumhist = np.cumsum(h * 1, axis=0)
return CumfreqResult(cumhist, l, b, e)
RelfreqResult = namedtuple('RelfreqResult',
('frequency', 'lowerlimit', 'binsize',
'extrapoints'))
def relfreq(a, numbins=10, defaultreallimits=None, weights=None):
"""
Return a relative frequency histogram, using the histogram function.
A relative frequency histogram is a mapping of the number of
observations in each of the bins relative to the total of observations.
Parameters
----------
a : array_like
Input array.
numbins : int, optional
The number of bins to use for the histogram. Default is 10.
defaultreallimits : tuple (lower, upper), optional
The lower and upper values for the range of the histogram.
If no value is given, a range slightly larger than the range of the
values in a is used. Specifically ``(a.min() - s, a.max() + s)``,
where ``s = (1/2)(a.max() - a.min()) / (numbins - 1)``.
weights : array_like, optional
The weights for each value in `a`. Default is None, which gives each
value a weight of 1.0
Returns
-------
frequency : ndarray
Binned values of relative frequency.
lowerlimit : float
Lower real limit.
binsize : float
Width of each bin.
extrapoints : int
Extra points.
Examples
--------
>>> import matplotlib.pyplot as plt
>>> from scipy import stats
>>> a = np.array([2, 4, 1, 2, 3, 2])
>>> res = stats.relfreq(a, numbins=4)
>>> res.frequency
array([ 0.16666667, 0.5 , 0.16666667, 0.16666667])
>>> np.sum(res.frequency) # relative frequencies should add up to 1
1.0
Create a normal distribution with 1000 random values
>>> rng = np.random.RandomState(seed=12345)
>>> samples = stats.norm.rvs(size=1000, random_state=rng)
Calculate relative frequencies
>>> res = stats.relfreq(samples, numbins=25)
Calculate space of values for x
>>> x = res.lowerlimit + np.linspace(0, res.binsize*res.frequency.size,
... res.frequency.size)
Plot relative frequency histogram
>>> fig = plt.figure(figsize=(5, 4))
>>> ax = fig.add_subplot(1, 1, 1)
>>> ax.bar(x, res.frequency, width=res.binsize)
>>> ax.set_title('Relative frequency histogram')
>>> ax.set_xlim([x.min(), x.max()])
>>> plt.show()
"""
a = np.asanyarray(a)
h, l, b, e = _histogram(a, numbins, defaultreallimits, weights=weights)
h = h / a.shape[0]
return RelfreqResult(h, l, b, e)
#####################################
# VARIABILITY FUNCTIONS #
#####################################
def obrientransform(*args):
"""
Compute the O'Brien transform on input data (any number of arrays).
Used to test for homogeneity of variance prior to running one-way stats.
Each array in ``*args`` is one level of a factor.
If `f_oneway` is run on the transformed data and found significant,
the variances are unequal. From Maxwell and Delaney [1]_, p.112.
Parameters
----------
args : tuple of array_like
Any number of arrays.
Returns
-------
obrientransform : ndarray
Transformed data for use in an ANOVA. The first dimension
of the result corresponds to the sequence of transformed
arrays. If the arrays given are all 1-D of the same length,
the return value is a 2-D array; otherwise it is a 1-D array
of type object, with each element being an ndarray.
References
----------
.. [1] S. E. Maxwell and H. D. Delaney, "Designing Experiments and
Analyzing Data: A Model Comparison Perspective", Wadsworth, 1990.
Examples
--------
We'll test the following data sets for differences in their variance.
>>> x = [10, 11, 13, 9, 7, 12, 12, 9, 10]
>>> y = [13, 21, 5, 10, 8, 14, 10, 12, 7, 15]
Apply the O'Brien transform to the data.
>>> from scipy.stats import obrientransform
>>> tx, ty = obrientransform(x, y)
Use `scipy.stats.f_oneway` to apply a one-way ANOVA test to the
transformed data.
>>> from scipy.stats import f_oneway
>>> F, p = f_oneway(tx, ty)
>>> p
0.1314139477040335
If we require that ``p < 0.05`` for significance, we cannot conclude
that the variances are different.
"""
TINY = np.sqrt(np.finfo(float).eps)
# `arrays` will hold the transformed arguments.
arrays = []
sLast = None
for arg in args:
a = np.asarray(arg)
n = len(a)
mu = np.mean(a)
sq = (a - mu)**2
sumsq = sq.sum()
# The O'Brien transform.
t = ((n - 1.5) * n * sq - 0.5 * sumsq) / ((n - 1) * (n - 2))
# Check that the mean of the transformed data is equal to the
# original variance.
var = sumsq / (n - 1)
if abs(var - np.mean(t)) > TINY:
raise ValueError('Lack of convergence in obrientransform.')
arrays.append(t)
sLast = a.shape
if sLast:
for arr in arrays[:-1]:
if sLast != arr.shape:
return np.array(arrays, dtype=object)
return np.array(arrays)
def sem(a, axis=0, ddof=1, nan_policy='propagate'):
"""
Compute standard error of the mean.
Calculate the standard error of the mean (or standard error of
measurement) of the values in the input array.
Parameters
----------
a : array_like
An array containing the values for which the standard error is
returned.
axis : int or None, optional
Axis along which to operate. Default is 0. If None, compute over
the whole array `a`.
ddof : int, optional
Delta degrees-of-freedom. How many degrees of freedom to adjust
for bias in limited samples relative to the population estimate
of variance. Defaults to 1.
nan_policy : {'propagate', 'raise', 'omit'}, optional
Defines how to handle when input contains nan.
The following options are available (default is 'propagate'):
* 'propagate': returns nan
* 'raise': throws an error
* 'omit': performs the calculations ignoring nan values
Returns
-------
s : ndarray or float
The standard error of the mean in the sample(s), along the input axis.
Notes
-----
The default value for `ddof` is different to the default (0) used by other
ddof containing routines, such as np.std and np.nanstd.
Examples
--------
Find standard error along the first axis:
>>> from scipy import stats
>>> a = np.arange(20).reshape(5,4)
>>> stats.sem(a)
array([ 2.8284, 2.8284, 2.8284, 2.8284])
Find standard error across the whole array, using n degrees of freedom:
>>> stats.sem(a, axis=None, ddof=0)
1.2893796958227628
"""
a, axis = _chk_asarray(a, axis)
contains_nan, nan_policy = _contains_nan(a, nan_policy)
if contains_nan and nan_policy == 'omit':
a = ma.masked_invalid(a)
return mstats_basic.sem(a, axis, ddof)
n = a.shape[axis]
s = np.std(a, axis=axis, ddof=ddof) / np.sqrt(n)
return s
def _isconst(x):
"""
Check if all values in x are the same. nans are ignored.
x must be a 1d array.
The return value is a 1d array with length 1, so it can be used
in np.apply_along_axis.
"""
y = x[~np.isnan(x)]
if y.size == 0:
return np.array([True])
else:
return (y[0] == y).all(keepdims=True)
def _quiet_nanmean(x):
"""
Compute nanmean for the 1d array x, but quietly return nan if x is all nan.
The return value is a 1d array with length 1, so it can be used
in np.apply_along_axis.
"""
y = x[~np.isnan(x)]
if y.size == 0:
return np.array([np.nan])
else:
return np.mean(y, keepdims=True)
def _quiet_nanstd(x, ddof=0):
"""
Compute nanstd for the 1d array x, but quietly return nan if x is all nan.
The return value is a 1d array with length 1, so it can be used
in np.apply_along_axis.
"""
y = x[~np.isnan(x)]
if y.size == 0:
return np.array([np.nan])
else:
return np.std(y, keepdims=True, ddof=ddof)
def zscore(a, axis=0, ddof=0, nan_policy='propagate'):
"""
Compute the z score.
Compute the z score of each value in the sample, relative to the
sample mean and standard deviation.
Parameters
----------
a : array_like
An array like object containing the sample data.
axis : int or None, optional
Axis along which to operate. Default is 0. If None, compute over
the whole array `a`.
ddof : int, optional
Degrees of freedom correction in the calculation of the
standard deviation. Default is 0.
nan_policy : {'propagate', 'raise', 'omit'}, optional
Defines how to handle when input contains nan. 'propagate' returns nan,
'raise' throws an error, 'omit' performs the calculations ignoring nan
values. Default is 'propagate'. Note that when the value is 'omit',
nans in the input also propagate to the output, but they do not affect
the z-scores computed for the non-nan values.
Returns
-------
zscore : array_like
The z-scores, standardized by mean and standard deviation of
input array `a`.
Notes
-----
This function preserves ndarray subclasses, and works also with
matrices and masked arrays (it uses `asanyarray` instead of
`asarray` for parameters).
Examples
--------
>>> a = np.array([ 0.7972, 0.0767, 0.4383, 0.7866, 0.8091,
... 0.1954, 0.6307, 0.6599, 0.1065, 0.0508])
>>> from scipy import stats
>>> stats.zscore(a)
array([ 1.1273, -1.247 , -0.0552, 1.0923, 1.1664, -0.8559, 0.5786,
0.6748, -1.1488, -1.3324])
Computing along a specified axis, using n-1 degrees of freedom
(``ddof=1``) to calculate the standard deviation:
>>> b = np.array([[ 0.3148, 0.0478, 0.6243, 0.4608],
... [ 0.7149, 0.0775, 0.6072, 0.9656],
... [ 0.6341, 0.1403, 0.9759, 0.4064],
... [ 0.5918, 0.6948, 0.904 , 0.3721],
... [ 0.0921, 0.2481, 0.1188, 0.1366]])
>>> stats.zscore(b, axis=1, ddof=1)
array([[-0.19264823, -1.28415119, 1.07259584, 0.40420358],
[ 0.33048416, -1.37380874, 0.04251374, 1.00081084],
[ 0.26796377, -1.12598418, 1.23283094, -0.37481053],
[-0.22095197, 0.24468594, 1.19042819, -1.21416216],
[-0.82780366, 1.4457416 , -0.43867764, -0.1792603 ]])
An example with `nan_policy='omit'`:
>>> x = np.array([[25.11, 30.10, np.nan, 32.02, 43.15],
... [14.95, 16.06, 121.25, 94.35, 29.81]])
>>> stats.zscore(x, axis=1, nan_policy='omit')
array([[-1.13490897, -0.37830299, nan, -0.08718406, 1.60039602],
[-0.91611681, -0.89090508, 1.4983032 , 0.88731639, -0.5785977 ]])
"""
return zmap(a, a, axis=axis, ddof=ddof, nan_policy=nan_policy)
def zmap(scores, compare, axis=0, ddof=0, nan_policy='propagate'):
"""
Calculate the relative z-scores.
Return an array of z-scores, i.e., scores that are standardized to
zero mean and unit variance, where mean and variance are calculated
from the comparison array.
Parameters
----------
scores : array_like
The input for which z-scores are calculated.
compare : array_like
The input from which the mean and standard deviation of the
normalization are taken; assumed to have the same dimension as
`scores`.
axis : int or None, optional
Axis over which mean and variance of `compare` are calculated.
Default is 0. If None, compute over the whole array `scores`.
ddof : int, optional
Degrees of freedom correction in the calculation of the
standard deviation. Default is 0.
nan_policy : {'propagate', 'raise', 'omit'}, optional
Defines how to handle the occurrence of nans in `compare`.
'propagate' returns nan, 'raise' raises an exception, 'omit'
performs the calculations ignoring nan values. Default is
'propagate'. Note that when the value is 'omit', nans in `scores`
also propagate to the output, but they do not affect the z-scores
computed for the non-nan values.
Returns
-------
zscore : array_like
Z-scores, in the same shape as `scores`.
Notes
-----
This function preserves ndarray subclasses, and works also with
matrices and masked arrays (it uses `asanyarray` instead of
`asarray` for parameters).
Examples
--------
>>> from scipy.stats import zmap
>>> a = [0.5, 2.0, 2.5, 3]
>>> b = [0, 1, 2, 3, 4]
>>> zmap(a, b)
array([-1.06066017, 0. , 0.35355339, 0.70710678])
"""
a = np.asanyarray(compare)
if a.size == 0:
return np.empty(a.shape)
contains_nan, nan_policy = _contains_nan(a, nan_policy)
if contains_nan and nan_policy == 'omit':
if axis is None:
mn = _quiet_nanmean(a.ravel())
std = _quiet_nanstd(a.ravel(), ddof=ddof)
isconst = _isconst(a.ravel())
else:
mn = np.apply_along_axis(_quiet_nanmean, axis, a)
std = np.apply_along_axis(_quiet_nanstd, axis, a, ddof=ddof)
isconst = np.apply_along_axis(_isconst, axis, a)
else:
mn = a.mean(axis=axis, keepdims=True)
std = a.std(axis=axis, ddof=ddof, keepdims=True)
if axis is None:
isconst = (a.item(0) == a).all()
else:
isconst = (_first(a, axis) == a).all(axis=axis, keepdims=True)
# Set std deviations that are 0 to 1 to avoid division by 0.
std[isconst] = 1.0
z = (scores - mn) / std
# Set the outputs associated with a constant input to nan.
z[np.broadcast_to(isconst, z.shape)] = np.nan
return z
def gstd(a, axis=0, ddof=1):
"""
Calculate the geometric standard deviation of an array.
The geometric standard deviation describes the spread of a set of numbers
where the geometric mean is preferred. It is a multiplicative factor, and
so a dimensionless quantity.
It is defined as the exponent of the standard deviation of ``log(a)``.
Mathematically the population geometric standard deviation can be
evaluated as::
gstd = exp(std(log(a)))
.. versionadded:: 1.3.0
Parameters
----------
a : array_like
An array like object containing the sample data.
axis : int, tuple or None, optional
Axis along which to operate. Default is 0. If None, compute over
the whole array `a`.
ddof : int, optional
Degree of freedom correction in the calculation of the
geometric standard deviation. Default is 1.
Returns
-------
ndarray or float
An array of the geometric standard deviation. If `axis` is None or `a`
is a 1d array a float is returned.
Notes
-----
As the calculation requires the use of logarithms the geometric standard
deviation only supports strictly positive values. Any non-positive or
infinite values will raise a `ValueError`.
The geometric standard deviation is sometimes confused with the exponent of
the standard deviation, ``exp(std(a))``. Instead the geometric standard
deviation is ``exp(std(log(a)))``.
The default value for `ddof` is different to the default value (0) used
by other ddof containing functions, such as ``np.std`` and ``np.nanstd``.
Examples
--------
Find the geometric standard deviation of a log-normally distributed sample.
Note that the standard deviation of the distribution is one, on a
log scale this evaluates to approximately ``exp(1)``.
>>> from scipy.stats import gstd
>>> np.random.seed(123)
>>> sample = np.random.lognormal(mean=0, sigma=1, size=1000)
>>> gstd(sample)
2.7217860664589946
Compute the geometric standard deviation of a multidimensional array and
of a given axis.
>>> a = np.arange(1, 25).reshape(2, 3, 4)
>>> gstd(a, axis=None)
2.2944076136018947
>>> gstd(a, axis=2)
array([[1.82424757, 1.22436866, 1.13183117],
[1.09348306, 1.07244798, 1.05914985]])
>>> gstd(a, axis=(1,2))
array([2.12939215, 1.22120169])
The geometric standard deviation further handles masked arrays.
>>> a = np.arange(1, 25).reshape(2, 3, 4)
>>> ma = np.ma.masked_where(a > 16, a)
>>> ma
masked_array(
data=[[[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]],
[[13, 14, 15, 16],
[--, --, --, --],
[--, --, --, --]]],
mask=[[[False, False, False, False],
[False, False, False, False],
[False, False, False, False]],
[[False, False, False, False],
[ True, True, True, True],
[ True, True, True, True]]],
fill_value=999999)
>>> gstd(ma, axis=2)
masked_array(
data=[[1.8242475707663655, 1.2243686572447428, 1.1318311657788478],
[1.0934830582350938, --, --]],
mask=[[False, False, False],
[False, True, True]],
fill_value=999999)
"""
a = np.asanyarray(a)
log = ma.log if isinstance(a, ma.MaskedArray) else np.log
try:
with warnings.catch_warnings():
warnings.simplefilter("error", RuntimeWarning)
return np.exp(np.std(log(a), axis=axis, ddof=ddof))
except RuntimeWarning as w:
if np.isinf(a).any():
raise ValueError(
'Infinite value encountered. The geometric standard deviation '
'is defined for strictly positive values only.'
) from w
a_nan = np.isnan(a)
a_nan_any = a_nan.any()
# exclude NaN's from negativity check, but
# avoid expensive masking for arrays with no NaN
if ((a_nan_any and np.less_equal(np.nanmin(a), 0)) or
(not a_nan_any and np.less_equal(a, 0).any())):
raise ValueError(
'Non positive value encountered. The geometric standard '
'deviation is defined for strictly positive values only.'
) from w
elif 'Degrees of freedom <= 0 for slice' == str(w):
raise ValueError(w) from w
else:
# Remaining warnings don't need to be exceptions.
return np.exp(np.std(log(a, where=~a_nan), axis=axis, ddof=ddof))
except TypeError as e:
raise ValueError(
'Invalid array input. The inputs could not be '
'safely coerced to any supported types') from e
# Private dictionary initialized only once at module level
# See https://en.wikipedia.org/wiki/Robust_measures_of_scale
_scale_conversions = {'raw': 1.0,
'normal': special.erfinv(0.5) * 2.0 * math.sqrt(2.0)}
def iqr(x, axis=None, rng=(25, 75), scale=1.0, nan_policy='propagate',
interpolation='linear', keepdims=False):
r"""
Compute the interquartile range of the data along the specified axis.
The interquartile range (IQR) is the difference between the 75th and
25th percentile of the data. It is a measure of the dispersion
similar to standard deviation or variance, but is much more robust
against outliers [2]_.
The ``rng`` parameter allows this function to compute other
percentile ranges than the actual IQR. For example, setting
``rng=(0, 100)`` is equivalent to `numpy.ptp`.
The IQR of an empty array is `np.nan`.
.. versionadded:: 0.18.0
Parameters
----------
x : array_like
Input array or object that can be converted to an array.
axis : int or sequence of int, optional
Axis along which the range is computed. The default is to
compute the IQR for the entire array.
rng : Two-element sequence containing floats in range of [0,100] optional
Percentiles over which to compute the range. Each must be
between 0 and 100, inclusive. The default is the true IQR:
`(25, 75)`. The order of the elements is not important.
scale : scalar or str, optional
The numerical value of scale will be divided out of the final
result. The following string values are recognized:
* 'raw' : No scaling, just return the raw IQR.
**Deprecated!** Use `scale=1` instead.
* 'normal' : Scale by
:math:`2 \sqrt{2} erf^{-1}(\frac{1}{2}) \approx 1.349`.
The default is 1.0. The use of scale='raw' is deprecated.
Array-like scale is also allowed, as long
as it broadcasts correctly to the output such that
``out / scale`` is a valid operation. The output dimensions
depend on the input array, `x`, the `axis` argument, and the
`keepdims` flag.
nan_policy : {'propagate', 'raise', 'omit'}, optional
Defines how to handle when input contains nan.
The following options are available (default is 'propagate'):
* 'propagate': returns nan
* 'raise': throws an error
* 'omit': performs the calculations ignoring nan values
interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'}, optional
Specifies the interpolation method to use when the percentile
boundaries lie between two data points `i` and `j`.
The following options are available (default is 'linear'):
* 'linear': `i + (j - i) * fraction`, where `fraction` is the
fractional part of the index surrounded by `i` and `j`.
* 'lower': `i`.
* 'higher': `j`.
* 'nearest': `i` or `j` whichever is nearest.
* 'midpoint': `(i + j) / 2`.
keepdims : bool, optional
If this is set to `True`, the reduced axes are left in the
result as dimensions with size one. With this option, the result
will broadcast correctly against the original array `x`.
Returns
-------
iqr : scalar or ndarray
If ``axis=None``, a scalar is returned. If the input contains
integers or floats of smaller precision than ``np.float64``, then the
output data-type is ``np.float64``. Otherwise, the output data-type is
the same as that of the input.
See Also
--------
numpy.std, numpy.var
Notes
-----
This function is heavily dependent on the version of `numpy` that is
installed. Versions greater than 1.11.0b3 are highly recommended, as they
include a number of enhancements and fixes to `numpy.percentile` and
`numpy.nanpercentile` that affect the operation of this function. The
following modifications apply:
Below 1.10.0 : `nan_policy` is poorly defined.
The default behavior of `numpy.percentile` is used for 'propagate'. This
is a hybrid of 'omit' and 'propagate' that mostly yields a skewed
version of 'omit' since NaNs are sorted to the end of the data. A
warning is raised if there are NaNs in the data.
Below 1.9.0: `numpy.nanpercentile` does not exist.
This means that `numpy.percentile` is used regardless of `nan_policy`
and a warning is issued. See previous item for a description of the
behavior.
Below 1.9.0: `keepdims` and `interpolation` are not supported.
The keywords get ignored with a warning if supplied with non-default
values. However, multiple axes are still supported.
References
----------
.. [1] "Interquartile range" https://en.wikipedia.org/wiki/Interquartile_range
.. [2] "Robust measures of scale" https://en.wikipedia.org/wiki/Robust_measures_of_scale
.. [3] "Quantile" https://en.wikipedia.org/wiki/Quantile
Examples
--------
>>> from scipy.stats import iqr
>>> x = np.array([[10, 7, 4], [3, 2, 1]])
>>> x
array([[10, 7, 4],
[ 3, 2, 1]])
>>> iqr(x)
4.0
>>> iqr(x, axis=0)
array([ 3.5, 2.5, 1.5])
>>> iqr(x, axis=1)
array([ 3., 1.])
>>> iqr(x, axis=1, keepdims=True)
array([[ 3.],
[ 1.]])
"""
x = asarray(x)
# This check prevents percentile from raising an error later. Also, it is
# consistent with `np.var` and `np.std`.
if not x.size:
return np.nan
# An error may be raised here, so fail-fast, before doing lengthy
# computations, even though `scale` is not used until later
if isinstance(scale, str):
scale_key = scale.lower()
if scale_key not in _scale_conversions:
raise ValueError("{0} not a valid scale for `iqr`".format(scale))
if scale_key == 'raw':
warnings.warn(
"use of scale='raw' is deprecated, use scale=1.0 instead",
np.VisibleDeprecationWarning
)
scale = _scale_conversions[scale_key]
# Select the percentile function to use based on nans and policy
contains_nan, nan_policy = _contains_nan(x, nan_policy)
if contains_nan and nan_policy == 'omit':
percentile_func = np.nanpercentile
else:
percentile_func = np.percentile
if len(rng) != 2:
raise TypeError("quantile range must be two element sequence")
if np.isnan(rng).any():
raise ValueError("range must not contain NaNs")
rng = sorted(rng)
pct = percentile_func(x, rng, axis=axis, interpolation=interpolation,
keepdims=keepdims)
out = np.subtract(pct[1], pct[0])
if scale != 1.0:
out /= scale
return out
def _mad_1d(x, center, nan_policy):
# Median absolute deviation for 1-d array x.
# This is a helper function for `median_abs_deviation`; it assumes its
# arguments have been validated already. In particular, x must be a
# 1-d numpy array, center must be callable, and if nan_policy is not
# 'propagate', it is assumed to be 'omit', because 'raise' is handled
# in `median_abs_deviation`.
# No warning is generated if x is empty or all nan.
isnan = np.isnan(x)
if isnan.any():
if nan_policy == 'propagate':
return np.nan
x = x[~isnan]
if x.size == 0:
# MAD of an empty array is nan.
return np.nan
# Edge cases have been handled, so do the basic MAD calculation.
med = center(x)
mad = np.median(np.abs(x - med))
return mad
def median_abs_deviation(x, axis=0, center=np.median, scale=1.0,
nan_policy='propagate'):
r"""
Compute the median absolute deviation of the data along the given axis.
The median absolute deviation (MAD, [1]_) computes the median over the
absolute deviations from the median. It is a measure of dispersion
similar to the standard deviation but more robust to outliers [2]_.
The MAD of an empty array is ``np.nan``.
.. versionadded:: 1.5.0
Parameters
----------
x : array_like
Input array or object that can be converted to an array.
axis : int or None, optional
Axis along which the range is computed. Default is 0. If None, compute
the MAD over the entire array.
center : callable, optional
A function that will return the central value. The default is to use
np.median. Any user defined function used will need to have the
function signature ``func(arr, axis)``.
scale : scalar or str, optional
The numerical value of scale will be divided out of the final
result. The default is 1.0. The string "normal" is also accepted,
and results in `scale` being the inverse of the standard normal
quantile function at 0.75, which is approximately 0.67449.
Array-like scale is also allowed, as long as it broadcasts correctly
to the output such that ``out / scale`` is a valid operation. The
output dimensions depend on the input array, `x`, and the `axis`
argument.
nan_policy : {'propagate', 'raise', 'omit'}, optional
Defines how to handle when input contains nan.
The following options are available (default is 'propagate'):
* 'propagate': returns nan
* 'raise': throws an error
* 'omit': performs the calculations ignoring nan values
Returns
-------
mad : scalar or ndarray
If ``axis=None``, a scalar is returned. If the input contains
integers or floats of smaller precision than ``np.float64``, then the
output data-type is ``np.float64``. Otherwise, the output data-type is
the same as that of the input.
See Also
--------
numpy.std, numpy.var, numpy.median, scipy.stats.iqr, scipy.stats.tmean,
scipy.stats.tstd, scipy.stats.tvar
Notes
-----
The `center` argument only affects the calculation of the central value
around which the MAD is calculated. That is, passing in ``center=np.mean``
will calculate the MAD around the mean - it will not calculate the *mean*
absolute deviation.
The input array may contain `inf`, but if `center` returns `inf`, the
corresponding MAD for that data will be `nan`.
References
----------
.. [1] "Median absolute deviation",
https://en.wikipedia.org/wiki/Median_absolute_deviation
.. [2] "Robust measures of scale",
https://en.wikipedia.org/wiki/Robust_measures_of_scale
Examples
--------
When comparing the behavior of `median_abs_deviation` with ``np.std``,
the latter is affected when we change a single value of an array to have an
outlier value while the MAD hardly changes:
>>> from scipy import stats
>>> x = stats.norm.rvs(size=100, scale=1, random_state=123456)
>>> x.std()
0.9973906394005013
>>> stats.median_abs_deviation(x)
0.82832610097857
>>> x[0] = 345.6
>>> x.std()
34.42304872314415
>>> stats.median_abs_deviation(x)
0.8323442311590675
Axis handling example:
>>> x = np.array([[10, 7, 4], [3, 2, 1]])
>>> x
array([[10, 7, 4],
[ 3, 2, 1]])
>>> stats.median_abs_deviation(x)
array([3.5, 2.5, 1.5])
>>> stats.median_abs_deviation(x, axis=None)
2.0
Scale normal example:
>>> x = stats.norm.rvs(size=1000000, scale=2, random_state=123456)
>>> stats.median_abs_deviation(x)
1.3487398527041636
>>> stats.median_abs_deviation(x, scale='normal')
1.9996446978061115
"""
if not callable(center):
raise TypeError("The argument 'center' must be callable. The given "
f"value {repr(center)} is not callable.")
# An error may be raised here, so fail-fast, before doing lengthy
# computations, even though `scale` is not used until later
if isinstance(scale, str):
if scale.lower() == 'normal':
scale = 0.6744897501960817 # special.ndtri(0.75)
else:
raise ValueError(f"{scale} is not a valid scale value.")
x = asarray(x)
# Consistent with `np.var` and `np.std`.
if not x.size:
if axis is None:
return np.nan
nan_shape = tuple(item for i, item in enumerate(x.shape) if i != axis)
if nan_shape == ():
# Return nan, not array(nan)
return np.nan
return np.full(nan_shape, np.nan)
contains_nan, nan_policy = _contains_nan(x, nan_policy)
if contains_nan:
if axis is None:
mad = _mad_1d(x.ravel(), center, nan_policy)
else:
mad = np.apply_along_axis(_mad_1d, axis, x, center, nan_policy)
else:
if axis is None:
med = center(x, axis=None)
mad = np.median(np.abs(x - med))
else:
# Wrap the call to center() in expand_dims() so it acts like
# keepdims=True was used.
med = np.expand_dims(center(x, axis=axis), axis)
mad = np.median(np.abs(x - med), axis=axis)
return mad / scale
# Keep the top newline so that the message does not show up on the stats page
_median_absolute_deviation_deprec_msg = """
To preserve the existing default behavior, use
`scipy.stats.median_abs_deviation(..., scale=1/1.4826)`.
The value 1.4826 is not numerically precise for scaling
with a normal distribution. For a numerically precise value, use
`scipy.stats.median_abs_deviation(..., scale='normal')`.
"""
# Due to numpy/gh-16349 we need to unindent the entire docstring
@np.deprecate(old_name='median_absolute_deviation',
new_name='median_abs_deviation',
message=_median_absolute_deviation_deprec_msg)
def median_absolute_deviation(x, axis=0, center=np.median, scale=1.4826,
nan_policy='propagate'):
r"""
Compute the median absolute deviation of the data along the given axis.
The median absolute deviation (MAD, [1]_) computes the median over the
absolute deviations from the median. It is a measure of dispersion
similar to the standard deviation but more robust to outliers [2]_.
The MAD of an empty array is ``np.nan``.
.. versionadded:: 1.3.0
Parameters
----------
x : array_like
Input array or object that can be converted to an array.
axis : int or None, optional
Axis along which the range is computed. Default is 0. If None, compute
the MAD over the entire array.
center : callable, optional
A function that will return the central value. The default is to use
np.median. Any user defined function used will need to have the function
signature ``func(arr, axis)``.
scale : int, optional
The scaling factor applied to the MAD. The default scale (1.4826)
ensures consistency with the standard deviation for normally distributed
data.
nan_policy : {'propagate', 'raise', 'omit'}, optional
Defines how to handle when input contains nan.
The following options are available (default is 'propagate'):
* 'propagate': returns nan
* 'raise': throws an error
* 'omit': performs the calculations ignoring nan values
Returns
-------
mad : scalar or ndarray
If ``axis=None``, a scalar is returned. If the input contains
integers or floats of smaller precision than ``np.float64``, then the
output data-type is ``np.float64``. Otherwise, the output data-type is
the same as that of the input.
See Also
--------
numpy.std, numpy.var, numpy.median, scipy.stats.iqr, scipy.stats.tmean,
scipy.stats.tstd, scipy.stats.tvar
Notes
-----
The `center` argument only affects the calculation of the central value
around which the MAD is calculated. That is, passing in ``center=np.mean``
will calculate the MAD around the mean - it will not calculate the *mean*
absolute deviation.
References
----------
.. [1] "Median absolute deviation",
https://en.wikipedia.org/wiki/Median_absolute_deviation
.. [2] "Robust measures of scale",
https://en.wikipedia.org/wiki/Robust_measures_of_scale
Examples
--------
When comparing the behavior of `median_absolute_deviation` with ``np.std``,
the latter is affected when we change a single value of an array to have an
outlier value while the MAD hardly changes:
>>> from scipy import stats
>>> x = stats.norm.rvs(size=100, scale=1, random_state=123456)
>>> x.std()
0.9973906394005013
>>> stats.median_absolute_deviation(x)
1.2280762773108278
>>> x[0] = 345.6
>>> x.std()
34.42304872314415
>>> stats.median_absolute_deviation(x)
1.2340335571164334
Axis handling example:
>>> x = np.array([[10, 7, 4], [3, 2, 1]])
>>> x
array([[10, 7, 4],
[ 3, 2, 1]])
>>> stats.median_absolute_deviation(x)
array([5.1891, 3.7065, 2.2239])
>>> stats.median_absolute_deviation(x, axis=None)
2.9652
"""
if isinstance(scale, str):
if scale.lower() == 'raw':
warnings.warn(
"use of scale='raw' is deprecated, use scale=1.0 instead",
np.VisibleDeprecationWarning
)
scale = 1.0
if not isinstance(scale, str):
scale = 1 / scale
return median_abs_deviation(x, axis=axis, center=center, scale=scale,
nan_policy=nan_policy)
#####################################
# TRIMMING FUNCTIONS #
#####################################
SigmaclipResult = namedtuple('SigmaclipResult', ('clipped', 'lower', 'upper'))
def sigmaclip(a, low=4., high=4.):
"""
Perform iterative sigma-clipping of array elements.
Starting from the full sample, all elements outside the critical range are
removed, i.e. all elements of the input array `c` that satisfy either of
the following conditions::
c < mean(c) - std(c)*low
c > mean(c) + std(c)*high
The iteration continues with the updated sample until no
elements are outside the (updated) range.
Parameters
----------
a : array_like
Data array, will be raveled if not 1-D.
low : float, optional
Lower bound factor of sigma clipping. Default is 4.
high : float, optional
Upper bound factor of sigma clipping. Default is 4.
Returns
-------
clipped : ndarray
Input array with clipped elements removed.
lower : float
Lower threshold value use for clipping.
upper : float
Upper threshold value use for clipping.
Examples
--------
>>> from scipy.stats import sigmaclip
>>> a = np.concatenate((np.linspace(9.5, 10.5, 31),
... np.linspace(0, 20, 5)))
>>> fact = 1.5
>>> c, low, upp = sigmaclip(a, fact, fact)
>>> c
array([ 9.96666667, 10. , 10.03333333, 10. ])
>>> c.var(), c.std()
(0.00055555555555555165, 0.023570226039551501)
>>> low, c.mean() - fact*c.std(), c.min()
(9.9646446609406727, 9.9646446609406727, 9.9666666666666668)
>>> upp, c.mean() + fact*c.std(), c.max()
(10.035355339059327, 10.035355339059327, 10.033333333333333)
>>> a = np.concatenate((np.linspace(9.5, 10.5, 11),
... np.linspace(-100, -50, 3)))
>>> c, low, upp = sigmaclip(a, 1.8, 1.8)
>>> (c == np.linspace(9.5, 10.5, 11)).all()
True
"""
c = np.asarray(a).ravel()
delta = 1
while delta:
c_std = c.std()
c_mean = c.mean()
size = c.size
critlower = c_mean - c_std * low
critupper = c_mean + c_std * high
c = c[(c >= critlower) & (c <= critupper)]
delta = size - c.size
return SigmaclipResult(c, critlower, critupper)
def trimboth(a, proportiontocut, axis=0):
"""
Slice off a proportion of items from both ends of an array.
Slice off the passed proportion of items from both ends of the passed
array (i.e., with `proportiontocut` = 0.1, slices leftmost 10% **and**
rightmost 10% of scores). The trimmed values are the lowest and
highest ones.
Slice off less if proportion results in a non-integer slice index (i.e.
conservatively slices off `proportiontocut`).
Parameters
----------
a : array_like
Data to trim.
proportiontocut : float
Proportion (in range 0-1) of total data set to trim of each end.
axis : int or None, optional
Axis along which to trim data. Default is 0. If None, compute over
the whole array `a`.
Returns
-------
out : ndarray
Trimmed version of array `a`. The order of the trimmed content
is undefined.
See Also
--------
trim_mean
Examples
--------
>>> from scipy import stats
>>> a = np.arange(20)
>>> b = stats.trimboth(a, 0.1)
>>> b.shape
(16,)
"""
a = np.asarray(a)
if a.size == 0:
return a
if axis is None:
a = a.ravel()
axis = 0
nobs = a.shape[axis]
lowercut = int(proportiontocut * nobs)
uppercut = nobs - lowercut
if (lowercut >= uppercut):
raise ValueError("Proportion too big.")
atmp = np.partition(a, (lowercut, uppercut - 1), axis)
sl = [slice(None)] * atmp.ndim
sl[axis] = slice(lowercut, uppercut)
return atmp[tuple(sl)]
def trim1(a, proportiontocut, tail='right', axis=0):
"""
Slice off a proportion from ONE end of the passed array distribution.
If `proportiontocut` = 0.1, slices off 'leftmost' or 'rightmost'
10% of scores. The lowest or highest values are trimmed (depending on
the tail).
Slice off less if proportion results in a non-integer slice index
(i.e. conservatively slices off `proportiontocut` ).
Parameters
----------
a : array_like
Input array.
proportiontocut : float
Fraction to cut off of 'left' or 'right' of distribution.
tail : {'left', 'right'}, optional
Defaults to 'right'.
axis : int or None, optional
Axis along which to trim data. Default is 0. If None, compute over
the whole array `a`.
Returns
-------
trim1 : ndarray
Trimmed version of array `a`. The order of the trimmed content is
undefined.
"""
a = np.asarray(a)
if axis is None:
a = a.ravel()
axis = 0
nobs = a.shape[axis]
# avoid possible corner case
if proportiontocut >= 1:
return []
if tail.lower() == 'right':
lowercut = 0
uppercut = nobs - int(proportiontocut * nobs)
elif tail.lower() == 'left':
lowercut = int(proportiontocut * nobs)
uppercut = nobs
atmp = np.partition(a, (lowercut, uppercut - 1), axis)
return atmp[lowercut:uppercut]
def trim_mean(a, proportiontocut, axis=0):
"""
Return mean of array after trimming distribution from both tails.
If `proportiontocut` = 0.1, slices off 'leftmost' and 'rightmost' 10% of
scores. The input is sorted before slicing. Slices off less if proportion
results in a non-integer slice index (i.e., conservatively slices off
`proportiontocut` ).
Parameters
----------
a : array_like
Input array.
proportiontocut : float
Fraction to cut off of both tails of the distribution.
axis : int or None, optional
Axis along which the trimmed means are computed. Default is 0.
If None, compute over the whole array `a`.
Returns
-------
trim_mean : ndarray
Mean of trimmed array.
See Also
--------
trimboth
tmean : Compute the trimmed mean ignoring values outside given `limits`.
Examples
--------
>>> from scipy import stats
>>> x = np.arange(20)
>>> stats.trim_mean(x, 0.1)
9.5
>>> x2 = x.reshape(5, 4)
>>> x2
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15],
[16, 17, 18, 19]])
>>> stats.trim_mean(x2, 0.25)
array([ 8., 9., 10., 11.])
>>> stats.trim_mean(x2, 0.25, axis=1)
array([ 1.5, 5.5, 9.5, 13.5, 17.5])
"""
a = np.asarray(a)
if a.size == 0:
return np.nan
if axis is None:
a = a.ravel()
axis = 0
nobs = a.shape[axis]
lowercut = int(proportiontocut * nobs)
uppercut = nobs - lowercut
if (lowercut > uppercut):
raise ValueError("Proportion too big.")
atmp = np.partition(a, (lowercut, uppercut - 1), axis)
sl = [slice(None)] * atmp.ndim
sl[axis] = slice(lowercut, uppercut)
return np.mean(atmp[tuple(sl)], axis=axis)
F_onewayResult = namedtuple('F_onewayResult', ('statistic', 'pvalue'))
class F_onewayConstantInputWarning(RuntimeWarning):
"""
Warning generated by `f_oneway` when an input is constant, e.g.
each of the samples provided is a constant array.
"""
def __init__(self, msg=None):
if msg is None:
msg = ("Each of the input arrays is constant;"
"the F statistic is not defined or infinite")
self.args = (msg,)
class F_onewayBadInputSizesWarning(RuntimeWarning):
"""
Warning generated by `f_oneway` when an input has length 0,
or if all the inputs have length 1.
"""
pass
def _create_f_oneway_nan_result(shape, axis):
"""
This is a helper function for f_oneway for creating the return values
in certain degenerate conditions. It creates return values that are
all nan with the appropriate shape for the given `shape` and `axis`.
"""
axis = np.core.multiarray.normalize_axis_index(axis, len(shape))
shp = shape[:axis] + shape[axis+1:]
if shp == ():
f = np.nan
prob = np.nan
else:
f = np.full(shp, fill_value=np.nan)
prob = f.copy()
return F_onewayResult(f, prob)
def _first(arr, axis):
"""
Return arr[..., 0:1, ...] where 0:1 is in the `axis` position.
"""
return np.take_along_axis(arr, np.array(0, ndmin=arr.ndim), axis)
def f_oneway(*args, axis=0):
"""
Perform one-way ANOVA.
The one-way ANOVA tests the null hypothesis that two or more groups have
the same population mean. The test is applied to samples from two or
more groups, possibly with differing sizes.
Parameters
----------
sample1, sample2, ... : array_like
The sample measurements for each group. There must be at least
two arguments. If the arrays are multidimensional, then all the
dimensions of the array must be the same except for `axis`.
axis : int, optional
Axis of the input arrays along which the test is applied.
Default is 0.
Returns
-------
statistic : float
The computed F statistic of the test.
pvalue : float
The associated p-value from the F distribution.
Warns
-----
F_onewayConstantInputWarning
Raised if each of the input arrays is constant array.
In this case the F statistic is either infinite or isn't defined,
so ``np.inf`` or ``np.nan`` is returned.
F_onewayBadInputSizesWarning
Raised if the length of any input array is 0, or if all the input
arrays have length 1. ``np.nan`` is returned for the F statistic
and the p-value in these cases.
Notes
-----
The ANOVA test has important assumptions that must be satisfied in order
for the associated p-value to be valid.
1. The samples are independent.
2. Each sample is from a normally distributed population.
3. The population standard deviations of the groups are all equal. This
property is known as homoscedasticity.
If these assumptions are not true for a given set of data, it may still
be possible to use the Kruskal-Wallis H-test (`scipy.stats.kruskal`)
although with some loss of power.
The length of each group must be at least one, and there must be at
least one group with length greater than one. If these conditions
are not satisfied, a warning is generated and (``np.nan``, ``np.nan``)
is returned.
If each group contains constant values, and there exist at least two
groups with different values, the function generates a warning and
returns (``np.inf``, 0).
If all values in all groups are the same, function generates a warning
and returns (``np.nan``, ``np.nan``).
The algorithm is from Heiman [2]_, pp.394-7.
References
----------
.. [1] R. Lowry, "Concepts and Applications of Inferential Statistics",
Chapter 14, 2014, http://vassarstats.net/textbook/
.. [2] G.W. Heiman, "Understanding research methods and statistics: An
integrated introduction for psychology", Houghton, Mifflin and
Company, 2001.
.. [3] G.H. McDonald, "Handbook of Biological Statistics", One-way ANOVA.
http://www.biostathandbook.com/onewayanova.html
Examples
--------
>>> from scipy.stats import f_oneway
Here are some data [3]_ on a shell measurement (the length of the anterior
adductor muscle scar, standardized by dividing by length) in the mussel
Mytilus trossulus from five locations: Tillamook, Oregon; Newport, Oregon;
Petersburg, Alaska; Magadan, Russia; and Tvarminne, Finland, taken from a
much larger data set used in McDonald et al. (1991).
>>> tillamook = [0.0571, 0.0813, 0.0831, 0.0976, 0.0817, 0.0859, 0.0735,
... 0.0659, 0.0923, 0.0836]
>>> newport = [0.0873, 0.0662, 0.0672, 0.0819, 0.0749, 0.0649, 0.0835,
... 0.0725]
>>> petersburg = [0.0974, 0.1352, 0.0817, 0.1016, 0.0968, 0.1064, 0.105]
>>> magadan = [0.1033, 0.0915, 0.0781, 0.0685, 0.0677, 0.0697, 0.0764,
... 0.0689]
>>> tvarminne = [0.0703, 0.1026, 0.0956, 0.0973, 0.1039, 0.1045]
>>> f_oneway(tillamook, newport, petersburg, magadan, tvarminne)
F_onewayResult(statistic=7.121019471642447, pvalue=0.0002812242314534544)
`f_oneway` accepts multidimensional input arrays. When the inputs
are multidimensional and `axis` is not given, the test is performed
along the first axis of the input arrays. For the following data, the
test is performed three times, once for each column.
>>> a = np.array([[9.87, 9.03, 6.81],
... [7.18, 8.35, 7.00],
... [8.39, 7.58, 7.68],
... [7.45, 6.33, 9.35],
... [6.41, 7.10, 9.33],
... [8.00, 8.24, 8.44]])
>>> b = np.array([[6.35, 7.30, 7.16],
... [6.65, 6.68, 7.63],
... [5.72, 7.73, 6.72],
... [7.01, 9.19, 7.41],
... [7.75, 7.87, 8.30],
... [6.90, 7.97, 6.97]])
>>> c = np.array([[3.31, 8.77, 1.01],
... [8.25, 3.24, 3.62],
... [6.32, 8.81, 5.19],
... [7.48, 8.83, 8.91],
... [8.59, 6.01, 6.07],
... [3.07, 9.72, 7.48]])
>>> F, p = f_oneway(a, b, c)
>>> F
array([1.75676344, 0.03701228, 3.76439349])
>>> p
array([0.20630784, 0.96375203, 0.04733157])
"""
if len(args) < 2:
raise TypeError(f'at least two inputs are required; got {len(args)}.')
args = [np.asarray(arg, dtype=float) for arg in args]
# ANOVA on N groups, each in its own array
num_groups = len(args)
# We haven't explicitly validated axis, but if it is bad, this call of
# np.concatenate will raise np.AxisError. The call will raise ValueError
# if the dimensions of all the arrays, except the axis dimension, are not
# the same.
alldata = np.concatenate(args, axis=axis)
bign = alldata.shape[axis]
# Check this after forming alldata, so shape errors are detected
# and reported before checking for 0 length inputs.
if any(arg.shape[axis] == 0 for arg in args):
warnings.warn(F_onewayBadInputSizesWarning('at least one input '
'has length 0'))
return _create_f_oneway_nan_result(alldata.shape, axis)
# Must have at least one group with length greater than 1.
if all(arg.shape[axis] == 1 for arg in args):
msg = ('all input arrays have length 1. f_oneway requires that at '
'least one input has length greater than 1.')
warnings.warn(F_onewayBadInputSizesWarning(msg))
return _create_f_oneway_nan_result(alldata.shape, axis)
# Check if the values within each group are constant, and if the common
# value in at least one group is different from that in another group.
# Based on https://github.com/scipy/scipy/issues/11669
# If axis=0, say, and the groups have shape (n0, ...), (n1, ...), ...,
# then is_const is a boolean array with shape (num_groups, ...).
# It is True if the groups along the axis slice are each consant.
# In the typical case where each input array is 1-d, is_const is a
# 1-d array with length num_groups.
is_const = np.concatenate([(_first(a, axis) == a).all(axis=axis,
keepdims=True)
for a in args], axis=axis)
# all_const is a boolean array with shape (...) (see previous comment).
# It is True if the values within each group along the axis slice are
# the same (e.g. [[3, 3, 3], [5, 5, 5, 5], [4, 4, 4]]).
all_const = is_const.all(axis=axis)
if all_const.any():
warnings.warn(F_onewayConstantInputWarning())
# all_same_const is True if all the values in the groups along the axis=0
# slice are the same (e.g. [[3, 3, 3], [3, 3, 3, 3], [3, 3, 3]]).
all_same_const = (_first(alldata, axis) == alldata).all(axis=axis)
# Determine the mean of the data, and subtract that from all inputs to a
# variance (via sum_of_sq / sq_of_sum) calculation. Variance is invariant
# to a shift in location, and centering all data around zero vastly
# improves numerical stability.
offset = alldata.mean(axis=axis, keepdims=True)
alldata -= offset
normalized_ss = _square_of_sums(alldata, axis=axis) / bign
sstot = _sum_of_squares(alldata, axis=axis) - normalized_ss
ssbn = 0
for a in args:
ssbn += _square_of_sums(a - offset, axis=axis) / a.shape[axis]
# Naming: variables ending in bn/b are for "between treatments", wn/w are
# for "within treatments"
ssbn -= normalized_ss
sswn = sstot - ssbn
dfbn = num_groups - 1
dfwn = bign - num_groups
msb = ssbn / dfbn
msw = sswn / dfwn
with np.errstate(divide='ignore', invalid='ignore'):
f = msb / msw
prob = special.fdtrc(dfbn, dfwn, f) # equivalent to stats.f.sf
# Fix any f values that should be inf or nan because the corresponding
# inputs were constant.
if np.isscalar(f):
if all_same_const:
f = np.nan
prob = np.nan
elif all_const:
f = np.inf
prob = 0.0
else:
f[all_const] = np.inf
prob[all_const] = 0.0
f[all_same_const] = np.nan
prob[all_same_const] = np.nan
return F_onewayResult(f, prob)
class PearsonRConstantInputWarning(RuntimeWarning):
"""Warning generated by `pearsonr` when an input is constant."""
def __init__(self, msg=None):
if msg is None:
msg = ("An input array is constant; the correlation coefficent "
"is not defined.")
self.args = (msg,)
class PearsonRNearConstantInputWarning(RuntimeWarning):
"""Warning generated by `pearsonr` when an input is nearly constant."""
def __init__(self, msg=None):
if msg is None:
msg = ("An input array is nearly constant; the computed "
"correlation coefficent may be inaccurate.")
self.args = (msg,)
def pearsonr(x, y):
r"""
Pearson correlation coefficient and p-value for testing non-correlation.
The Pearson correlation coefficient [1]_ measures the linear relationship
between two datasets. The calculation of the p-value relies on the
assumption that each dataset is normally distributed. (See Kowalski [3]_
for a discussion of the effects of non-normality of the input on the
distribution of the correlation coefficient.) Like other correlation
coefficients, this one varies between -1 and +1 with 0 implying no
correlation. Correlations of -1 or +1 imply an exact linear relationship.
Positive correlations imply that as x increases, so does y. Negative
correlations imply that as x increases, y decreases.
The p-value roughly indicates the probability of an uncorrelated system
producing datasets that have a Pearson correlation at least as extreme
as the one computed from these datasets.
Parameters
----------
x : (N,) array_like
Input array.
y : (N,) array_like
Input array.
Returns
-------
r : float
Pearson's correlation coefficient.
p-value : float
Two-tailed p-value.
Warns
-----
PearsonRConstantInputWarning
Raised if an input is a constant array. The correlation coefficient
is not defined in this case, so ``np.nan`` is returned.
PearsonRNearConstantInputWarning
Raised if an input is "nearly" constant. The array ``x`` is considered
nearly constant if ``norm(x - mean(x)) < 1e-13 * abs(mean(x))``.
Numerical errors in the calculation ``x - mean(x)`` in this case might
result in an inaccurate calculation of r.
See Also
--------
spearmanr : Spearman rank-order correlation coefficient.
kendalltau : Kendall's tau, a correlation measure for ordinal data.
Notes
-----
The correlation coefficient is calculated as follows:
.. math::
r = \frac{\sum (x - m_x) (y - m_y)}
{\sqrt{\sum (x - m_x)^2 \sum (y - m_y)^2}}
where :math:`m_x` is the mean of the vector :math:`x` and :math:`m_y` is
the mean of the vector :math:`y`.
Under the assumption that :math:`x` and :math:`m_y` are drawn from
independent normal distributions (so the population correlation coefficient
is 0), the probability density function of the sample correlation
coefficient :math:`r` is ([1]_, [2]_):
.. math::
f(r) = \frac{{(1-r^2)}^{n/2-2}}{\mathrm{B}(\frac{1}{2},\frac{n}{2}-1)}
where n is the number of samples, and B is the beta function. This
is sometimes referred to as the exact distribution of r. This is
the distribution that is used in `pearsonr` to compute the p-value.
The distribution is a beta distribution on the interval [-1, 1],
with equal shape parameters a = b = n/2 - 1. In terms of SciPy's
implementation of the beta distribution, the distribution of r is::
dist = scipy.stats.beta(n/2 - 1, n/2 - 1, loc=-1, scale=2)
The p-value returned by `pearsonr` is a two-sided p-value. For a
given sample with correlation coefficient r, the p-value is
the probability that abs(r') of a random sample x' and y' drawn from
the population with zero correlation would be greater than or equal
to abs(r). In terms of the object ``dist`` shown above, the p-value
for a given r and length n can be computed as::
p = 2*dist.cdf(-abs(r))
When n is 2, the above continuous distribution is not well-defined.
One can interpret the limit of the beta distribution as the shape
parameters a and b approach a = b = 0 as a discrete distribution with
equal probability masses at r = 1 and r = -1. More directly, one
can observe that, given the data x = [x1, x2] and y = [y1, y2], and
assuming x1 != x2 and y1 != y2, the only possible values for r are 1
and -1. Because abs(r') for any sample x' and y' with length 2 will
be 1, the two-sided p-value for a sample of length 2 is always 1.
References
----------
.. [1] "Pearson correlation coefficient", Wikipedia,
https://en.wikipedia.org/wiki/Pearson_correlation_coefficient
.. [2] Student, "Probable error of a correlation coefficient",
Biometrika, Volume 6, Issue 2-3, 1 September 1908, pp. 302-310.
.. [3] C. J. Kowalski, "On the Effects of Non-Normality on the Distribution
of the Sample Product-Moment Correlation Coefficient"
Journal of the Royal Statistical Society. Series C (Applied
Statistics), Vol. 21, No. 1 (1972), pp. 1-12.
Examples
--------
>>> from scipy import stats
>>> a = np.array([0, 0, 0, 1, 1, 1, 1])
>>> b = np.arange(7)
>>> stats.pearsonr(a, b)
(0.8660254037844386, 0.011724811003954649)
>>> stats.pearsonr([1, 2, 3, 4, 5], [10, 9, 2.5, 6, 4])
(-0.7426106572325057, 0.1505558088534455)
"""
n = len(x)
if n != len(y):
raise ValueError('x and y must have the same length.')
if n < 2:
raise ValueError('x and y must have length at least 2.')
x = np.asarray(x)
y = np.asarray(y)
# If an input is constant, the correlation coefficient is not defined.
if (x == x[0]).all() or (y == y[0]).all():
warnings.warn(PearsonRConstantInputWarning())
return np.nan, np.nan
# dtype is the data type for the calculations. This expression ensures
# that the data type is at least 64 bit floating point. It might have
# more precision if the input is, for example, np.longdouble.
dtype = type(1.0 + x[0] + y[0])
if n == 2:
return dtype(np.sign(x[1] - x[0])*np.sign(y[1] - y[0])), 1.0
xmean = x.mean(dtype=dtype)
ymean = y.mean(dtype=dtype)
# By using `astype(dtype)`, we ensure that the intermediate calculations
# use at least 64 bit floating point.
xm = x.astype(dtype) - xmean
ym = y.astype(dtype) - ymean
# Unlike np.linalg.norm or the expression sqrt((xm*xm).sum()),
# scipy.linalg.norm(xm) does not overflow if xm is, for example,
# [-5e210, 5e210, 3e200, -3e200]
normxm = linalg.norm(xm)
normym = linalg.norm(ym)
threshold = 1e-13
if normxm < threshold*abs(xmean) or normym < threshold*abs(ymean):
# If all the values in x (likewise y) are very close to the mean,
# the loss of precision that occurs in the subtraction xm = x - xmean
# might result in large errors in r.
warnings.warn(PearsonRNearConstantInputWarning())
r = np.dot(xm/normxm, ym/normym)
# Presumably, if abs(r) > 1, then it is only some small artifact of
# floating point arithmetic.
r = max(min(r, 1.0), -1.0)
# As explained in the docstring, the p-value can be computed as
# p = 2*dist.cdf(-abs(r))
# where dist is the beta distribution on [-1, 1] with shape parameters
# a = b = n/2 - 1. `special.btdtr` is the CDF for the beta distribution
# on [0, 1]. To use it, we make the transformation x = (r + 1)/2; the
# shape parameters do not change. Then -abs(r) used in `cdf(-abs(r))`
# becomes x = (-abs(r) + 1)/2 = 0.5*(1 - abs(r)). (r is cast to float64
# to avoid a TypeError raised by btdtr when r is higher precision.)
ab = n/2 - 1
prob = 2*special.btdtr(ab, ab, 0.5*(1 - abs(np.float64(r))))
return r, prob
def fisher_exact(table, alternative='two-sided'):
"""
Perform a Fisher exact test on a 2x2 contingency table.
Parameters
----------
table : array_like of ints
A 2x2 contingency table. Elements should be non-negative integers.
alternative : {'two-sided', 'less', 'greater'}, optional
Defines the alternative hypothesis.
The following options are available (default is 'two-sided'):
* 'two-sided'
* 'less': one-sided
* 'greater': one-sided
Returns
-------
oddsratio : float
This is prior odds ratio and not a posterior estimate.
p_value : float
P-value, the probability of obtaining a distribution at least as
extreme as the one that was actually observed, assuming that the
null hypothesis is true.
See Also
--------
chi2_contingency : Chi-square test of independence of variables in a
contingency table.
Notes
-----
The calculated odds ratio is different from the one R uses. This scipy
implementation returns the (more common) "unconditional Maximum
Likelihood Estimate", while R uses the "conditional Maximum Likelihood
Estimate".
For tables with large numbers, the (inexact) chi-square test implemented
in the function `chi2_contingency` can also be used.
Examples
--------
Say we spend a few days counting whales and sharks in the Atlantic and
Indian oceans. In the Atlantic ocean we find 8 whales and 1 shark, in the
Indian ocean 2 whales and 5 sharks. Then our contingency table is::
Atlantic Indian
whales 8 2
sharks 1 5
We use this table to find the p-value:
>>> import scipy.stats as stats
>>> oddsratio, pvalue = stats.fisher_exact([[8, 2], [1, 5]])
>>> pvalue
0.0349...
The probability that we would observe this or an even more imbalanced ratio
by chance is about 3.5%. A commonly used significance level is 5%--if we
adopt that, we can therefore conclude that our observed imbalance is
statistically significant; whales prefer the Atlantic while sharks prefer
the Indian ocean.
"""
hypergeom = distributions.hypergeom
c = np.asarray(table, dtype=np.int64) # int32 is not enough for the algorithm
if not c.shape == (2, 2):
raise ValueError("The input `table` must be of shape (2, 2).")
if np.any(c < 0):
raise ValueError("All values in `table` must be nonnegative.")
if 0 in c.sum(axis=0) or 0 in c.sum(axis=1):
# If both values in a row or column are zero, the p-value is 1 and
# the odds ratio is NaN.
return np.nan, 1.0
if c[1, 0] > 0 and c[0, 1] > 0:
oddsratio = c[0, 0] * c[1, 1] / (c[1, 0] * c[0, 1])
else:
oddsratio = np.inf
n1 = c[0, 0] + c[0, 1]
n2 = c[1, 0] + c[1, 1]
n = c[0, 0] + c[1, 0]
def binary_search(n, n1, n2, side):
"""Binary search for where to begin halves in two-sided test."""
if side == "upper":
minval = mode
maxval = n
else:
minval = 0
maxval = mode
guess = -1
while maxval - minval > 1:
if maxval == minval + 1 and guess == minval:
guess = maxval
else:
guess = (maxval + minval) // 2
pguess = hypergeom.pmf(guess, n1 + n2, n1, n)
if side == "upper":
ng = guess - 1
else:
ng = guess + 1
if pguess <= pexact < hypergeom.pmf(ng, n1 + n2, n1, n):
break
elif pguess < pexact:
maxval = guess
else:
minval = guess
if guess == -1:
guess = minval
if side == "upper":
while guess > 0 and hypergeom.pmf(guess, n1 + n2, n1, n) < pexact * epsilon:
guess -= 1
while hypergeom.pmf(guess, n1 + n2, n1, n) > pexact / epsilon:
guess += 1
else:
while hypergeom.pmf(guess, n1 + n2, n1, n) < pexact * epsilon:
guess += 1
while guess > 0 and hypergeom.pmf(guess, n1 + n2, n1, n) > pexact / epsilon:
guess -= 1
return guess
if alternative == 'less':
pvalue = hypergeom.cdf(c[0, 0], n1 + n2, n1, n)
elif alternative == 'greater':
# Same formula as the 'less' case, but with the second column.
pvalue = hypergeom.cdf(c[0, 1], n1 + n2, n1, c[0, 1] + c[1, 1])
elif alternative == 'two-sided':
mode = int((n + 1) * (n1 + 1) / (n1 + n2 + 2))
pexact = hypergeom.pmf(c[0, 0], n1 + n2, n1, n)
pmode = hypergeom.pmf(mode, n1 + n2, n1, n)
epsilon = 1 - 1e-4
if np.abs(pexact - pmode) / np.maximum(pexact, pmode) <= 1 - epsilon:
return oddsratio, 1.
elif c[0, 0] < mode:
plower = hypergeom.cdf(c[0, 0], n1 + n2, n1, n)
if hypergeom.pmf(n, n1 + n2, n1, n) > pexact / epsilon:
return oddsratio, plower
guess = binary_search(n, n1, n2, "upper")
pvalue = plower + hypergeom.sf(guess - 1, n1 + n2, n1, n)
else:
pupper = hypergeom.sf(c[0, 0] - 1, n1 + n2, n1, n)
if hypergeom.pmf(0, n1 + n2, n1, n) > pexact / epsilon:
return oddsratio, pupper
guess = binary_search(n, n1, n2, "lower")
pvalue = pupper + hypergeom.cdf(guess, n1 + n2, n1, n)
else:
msg = "`alternative` should be one of {'two-sided', 'less', 'greater'}"
raise ValueError(msg)
pvalue = min(pvalue, 1.0)
return oddsratio, pvalue
class SpearmanRConstantInputWarning(RuntimeWarning):
"""Warning generated by `spearmanr` when an input is constant."""
def __init__(self, msg=None):
if msg is None:
msg = ("An input array is constant; the correlation coefficent "
"is not defined.")
self.args = (msg,)
SpearmanrResult = namedtuple('SpearmanrResult', ('correlation', 'pvalue'))
def spearmanr(a, b=None, axis=0, nan_policy='propagate'):
"""
Calculate a Spearman correlation coefficient with associated p-value.
The Spearman rank-order correlation coefficient is a nonparametric measure
of the monotonicity of the relationship between two datasets. Unlike the
Pearson correlation, the Spearman correlation does not assume that both
datasets are normally distributed. Like other correlation coefficients,
this one varies between -1 and +1 with 0 implying no correlation.
Correlations of -1 or +1 imply an exact monotonic relationship. Positive
correlations imply that as x increases, so does y. Negative correlations
imply that as x increases, y decreases.
The p-value roughly indicates the probability of an uncorrelated system
producing datasets that have a Spearman correlation at least as extreme
as the one computed from these datasets. The p-values are not entirely
reliable but are probably reasonable for datasets larger than 500 or so.
Parameters
----------
a, b : 1D or 2D array_like, b is optional
One or two 1-D or 2-D arrays containing multiple variables and
observations. When these are 1-D, each represents a vector of
observations of a single variable. For the behavior in the 2-D case,
see under ``axis``, below.
Both arrays need to have the same length in the ``axis`` dimension.
axis : int or None, optional
If axis=0 (default), then each column represents a variable, with
observations in the rows. If axis=1, the relationship is transposed:
each row represents a variable, while the columns contain observations.
If axis=None, then both arrays will be raveled.
nan_policy : {'propagate', 'raise', 'omit'}, optional
Defines how to handle when input contains nan.
The following options are available (default is 'propagate'):
* 'propagate': returns nan
* 'raise': throws an error
* 'omit': performs the calculations ignoring nan values
Returns
-------
correlation : float or ndarray (2-D square)
Spearman correlation matrix or correlation coefficient (if only 2
variables are given as parameters. Correlation matrix is square with
length equal to total number of variables (columns or rows) in ``a``
and ``b`` combined.
pvalue : float
The two-sided p-value for a hypothesis test whose null hypothesis is
that two sets of data are uncorrelated, has same dimension as rho.
References
----------
.. [1] Zwillinger, D. and Kokoska, S. (2000). CRC Standard
Probability and Statistics Tables and Formulae. Chapman & Hall: New
York. 2000.
Section 14.7
Examples
--------
>>> from scipy import stats
>>> stats.spearmanr([1,2,3,4,5], [5,6,7,8,7])
(0.82078268166812329, 0.088587005313543798)
>>> np.random.seed(1234321)
>>> x2n = np.random.randn(100, 2)
>>> y2n = np.random.randn(100, 2)
>>> stats.spearmanr(x2n)
(0.059969996999699973, 0.55338590803773591)
>>> stats.spearmanr(x2n[:,0], x2n[:,1])
(0.059969996999699973, 0.55338590803773591)
>>> rho, pval = stats.spearmanr(x2n, y2n)
>>> rho
array([[ 1. , 0.05997 , 0.18569457, 0.06258626],
[ 0.05997 , 1. , 0.110003 , 0.02534653],
[ 0.18569457, 0.110003 , 1. , 0.03488749],
[ 0.06258626, 0.02534653, 0.03488749, 1. ]])
>>> pval
array([[ 0. , 0.55338591, 0.06435364, 0.53617935],
[ 0.55338591, 0. , 0.27592895, 0.80234077],
[ 0.06435364, 0.27592895, 0. , 0.73039992],
[ 0.53617935, 0.80234077, 0.73039992, 0. ]])
>>> rho, pval = stats.spearmanr(x2n.T, y2n.T, axis=1)
>>> rho
array([[ 1. , 0.05997 , 0.18569457, 0.06258626],
[ 0.05997 , 1. , 0.110003 , 0.02534653],
[ 0.18569457, 0.110003 , 1. , 0.03488749],
[ 0.06258626, 0.02534653, 0.03488749, 1. ]])
>>> stats.spearmanr(x2n, y2n, axis=None)
(0.10816770419260482, 0.1273562188027364)
>>> stats.spearmanr(x2n.ravel(), y2n.ravel())
(0.10816770419260482, 0.1273562188027364)
>>> xint = np.random.randint(10, size=(100, 2))
>>> stats.spearmanr(xint)
(0.052760927029710199, 0.60213045837062351)
"""
if axis is not None and axis > 1:
raise ValueError("spearmanr only handles 1-D or 2-D arrays, supplied axis argument {}, please use only values 0, 1 or None for axis".format(axis))
a, axisout = _chk_asarray(a, axis)
if a.ndim > 2:
raise ValueError("spearmanr only handles 1-D or 2-D arrays")
if b is None:
if a.ndim < 2:
raise ValueError("`spearmanr` needs at least 2 variables to compare")
else:
# Concatenate a and b, so that we now only have to handle the case
# of a 2-D `a`.
b, _ = _chk_asarray(b, axis)
if axisout == 0:
a = np.column_stack((a, b))
else:
a = np.row_stack((a, b))
n_vars = a.shape[1 - axisout]
n_obs = a.shape[axisout]
if n_obs <= 1:
# Handle empty arrays or single observations.
return SpearmanrResult(np.nan, np.nan)
if axisout == 0:
if (a[:, 0][0] == a[:, 0]).all() or (a[:, 1][0] == a[:, 1]).all():
# If an input is constant, the correlation coefficient is not defined.
warnings.warn(SpearmanRConstantInputWarning())
return SpearmanrResult(np.nan, np.nan)
else: # case when axisout == 1 b/c a is 2 dim only
if (a[0, :][0] == a[0, :]).all() or (a[1, :][0] == a[1, :]).all():
# If an input is constant, the correlation coefficient is not defined.
warnings.warn(SpearmanRConstantInputWarning())
return SpearmanrResult(np.nan, np.nan)
a_contains_nan, nan_policy = _contains_nan(a, nan_policy)
variable_has_nan = np.zeros(n_vars, dtype=bool)
if a_contains_nan:
if nan_policy == 'omit':
return mstats_basic.spearmanr(a, axis=axis, nan_policy=nan_policy)
elif nan_policy == 'propagate':
if a.ndim == 1 or n_vars <= 2:
return SpearmanrResult(np.nan, np.nan)
else:
# Keep track of variables with NaNs, set the outputs to NaN
# only for those variables
variable_has_nan = np.isnan(a).any(axis=axisout)
a_ranked = np.apply_along_axis(rankdata, axisout, a)
rs = np.corrcoef(a_ranked, rowvar=axisout)
dof = n_obs - 2 # degrees of freedom
# rs can have elements equal to 1, so avoid zero division warnings
with np.errstate(divide='ignore'):
# clip the small negative values possibly caused by rounding
# errors before taking the square root
t = rs * np.sqrt((dof/((rs+1.0)*(1.0-rs))).clip(0))
prob = 2 * distributions.t.sf(np.abs(t), dof)
# For backwards compatibility, return scalars when comparing 2 columns
if rs.shape == (2, 2):
return SpearmanrResult(rs[1, 0], prob[1, 0])
else:
rs[variable_has_nan, :] = np.nan
rs[:, variable_has_nan] = np.nan
return SpearmanrResult(rs, prob)
PointbiserialrResult = namedtuple('PointbiserialrResult',
('correlation', 'pvalue'))
def pointbiserialr(x, y):
r"""
Calculate a point biserial correlation coefficient and its p-value.
The point biserial correlation is used to measure the relationship
between a binary variable, x, and a continuous variable, y. Like other
correlation coefficients, this one varies between -1 and +1 with 0
implying no correlation. Correlations of -1 or +1 imply a determinative
relationship.
This function uses a shortcut formula but produces the same result as
`pearsonr`.
Parameters
----------
x : array_like of bools
Input array.
y : array_like
Input array.
Returns
-------
correlation : float
R value.
pvalue : float
Two-sided p-value.
Notes
-----
`pointbiserialr` uses a t-test with ``n-1`` degrees of freedom.
It is equivalent to `pearsonr`.
The value of the point-biserial correlation can be calculated from:
.. math::
r_{pb} = \frac{\overline{Y_{1}} -
\overline{Y_{0}}}{s_{y}}\sqrt{\frac{N_{1} N_{2}}{N (N - 1))}}
Where :math:`Y_{0}` and :math:`Y_{1}` are means of the metric
observations coded 0 and 1 respectively; :math:`N_{0}` and :math:`N_{1}`
are number of observations coded 0 and 1 respectively; :math:`N` is the
total number of observations and :math:`s_{y}` is the standard
deviation of all the metric observations.
A value of :math:`r_{pb}` that is significantly different from zero is
completely equivalent to a significant difference in means between the two
groups. Thus, an independent groups t Test with :math:`N-2` degrees of
freedom may be used to test whether :math:`r_{pb}` is nonzero. The
relation between the t-statistic for comparing two independent groups and
:math:`r_{pb}` is given by:
.. math::
t = \sqrt{N - 2}\frac{r_{pb}}{\sqrt{1 - r^{2}_{pb}}}
References
----------
.. [1] J. Lev, "The Point Biserial Coefficient of Correlation", Ann. Math.
Statist., Vol. 20, no.1, pp. 125-126, 1949.
.. [2] R.F. Tate, "Correlation Between a Discrete and a Continuous
Variable. Point-Biserial Correlation.", Ann. Math. Statist., Vol. 25,
np. 3, pp. 603-607, 1954.
.. [3] D. Kornbrot "Point Biserial Correlation", In Wiley StatsRef:
Statistics Reference Online (eds N. Balakrishnan, et al.), 2014.
:doi:`10.1002/9781118445112.stat06227`
Examples
--------
>>> from scipy import stats
>>> a = np.array([0, 0, 0, 1, 1, 1, 1])
>>> b = np.arange(7)
>>> stats.pointbiserialr(a, b)
(0.8660254037844386, 0.011724811003954652)
>>> stats.pearsonr(a, b)
(0.86602540378443871, 0.011724811003954626)
>>> np.corrcoef(a, b)
array([[ 1. , 0.8660254],
[ 0.8660254, 1. ]])
"""
rpb, prob = pearsonr(x, y)
return PointbiserialrResult(rpb, prob)
KendalltauResult = namedtuple('KendalltauResult', ('correlation', 'pvalue'))
def kendalltau(x, y, initial_lexsort=None, nan_policy='propagate',
method='auto', variant='b'):
"""
Calculate Kendall's tau, a correlation measure for ordinal data.
Kendall's tau is a measure of the correspondence between two rankings.
Values close to 1 indicate strong agreement, and values close to -1
indicate strong disagreement. This implements two variants of Kendall's
tau: tau-b (the default) and tau-c (also known as Stuart's tau-c). These
differ only in how they are normalized to lie within the range -1 to 1;
the hypothesis tests (their p-values) are identical. Kendall's original
tau-a is not implemented separately because both tau-b and tau-c reduce
to tau-a in the absence of ties.
Parameters
----------
x, y : array_like
Arrays of rankings, of the same shape. If arrays are not 1-D, they
will be flattened to 1-D.
initial_lexsort : bool, optional
Unused (deprecated).
nan_policy : {'propagate', 'raise', 'omit'}, optional
Defines how to handle when input contains nan.
The following options are available (default is 'propagate'):
* 'propagate': returns nan
* 'raise': throws an error
* 'omit': performs the calculations ignoring nan values
method : {'auto', 'asymptotic', 'exact'}, optional
Defines which method is used to calculate the p-value [5]_.
The following options are available (default is 'auto'):
* 'auto': selects the appropriate method based on a trade-off
between speed and accuracy
* 'asymptotic': uses a normal approximation valid for large samples
* 'exact': computes the exact p-value, but can only be used if no ties
are present. As the sample size increases, the 'exact' computation
time may grow and the result may lose some precision.
variant: {'b', 'c'}, optional
Defines which variant of Kendall's tau is returned. Default is 'b'.
Returns
-------
correlation : float
The tau statistic.
pvalue : float
The two-sided p-value for a hypothesis test whose null hypothesis is
an absence of association, tau = 0.
See Also
--------
spearmanr : Calculates a Spearman rank-order correlation coefficient.
theilslopes : Computes the Theil-Sen estimator for a set of points (x, y).
weightedtau : Computes a weighted version of Kendall's tau.
Notes
-----
The definition of Kendall's tau that is used is [2]_::
tau_b = (P - Q) / sqrt((P + Q + T) * (P + Q + U))
tau_c = 2 (P - Q) / (n**2 * (m - 1) / m)
where P is the number of concordant pairs, Q the number of discordant
pairs, T the number of ties only in `x`, and U the number of ties only in
`y`. If a tie occurs for the same pair in both `x` and `y`, it is not
added to either T or U. n is the total number of samples, and m is the
number of unique values in either `x` or `y`, whichever is smaller.
References
----------
.. [1] Maurice G. Kendall, "A New Measure of Rank Correlation", Biometrika
Vol. 30, No. 1/2, pp. 81-93, 1938.
.. [2] Maurice G. Kendall, "The treatment of ties in ranking problems",
Biometrika Vol. 33, No. 3, pp. 239-251. 1945.
.. [3] Gottfried E. Noether, "Elements of Nonparametric Statistics", John
Wiley & Sons, 1967.
.. [4] Peter M. Fenwick, "A new data structure for cumulative frequency
tables", Software: Practice and Experience, Vol. 24, No. 3,
pp. 327-336, 1994.
.. [5] Maurice G. Kendall, "Rank Correlation Methods" (4th Edition),
Charles Griffin & Co., 1970.
Examples
--------
>>> from scipy import stats
>>> x1 = [12, 2, 1, 12, 2]
>>> x2 = [1, 4, 7, 1, 0]
>>> tau, p_value = stats.kendalltau(x1, x2)
>>> tau
-0.47140452079103173
>>> p_value
0.2827454599327748
"""
x = np.asarray(x).ravel()
y = np.asarray(y).ravel()
if x.size != y.size:
raise ValueError("All inputs to `kendalltau` must be of the same "
f"size, found x-size {x.size} and y-size {y.size}")
elif not x.size or not y.size:
# Return NaN if arrays are empty
return KendalltauResult(np.nan, np.nan)
# check both x and y
cnx, npx = _contains_nan(x, nan_policy)
cny, npy = _contains_nan(y, nan_policy)
contains_nan = cnx or cny
if npx == 'omit' or npy == 'omit':
nan_policy = 'omit'
if contains_nan and nan_policy == 'propagate':
return KendalltauResult(np.nan, np.nan)
elif contains_nan and nan_policy == 'omit':
x = ma.masked_invalid(x)
y = ma.masked_invalid(y)
if variant == 'b':
return mstats_basic.kendalltau(x, y, method=method, use_ties=True)
else:
raise ValueError("Only variant 'b' is supported for masked arrays")
if initial_lexsort is not None: # deprecate to drop!
warnings.warn('"initial_lexsort" is gone!')
def count_rank_tie(ranks):
cnt = np.bincount(ranks).astype('int64', copy=False)
cnt = cnt[cnt > 1]
return ((cnt * (cnt - 1) // 2).sum(),
(cnt * (cnt - 1.) * (cnt - 2)).sum(),
(cnt * (cnt - 1.) * (2*cnt + 5)).sum())
size = x.size
perm = np.argsort(y) # sort on y and convert y to dense ranks
x, y = x[perm], y[perm]
y = np.r_[True, y[1:] != y[:-1]].cumsum(dtype=np.intp)
# stable sort on x and convert x to dense ranks
perm = np.argsort(x, kind='mergesort')
x, y = x[perm], y[perm]
x = np.r_[True, x[1:] != x[:-1]].cumsum(dtype=np.intp)
dis = _kendall_dis(x, y) # discordant pairs
obs = np.r_[True, (x[1:] != x[:-1]) | (y[1:] != y[:-1]), True]
cnt = np.diff(np.nonzero(obs)[0]).astype('int64', copy=False)
ntie = (cnt * (cnt - 1) // 2).sum() # joint ties
xtie, x0, x1 = count_rank_tie(x) # ties in x, stats
ytie, y0, y1 = count_rank_tie(y) # ties in y, stats
tot = (size * (size - 1)) // 2
if xtie == tot or ytie == tot:
return KendalltauResult(np.nan, np.nan)
# Note that tot = con + dis + (xtie - ntie) + (ytie - ntie) + ntie
# = con + dis + xtie + ytie - ntie
con_minus_dis = tot - xtie - ytie + ntie - 2 * dis
if variant == 'b':
tau = con_minus_dis / np.sqrt(tot - xtie) / np.sqrt(tot - ytie)
elif variant == 'c':
minclasses = min(len(set(x)), len(set(y)))
tau = 2*con_minus_dis / (size**2 * (minclasses-1)/minclasses)
else:
raise ValueError(f"Unknown variant of the method chosen: {variant}. "
"variant must be 'b' or 'c'.")
# Limit range to fix computational errors
tau = min(1., max(-1., tau))
# The p-value calculation is the same for all variants since the p-value
# depends only on con_minus_dis.
if method == 'exact' and (xtie != 0 or ytie != 0):
raise ValueError("Ties found, exact method cannot be used.")
if method == 'auto':
if (xtie == 0 and ytie == 0) and (size <= 33 or
min(dis, tot-dis) <= 1):
method = 'exact'
else:
method = 'asymptotic'
if xtie == 0 and ytie == 0 and method == 'exact':
pvalue = mstats_basic._kendall_p_exact(size, min(dis, tot-dis))
elif method == 'asymptotic':
# con_minus_dis is approx normally distributed with this variance [3]_
m = size * (size - 1.)
var = ((m * (2*size + 5) - x1 - y1) / 18 +
(2 * xtie * ytie) / m + x0 * y0 / (9 * m * (size - 2)))
pvalue = (special.erfc(np.abs(con_minus_dis) /
np.sqrt(var) / np.sqrt(2)))
else:
raise ValueError(f"Unknown method {method} specified. Use 'auto', "
"'exact' or 'asymptotic'.")
return KendalltauResult(tau, pvalue)
WeightedTauResult = namedtuple('WeightedTauResult', ('correlation', 'pvalue'))
def weightedtau(x, y, rank=True, weigher=None, additive=True):
r"""
Compute a weighted version of Kendall's :math:`\tau`.
The weighted :math:`\tau` is a weighted version of Kendall's
:math:`\tau` in which exchanges of high weight are more influential than
exchanges of low weight. The default parameters compute the additive
hyperbolic version of the index, :math:`\tau_\mathrm h`, which has
been shown to provide the best balance between important and
unimportant elements [1]_.
The weighting is defined by means of a rank array, which assigns a
nonnegative rank to each element (higher importance ranks being
associated with smaller values, e.g., 0 is the highest possible rank),
and a weigher function, which assigns a weight based on the rank to
each element. The weight of an exchange is then the sum or the product
of the weights of the ranks of the exchanged elements. The default
parameters compute :math:`\tau_\mathrm h`: an exchange between
elements with rank :math:`r` and :math:`s` (starting from zero) has
weight :math:`1/(r+1) + 1/(s+1)`.
Specifying a rank array is meaningful only if you have in mind an
external criterion of importance. If, as it usually happens, you do
not have in mind a specific rank, the weighted :math:`\tau` is
defined by averaging the values obtained using the decreasing
lexicographical rank by (`x`, `y`) and by (`y`, `x`). This is the
behavior with default parameters. Note that the convention used
here for ranking (lower values imply higher importance) is opposite
to that used by other SciPy statistical functions.
Parameters
----------
x, y : array_like
Arrays of scores, of the same shape. If arrays are not 1-D, they will
be flattened to 1-D.
rank : array_like of ints or bool, optional
A nonnegative rank assigned to each element. If it is None, the
decreasing lexicographical rank by (`x`, `y`) will be used: elements of
higher rank will be those with larger `x`-values, using `y`-values to
break ties (in particular, swapping `x` and `y` will give a different
result). If it is False, the element indices will be used
directly as ranks. The default is True, in which case this
function returns the average of the values obtained using the
decreasing lexicographical rank by (`x`, `y`) and by (`y`, `x`).
weigher : callable, optional
The weigher function. Must map nonnegative integers (zero
representing the most important element) to a nonnegative weight.
The default, None, provides hyperbolic weighing, that is,
rank :math:`r` is mapped to weight :math:`1/(r+1)`.
additive : bool, optional
If True, the weight of an exchange is computed by adding the
weights of the ranks of the exchanged elements; otherwise, the weights
are multiplied. The default is True.
Returns
-------
correlation : float
The weighted :math:`\tau` correlation index.
pvalue : float
Presently ``np.nan``, as the null statistics is unknown (even in the
additive hyperbolic case).
See Also
--------
kendalltau : Calculates Kendall's tau.
spearmanr : Calculates a Spearman rank-order correlation coefficient.
theilslopes : Computes the Theil-Sen estimator for a set of points (x, y).
Notes
-----
This function uses an :math:`O(n \log n)`, mergesort-based algorithm
[1]_ that is a weighted extension of Knight's algorithm for Kendall's
:math:`\tau` [2]_. It can compute Shieh's weighted :math:`\tau` [3]_
between rankings without ties (i.e., permutations) by setting
`additive` and `rank` to False, as the definition given in [1]_ is a
generalization of Shieh's.
NaNs are considered the smallest possible score.
.. versionadded:: 0.19.0
References
----------
.. [1] Sebastiano Vigna, "A weighted correlation index for rankings with
ties", Proceedings of the 24th international conference on World
Wide Web, pp. 1166-1176, ACM, 2015.
.. [2] W.R. Knight, "A Computer Method for Calculating Kendall's Tau with
Ungrouped Data", Journal of the American Statistical Association,
Vol. 61, No. 314, Part 1, pp. 436-439, 1966.
.. [3] Grace S. Shieh. "A weighted Kendall's tau statistic", Statistics &
Probability Letters, Vol. 39, No. 1, pp. 17-24, 1998.
Examples
--------
>>> from scipy import stats
>>> x = [12, 2, 1, 12, 2]
>>> y = [1, 4, 7, 1, 0]
>>> tau, p_value = stats.weightedtau(x, y)
>>> tau
-0.56694968153682723
>>> p_value
nan
>>> tau, p_value = stats.weightedtau(x, y, additive=False)
>>> tau
-0.62205716951801038
NaNs are considered the smallest possible score:
>>> x = [12, 2, 1, 12, 2]
>>> y = [1, 4, 7, 1, np.nan]
>>> tau, _ = stats.weightedtau(x, y)
>>> tau
-0.56694968153682723
This is exactly Kendall's tau:
>>> x = [12, 2, 1, 12, 2]
>>> y = [1, 4, 7, 1, 0]
>>> tau, _ = stats.weightedtau(x, y, weigher=lambda x: 1)
>>> tau
-0.47140452079103173
>>> x = [12, 2, 1, 12, 2]
>>> y = [1, 4, 7, 1, 0]
>>> stats.weightedtau(x, y, rank=None)
WeightedTauResult(correlation=-0.4157652301037516, pvalue=nan)
>>> stats.weightedtau(y, x, rank=None)
WeightedTauResult(correlation=-0.7181341329699028, pvalue=nan)
"""
x = np.asarray(x).ravel()
y = np.asarray(y).ravel()
if x.size != y.size:
raise ValueError("All inputs to `weightedtau` must be of the same size, "
"found x-size %s and y-size %s" % (x.size, y.size))
if not x.size:
return WeightedTauResult(np.nan, np.nan) # Return NaN if arrays are empty
# If there are NaNs we apply _toint64()
if np.isnan(np.sum(x)):
x = _toint64(x)
if np.isnan(np.sum(y)):
y = _toint64(y)
# Reduce to ranks unsupported types
if x.dtype != y.dtype:
if x.dtype != np.int64:
x = _toint64(x)
if y.dtype != np.int64:
y = _toint64(y)
else:
if x.dtype not in (np.int32, np.int64, np.float32, np.float64):
x = _toint64(x)
y = _toint64(y)
if rank is True:
return WeightedTauResult((
_weightedrankedtau(x, y, None, weigher, additive) +
_weightedrankedtau(y, x, None, weigher, additive)
) / 2, np.nan)
if rank is False:
rank = np.arange(x.size, dtype=np.intp)
elif rank is not None:
rank = np.asarray(rank).ravel()
if rank.size != x.size:
raise ValueError("All inputs to `weightedtau` must be of the same size, "
"found x-size %s and rank-size %s" % (x.size, rank.size))
return WeightedTauResult(_weightedrankedtau(x, y, rank, weigher, additive), np.nan)
# FROM MGCPY: https://github.com/neurodata/mgcpy
class _ParallelP(object):
"""
Helper function to calculate parallel p-value.
"""
def __init__(self, x, y, random_states):
self.x = x
self.y = y
self.random_states = random_states
def __call__(self, index):
order = self.random_states[index].permutation(self.y.shape[0])
permy = self.y[order][:, order]
# calculate permuted stats, store in null distribution
perm_stat = _mgc_stat(self.x, permy)[0]
return perm_stat
def _perm_test(x, y, stat, reps=1000, workers=-1, random_state=None):
r"""
Helper function that calculates the p-value. See below for uses.
Parameters
----------
x, y : ndarray
`x` and `y` have shapes `(n, p)` and `(n, q)`.
stat : float
The sample test statistic.
reps : int, optional
The number of replications used to estimate the null when using the
permutation test. The default is 1000 replications.
workers : int or map-like callable, optional
If `workers` is an int the population is subdivided into `workers`
sections and evaluated in parallel (uses
`multiprocessing.Pool <multiprocessing>`). Supply `-1` to use all cores
available to the Process. Alternatively supply a map-like callable,
such as `multiprocessing.Pool.map` for evaluating the population in
parallel. This evaluation is carried out as `workers(func, iterable)`.
Requires that `func` be pickleable.
random_state : int or np.random.RandomState instance, optional
If already a RandomState instance, use it.
If seed is an int, return a new RandomState instance seeded with seed.
If None, use np.random.RandomState. Default is None.
Returns
-------
pvalue : float
The sample test p-value.
null_dist : list
The approximated null distribution.
"""
# generate seeds for each rep (change to new parallel random number
# capabilities in numpy >= 1.17+)
random_state = check_random_state(random_state)
random_states = [np.random.RandomState(rng_integers(random_state, 1 << 32,
size=4, dtype=np.uint32)) for _ in range(reps)]
# parallelizes with specified workers over number of reps and set seeds
parallelp = _ParallelP(x=x, y=y, random_states=random_states)
with MapWrapper(workers) as mapwrapper:
null_dist = np.array(list(mapwrapper(parallelp, range(reps))))
# calculate p-value and significant permutation map through list
pvalue = (null_dist >= stat).sum() / reps
# correct for a p-value of 0. This is because, with bootstrapping
# permutations, a p-value of 0 is incorrect
if pvalue == 0:
pvalue = 1 / reps
return pvalue, null_dist
def _euclidean_dist(x):
return cdist(x, x)
MGCResult = namedtuple('MGCResult', ('stat', 'pvalue', 'mgc_dict'))
def multiscale_graphcorr(x, y, compute_distance=_euclidean_dist, reps=1000,
workers=1, is_twosamp=False, random_state=None):
r"""
Computes the Multiscale Graph Correlation (MGC) test statistic.
Specifically, for each point, MGC finds the :math:`k`-nearest neighbors for
one property (e.g. cloud density), and the :math:`l`-nearest neighbors for
the other property (e.g. grass wetness) [1]_. This pair :math:`(k, l)` is
called the "scale". A priori, however, it is not know which scales will be
most informative. So, MGC computes all distance pairs, and then efficiently
computes the distance correlations for all scales. The local correlations
illustrate which scales are relatively informative about the relationship.
The key, therefore, to successfully discover and decipher relationships
between disparate data modalities is to adaptively determine which scales
are the most informative, and the geometric implication for the most
informative scales. Doing so not only provides an estimate of whether the
modalities are related, but also provides insight into how the
determination was made. This is especially important in high-dimensional
data, where simple visualizations do not reveal relationships to the
unaided human eye. Characterizations of this implementation in particular
have been derived from and benchmarked within in [2]_.
Parameters
----------
x, y : ndarray
If ``x`` and ``y`` have shapes ``(n, p)`` and ``(n, q)`` where `n` is
the number of samples and `p` and `q` are the number of dimensions,
then the MGC independence test will be run. Alternatively, ``x`` and
``y`` can have shapes ``(n, n)`` if they are distance or similarity
matrices, and ``compute_distance`` must be sent to ``None``. If ``x``
and ``y`` have shapes ``(n, p)`` and ``(m, p)``, an unpaired
two-sample MGC test will be run.
compute_distance : callable, optional
A function that computes the distance or similarity among the samples
within each data matrix. Set to ``None`` if ``x`` and ``y`` are
already distance matrices. The default uses the euclidean norm metric.
If you are calling a custom function, either create the distance
matrix before-hand or create a function of the form
``compute_distance(x)`` where `x` is the data matrix for which
pairwise distances are calculated.
reps : int, optional
The number of replications used to estimate the null when using the
permutation test. The default is ``1000``.
workers : int or map-like callable, optional
If ``workers`` is an int the population is subdivided into ``workers``
sections and evaluated in parallel (uses ``multiprocessing.Pool
<multiprocessing>``). Supply ``-1`` to use all cores available to the
Process. Alternatively supply a map-like callable, such as
``multiprocessing.Pool.map`` for evaluating the p-value in parallel.
This evaluation is carried out as ``workers(func, iterable)``.
Requires that `func` be pickleable. The default is ``1``.
is_twosamp : bool, optional
If `True`, a two sample test will be run. If ``x`` and ``y`` have
shapes ``(n, p)`` and ``(m, p)``, this optional will be overriden and
set to ``True``. Set to ``True`` if ``x`` and ``y`` both have shapes
``(n, p)`` and a two sample test is desired. The default is ``False``.
Note that this will not run if inputs are distance matrices.
random_state : int or np.random.RandomState instance, optional
If already a RandomState instance, use it.
If seed is an int, return a new RandomState instance seeded with seed.
If None, use np.random.RandomState. Default is None.
Returns
-------
stat : float
The sample MGC test statistic within `[-1, 1]`.
pvalue : float
The p-value obtained via permutation.
mgc_dict : dict
Contains additional useful additional returns containing the following
keys:
- mgc_map : ndarray
A 2D representation of the latent geometry of the relationship.
of the relationship.
- opt_scale : (int, int)
The estimated optimal scale as a `(x, y)` pair.
- null_dist : list
The null distribution derived from the permuted matrices
See Also
--------
pearsonr : Pearson correlation coefficient and p-value for testing
non-correlation.
kendalltau : Calculates Kendall's tau.
spearmanr : Calculates a Spearman rank-order correlation coefficient.
Notes
-----
A description of the process of MGC and applications on neuroscience data
can be found in [1]_. It is performed using the following steps:
#. Two distance matrices :math:`D^X` and :math:`D^Y` are computed and
modified to be mean zero columnwise. This results in two
:math:`n \times n` distance matrices :math:`A` and :math:`B` (the
centering and unbiased modification) [3]_.
#. For all values :math:`k` and :math:`l` from :math:`1, ..., n`,
* The :math:`k`-nearest neighbor and :math:`l`-nearest neighbor graphs
are calculated for each property. Here, :math:`G_k (i, j)` indicates
the :math:`k`-smallest values of the :math:`i`-th row of :math:`A`
and :math:`H_l (i, j)` indicates the :math:`l` smallested values of
the :math:`i`-th row of :math:`B`
* Let :math:`\circ` denotes the entry-wise matrix product, then local
correlations are summed and normalized using the following statistic:
.. math::
c^{kl} = \frac{\sum_{ij} A G_k B H_l}
{\sqrt{\sum_{ij} A^2 G_k \times \sum_{ij} B^2 H_l}}
#. The MGC test statistic is the smoothed optimal local correlation of
:math:`\{ c^{kl} \}`. Denote the smoothing operation as :math:`R(\cdot)`
(which essentially set all isolated large correlations) as 0 and
connected large correlations the same as before, see [3]_.) MGC is,
.. math::
MGC_n (x, y) = \max_{(k, l)} R \left(c^{kl} \left( x_n, y_n \right)
\right)
The test statistic returns a value between :math:`(-1, 1)` since it is
normalized.
The p-value returned is calculated using a permutation test. This process
is completed by first randomly permuting :math:`y` to estimate the null
distribution and then calculating the probability of observing a test
statistic, under the null, at least as extreme as the observed test
statistic.
MGC requires at least 5 samples to run with reliable results. It can also
handle high-dimensional data sets.
In addition, by manipulating the input data matrices, the two-sample
testing problem can be reduced to the independence testing problem [4]_.
Given sample data :math:`U` and :math:`V` of sizes :math:`p \times n`
:math:`p \times m`, data matrix :math:`X` and :math:`Y` can be created as
follows:
.. math::
X = [U | V] \in \mathcal{R}^{p \times (n + m)}
Y = [0_{1 \times n} | 1_{1 \times m}] \in \mathcal{R}^{(n + m)}
Then, the MGC statistic can be calculated as normal. This methodology can
be extended to similar tests such as distance correlation [4]_.
.. versionadded:: 1.4.0
References
----------
.. [1] Vogelstein, J. T., Bridgeford, E. W., Wang, Q., Priebe, C. E.,
Maggioni, M., & Shen, C. (2019). Discovering and deciphering
relationships across disparate data modalities. ELife.
.. [2] Panda, S., Palaniappan, S., Xiong, J., Swaminathan, A.,
Ramachandran, S., Bridgeford, E. W., ... Vogelstein, J. T. (2019).
mgcpy: A Comprehensive High Dimensional Independence Testing Python
Package. :arXiv:`1907.02088`
.. [3] Shen, C., Priebe, C.E., & Vogelstein, J. T. (2019). From distance
correlation to multiscale graph correlation. Journal of the American
Statistical Association.
.. [4] Shen, C. & Vogelstein, J. T. (2018). The Exact Equivalence of
Distance and Kernel Methods for Hypothesis Testing.
:arXiv:`1806.05514`
Examples
--------
>>> from scipy.stats import multiscale_graphcorr
>>> x = np.arange(100)
>>> y = x
>>> stat, pvalue, _ = multiscale_graphcorr(x, y, workers=-1)
>>> '%.1f, %.3f' % (stat, pvalue)
'1.0, 0.001'
Alternatively,
>>> x = np.arange(100)
>>> y = x
>>> mgc = multiscale_graphcorr(x, y)
>>> '%.1f, %.3f' % (mgc.stat, mgc.pvalue)
'1.0, 0.001'
To run an unpaired two-sample test,
>>> x = np.arange(100)
>>> y = np.arange(79)
>>> mgc = multiscale_graphcorr(x, y, random_state=1)
>>> '%.3f, %.2f' % (mgc.stat, mgc.pvalue)
'0.033, 0.02'
or, if shape of the inputs are the same,
>>> x = np.arange(100)
>>> y = x
>>> mgc = multiscale_graphcorr(x, y, is_twosamp=True)
>>> '%.3f, %.1f' % (mgc.stat, mgc.pvalue)
'-0.008, 1.0'
"""
if not isinstance(x, np.ndarray) or not isinstance(y, np.ndarray):
raise ValueError("x and y must be ndarrays")
# convert arrays of type (n,) to (n, 1)
if x.ndim == 1:
x = x[:, np.newaxis]
elif x.ndim != 2:
raise ValueError("Expected a 2-D array `x`, found shape "
"{}".format(x.shape))
if y.ndim == 1:
y = y[:, np.newaxis]
elif y.ndim != 2:
raise ValueError("Expected a 2-D array `y`, found shape "
"{}".format(y.shape))
nx, px = x.shape
ny, py = y.shape
# check for NaNs
_contains_nan(x, nan_policy='raise')
_contains_nan(y, nan_policy='raise')
# check for positive or negative infinity and raise error
if np.sum(np.isinf(x)) > 0 or np.sum(np.isinf(y)) > 0:
raise ValueError("Inputs contain infinities")
if nx != ny:
if px == py:
# reshape x and y for two sample testing
is_twosamp = True
else:
raise ValueError("Shape mismatch, x and y must have shape [n, p] "
"and [n, q] or have shape [n, p] and [m, p].")
if nx < 5 or ny < 5:
raise ValueError("MGC requires at least 5 samples to give reasonable "
"results.")
# convert x and y to float
x = x.astype(np.float64)
y = y.astype(np.float64)
# check if compute_distance_matrix if a callable()
if not callable(compute_distance) and compute_distance is not None:
raise ValueError("Compute_distance must be a function.")
# check if number of reps exists, integer, or > 0 (if under 1000 raises
# warning)
if not isinstance(reps, int) or reps < 0:
raise ValueError("Number of reps must be an integer greater than 0.")
elif reps < 1000:
msg = ("The number of replications is low (under 1000), and p-value "
"calculations may be unreliable. Use the p-value result, with "
"caution!")
warnings.warn(msg, RuntimeWarning)
if is_twosamp:
if compute_distance is None:
raise ValueError("Cannot run if inputs are distance matrices")
x, y = _two_sample_transform(x, y)
if compute_distance is not None:
# compute distance matrices for x and y
x = compute_distance(x)
y = compute_distance(y)
# calculate MGC stat
stat, stat_dict = _mgc_stat(x, y)
stat_mgc_map = stat_dict["stat_mgc_map"]
opt_scale = stat_dict["opt_scale"]
# calculate permutation MGC p-value
pvalue, null_dist = _perm_test(x, y, stat, reps=reps, workers=workers,
random_state=random_state)
# save all stats (other than stat/p-value) in dictionary
mgc_dict = {"mgc_map": stat_mgc_map,
"opt_scale": opt_scale,
"null_dist": null_dist}
return MGCResult(stat, pvalue, mgc_dict)
def _mgc_stat(distx, disty):
r"""
Helper function that calculates the MGC stat. See above for use.
Parameters
----------
x, y : ndarray
`x` and `y` have shapes `(n, p)` and `(n, q)` or `(n, n)` and `(n, n)`
if distance matrices.
Returns
-------
stat : float
The sample MGC test statistic within `[-1, 1]`.
stat_dict : dict
Contains additional useful additional returns containing the following
keys:
- stat_mgc_map : ndarray
MGC-map of the statistics.
- opt_scale : (float, float)
The estimated optimal scale as a `(x, y)` pair.
"""
# calculate MGC map and optimal scale
stat_mgc_map = _local_correlations(distx, disty, global_corr='mgc')
n, m = stat_mgc_map.shape
if m == 1 or n == 1:
# the global scale at is the statistic calculated at maximial nearest
# neighbors. There is not enough local scale to search over, so
# default to global scale
stat = stat_mgc_map[m - 1][n - 1]
opt_scale = m * n
else:
samp_size = len(distx) - 1
# threshold to find connected region of significant local correlations
sig_connect = _threshold_mgc_map(stat_mgc_map, samp_size)
# maximum within the significant region
stat, opt_scale = _smooth_mgc_map(sig_connect, stat_mgc_map)
stat_dict = {"stat_mgc_map": stat_mgc_map,
"opt_scale": opt_scale}
return stat, stat_dict
def _threshold_mgc_map(stat_mgc_map, samp_size):
r"""
Finds a connected region of significance in the MGC-map by thresholding.
Parameters
----------
stat_mgc_map : ndarray
All local correlations within `[-1,1]`.
samp_size : int
The sample size of original data.
Returns
-------
sig_connect : ndarray
A binary matrix with 1's indicating the significant region.
"""
m, n = stat_mgc_map.shape
# 0.02 is simply an empirical threshold, this can be set to 0.01 or 0.05
# with varying levels of performance. Threshold is based on a beta
# approximation.
per_sig = 1 - (0.02 / samp_size) # Percentile to consider as significant
threshold = samp_size * (samp_size - 3)/4 - 1/2 # Beta approximation
threshold = distributions.beta.ppf(per_sig, threshold, threshold) * 2 - 1
# the global scale at is the statistic calculated at maximial nearest
# neighbors. Threshold is the maximium on the global and local scales
threshold = max(threshold, stat_mgc_map[m - 1][n - 1])
# find the largest connected component of significant correlations
sig_connect = stat_mgc_map > threshold
if np.sum(sig_connect) > 0:
sig_connect, _ = measurements.label(sig_connect)
_, label_counts = np.unique(sig_connect, return_counts=True)
# skip the first element in label_counts, as it is count(zeros)
max_label = np.argmax(label_counts[1:]) + 1
sig_connect = sig_connect == max_label
else:
sig_connect = np.array([[False]])
return sig_connect
def _smooth_mgc_map(sig_connect, stat_mgc_map):
"""
Finds the smoothed maximal within the significant region R.
If area of R is too small it returns the last local correlation. Otherwise,
returns the maximum within significant_connected_region.
Parameters
----------
sig_connect: ndarray
A binary matrix with 1's indicating the significant region.
stat_mgc_map: ndarray
All local correlations within `[-1, 1]`.
Returns
-------
stat : float
The sample MGC statistic within `[-1, 1]`.
opt_scale: (float, float)
The estimated optimal scale as an `(x, y)` pair.
"""
m, n = stat_mgc_map.shape
# the global scale at is the statistic calculated at maximial nearest
# neighbors. By default, statistic and optimal scale are global.
stat = stat_mgc_map[m - 1][n - 1]
opt_scale = [m, n]
if np.linalg.norm(sig_connect) != 0:
# proceed only when the connected region's area is sufficiently large
# 0.02 is simply an empirical threshold, this can be set to 0.01 or 0.05
# with varying levels of performance
if np.sum(sig_connect) >= np.ceil(0.02 * max(m, n)) * min(m, n):
max_corr = max(stat_mgc_map[sig_connect])
# find all scales within significant_connected_region that maximize
# the local correlation
max_corr_index = np.where((stat_mgc_map >= max_corr) & sig_connect)
if max_corr >= stat:
stat = max_corr
k, l = max_corr_index
one_d_indices = k * n + l # 2D to 1D indexing
k = np.max(one_d_indices) // n
l = np.max(one_d_indices) % n
opt_scale = [k+1, l+1] # adding 1s to match R indexing
return stat, opt_scale
def _two_sample_transform(u, v):
"""
Helper function that concatenates x and y for two sample MGC stat. See
above for use.
Parameters
----------
u, v : ndarray
`u` and `v` have shapes `(n, p)` and `(m, p)`.
Returns
-------
x : ndarray
Concatenate `u` and `v` along the `axis = 0`. `x` thus has shape
`(2n, p)`.
y : ndarray
Label matrix for `x` where 0 refers to samples that comes from `u` and
1 refers to samples that come from `v`. `y` thus has shape `(2n, 1)`.
"""
nx = u.shape[0]
ny = v.shape[0]
x = np.concatenate([u, v], axis=0)
y = np.concatenate([np.zeros(nx), np.ones(ny)], axis=0).reshape(-1, 1)
return x, y
#####################################
# INFERENTIAL STATISTICS #
#####################################
Ttest_1sampResult = namedtuple('Ttest_1sampResult', ('statistic', 'pvalue'))
def ttest_1samp(a, popmean, axis=0, nan_policy='propagate',
alternative="two-sided"):
"""
Calculate the T-test for the mean of ONE group of scores.
This is a two-sided test for the null hypothesis that the expected value
(mean) of a sample of independent observations `a` is equal to the given
population mean, `popmean`.
Parameters
----------
a : array_like
Sample observation.
popmean : float or array_like
Expected value in null hypothesis. If array_like, then it must have the
same shape as `a` excluding the axis dimension.
axis : int or None, optional
Axis along which to compute test; default is 0. If None, compute over
the whole array `a`.
nan_policy : {'propagate', 'raise', 'omit'}, optional
Defines how to handle when input contains nan.
The following options are available (default is 'propagate'):
* 'propagate': returns nan
* 'raise': throws an error
* 'omit': performs the calculations ignoring nan values
alternative : {'two-sided', 'less', 'greater'}, optional
Defines the alternative hypothesis.
The following options are available (default is 'two-sided'):
* 'two-sided'
* 'less': one-sided
* 'greater': one-sided
.. versionadded:: 1.6.0
Returns
-------
statistic : float or array
t-statistic.
pvalue : float or array
Two-sided p-value.
Examples
--------
>>> from scipy import stats
>>> np.random.seed(7654567) # fix seed to get the same result
>>> rvs = stats.norm.rvs(loc=5, scale=10, size=(50,2))
Test if mean of random sample is equal to true mean, and different mean.
We reject the null hypothesis in the second case and don't reject it in
the first case.
>>> stats.ttest_1samp(rvs,5.0)
(array([-0.68014479, -0.04323899]), array([ 0.49961383, 0.96568674]))
>>> stats.ttest_1samp(rvs,0.0)
(array([ 2.77025808, 4.11038784]), array([ 0.00789095, 0.00014999]))
Examples using axis and non-scalar dimension for population mean.
>>> result = stats.ttest_1samp(rvs, [5.0, 0.0])
>>> result.statistic
array([-0.68014479, 4.11038784]),
>>> result.pvalue
array([4.99613833e-01, 1.49986458e-04])
>>> result = stats.ttest_1samp(rvs.T, [5.0, 0.0], axis=1)
>>> result.statistic
array([-0.68014479, 4.11038784])
>>> result.pvalue
array([4.99613833e-01, 1.49986458e-04])
>>> result = stats.ttest_1samp(rvs, [[5.0], [0.0]])
>>> result.statistic
array([[-0.68014479, -0.04323899],
[ 2.77025808, 4.11038784]])
>>> result.pvalue
array([[4.99613833e-01, 9.65686743e-01],
[7.89094663e-03, 1.49986458e-04]])
"""
a, axis = _chk_asarray(a, axis)
contains_nan, nan_policy = _contains_nan(a, nan_policy)
if contains_nan and nan_policy == 'omit':
if alternative != 'two-sided':
raise ValueError("nan-containing/masked inputs with "
"nan_policy='omit' are currently not "
"supported by one-sided alternatives.")
a = ma.masked_invalid(a)
return mstats_basic.ttest_1samp(a, popmean, axis)
n = a.shape[axis]
df = n - 1
d = np.mean(a, axis) - popmean
v = np.var(a, axis, ddof=1)
denom = np.sqrt(v / n)
with np.errstate(divide='ignore', invalid='ignore'):
t = np.divide(d, denom)
t, prob = _ttest_finish(df, t, alternative)
return Ttest_1sampResult(t, prob)
def _ttest_finish(df, t, alternative):
"""Common code between all 3 t-test functions."""
if alternative == 'less':
prob = distributions.t.cdf(t, df)
elif alternative == 'greater':
prob = distributions.t.sf(t, df)
elif alternative == 'two-sided':
prob = 2 * distributions.t.sf(np.abs(t), df)
else:
raise ValueError("alternative must be "
"'less', 'greater' or 'two-sided'")
if t.ndim == 0:
t = t[()]
return t, prob
def _ttest_ind_from_stats(mean1, mean2, denom, df, alternative):
d = mean1 - mean2
with np.errstate(divide='ignore', invalid='ignore'):
t = np.divide(d, denom)
t, prob = _ttest_finish(df, t, alternative)
return (t, prob)
def _unequal_var_ttest_denom(v1, n1, v2, n2):
vn1 = v1 / n1
vn2 = v2 / n2
with np.errstate(divide='ignore', invalid='ignore'):
df = (vn1 + vn2)**2 / (vn1**2 / (n1 - 1) + vn2**2 / (n2 - 1))
# If df is undefined, variances are zero (assumes n1 > 0 & n2 > 0).
# Hence it doesn't matter what df is as long as it's not NaN.
df = np.where(np.isnan(df), 1, df)
denom = np.sqrt(vn1 + vn2)
return df, denom
def _equal_var_ttest_denom(v1, n1, v2, n2):
df = n1 + n2 - 2.0
svar = ((n1 - 1) * v1 + (n2 - 1) * v2) / df
denom = np.sqrt(svar * (1.0 / n1 + 1.0 / n2))
return df, denom
Ttest_indResult = namedtuple('Ttest_indResult', ('statistic', 'pvalue'))
def ttest_ind_from_stats(mean1, std1, nobs1, mean2, std2, nobs2,
equal_var=True, alternative="two-sided"):
r"""
T-test for means of two independent samples from descriptive statistics.
This is a two-sided test for the null hypothesis that two independent
samples have identical average (expected) values.
Parameters
----------
mean1 : array_like
The mean(s) of sample 1.
std1 : array_like
The standard deviation(s) of sample 1.
nobs1 : array_like
The number(s) of observations of sample 1.
mean2 : array_like
The mean(s) of sample 2.
std2 : array_like
The standard deviations(s) of sample 2.
nobs2 : array_like
The number(s) of observations of sample 2.
equal_var : bool, optional
If True (default), perform a standard independent 2 sample test
that assumes equal population variances [1]_.
If False, perform Welch's t-test, which does not assume equal
population variance [2]_.
alternative : {'two-sided', 'less', 'greater'}, optional
Defines the alternative hypothesis.
The following options are available (default is 'two-sided'):
* 'two-sided'
* 'less': one-sided
* 'greater': one-sided
.. versionadded:: 1.6.0
Returns
-------
statistic : float or array
The calculated t-statistics.
pvalue : float or array
The two-tailed p-value.
See Also
--------
scipy.stats.ttest_ind
Notes
-----
.. versionadded:: 0.16.0
References
----------
.. [1] https://en.wikipedia.org/wiki/T-test#Independent_two-sample_t-test
.. [2] https://en.wikipedia.org/wiki/Welch%27s_t-test
Examples
--------
Suppose we have the summary data for two samples, as follows::
Sample Sample
Size Mean Variance
Sample 1 13 15.0 87.5
Sample 2 11 12.0 39.0
Apply the t-test to this data (with the assumption that the population
variances are equal):
>>> from scipy.stats import ttest_ind_from_stats
>>> ttest_ind_from_stats(mean1=15.0, std1=np.sqrt(87.5), nobs1=13,
... mean2=12.0, std2=np.sqrt(39.0), nobs2=11)
Ttest_indResult(statistic=0.9051358093310269, pvalue=0.3751996797581487)
For comparison, here is the data from which those summary statistics
were taken. With this data, we can compute the same result using
`scipy.stats.ttest_ind`:
>>> a = np.array([1, 3, 4, 6, 11, 13, 15, 19, 22, 24, 25, 26, 26])
>>> b = np.array([2, 4, 6, 9, 11, 13, 14, 15, 18, 19, 21])
>>> from scipy.stats import ttest_ind
>>> ttest_ind(a, b)
Ttest_indResult(statistic=0.905135809331027, pvalue=0.3751996797581486)
Suppose we instead have binary data and would like to apply a t-test to
compare the proportion of 1s in two independent groups::
Number of Sample Sample
Size ones Mean Variance
Sample 1 150 30 0.2 0.16
Sample 2 200 45 0.225 0.174375
The sample mean :math:`\hat{p}` is the proportion of ones in the sample
and the variance for a binary observation is estimated by
:math:`\hat{p}(1-\hat{p})`.
>>> ttest_ind_from_stats(mean1=0.2, std1=np.sqrt(0.16), nobs1=150,
... mean2=0.225, std2=np.sqrt(0.17437), nobs2=200)
Ttest_indResult(statistic=-0.564327545549774, pvalue=0.5728947691244874)
For comparison, we could compute the t statistic and p-value using
arrays of 0s and 1s and `scipy.stat.ttest_ind`, as above.
>>> group1 = np.array([1]*30 + [0]*(150-30))
>>> group2 = np.array([1]*45 + [0]*(200-45))
>>> ttest_ind(group1, group2)
Ttest_indResult(statistic=-0.5627179589855622, pvalue=0.573989277115258)
"""
mean1 = np.asarray(mean1)
std1 = np.asarray(std1)
mean2 = np.asarray(mean2)
std2 = np.asarray(std2)
if equal_var:
df, denom = _equal_var_ttest_denom(std1**2, nobs1, std2**2, nobs2)
else:
df, denom = _unequal_var_ttest_denom(std1**2, nobs1,
std2**2, nobs2)
res = _ttest_ind_from_stats(mean1, mean2, denom, df, alternative)
return Ttest_indResult(*res)
def _ttest_nans(a, b, axis, namedtuple_type):
"""
Generate an array of `nan`, with shape determined by `a`, `b` and `axis`.
This function is used by ttest_ind and ttest_rel to create the return
value when one of the inputs has size 0.
The shapes of the arrays are determined by dropping `axis` from the
shapes of `a` and `b` and broadcasting what is left.
The return value is a named tuple of the type given in `namedtuple_type`.
Examples
--------
>>> a = np.zeros((9, 2))
>>> b = np.zeros((5, 1))
>>> _ttest_nans(a, b, 0, Ttest_indResult)
Ttest_indResult(statistic=array([nan, nan]), pvalue=array([nan, nan]))
>>> a = np.zeros((3, 0, 9))
>>> b = np.zeros((1, 10))
>>> stat, p = _ttest_nans(a, b, -1, Ttest_indResult)
>>> stat
array([], shape=(3, 0), dtype=float64)
>>> p
array([], shape=(3, 0), dtype=float64)
>>> a = np.zeros(10)
>>> b = np.zeros(7)
>>> _ttest_nans(a, b, 0, Ttest_indResult)
Ttest_indResult(statistic=nan, pvalue=nan)
"""
shp = _broadcast_shapes_with_dropped_axis(a, b, axis)
if len(shp) == 0:
t = np.nan
p = np.nan
else:
t = np.full(shp, fill_value=np.nan)
p = t.copy()
return namedtuple_type(t, p)
def ttest_ind(a, b, axis=0, equal_var=True, nan_policy='propagate',
permutations=None, random_state=None, alternative="two-sided"):
"""
Calculate the T-test for the means of *two independent* samples of scores.
This is a two-sided test for the null hypothesis that 2 independent samples
have identical average (expected) values. This test assumes that the
populations have identical variances by default.
Parameters
----------
a, b : array_like
The arrays must have the same shape, except in the dimension
corresponding to `axis` (the first, by default).
axis : int or None, optional
Axis along which to compute test. If None, compute over the whole
arrays, `a`, and `b`.
equal_var : bool, optional
If True (default), perform a standard independent 2 sample test
that assumes equal population variances [1]_.
If False, perform Welch's t-test, which does not assume equal
population variance [2]_.
.. versionadded:: 0.11.0
nan_policy : {'propagate', 'raise', 'omit'}, optional
Defines how to handle when input contains nan.
The following options are available (default is 'propagate'):
* 'propagate': returns nan
* 'raise': throws an error
* 'omit': performs the calculations ignoring nan values
The 'omit' option is not currently available for permutation tests or
one-sided asympyotic tests.
permutations : int or None (default), optional
The number of random permutations that will be used to estimate
p-values using a permutation test. If `permutations` equals or exceeds
the number of distinct permutations, an exact test is performed
instead (i.e. each distinct permutation is used exactly once).
If None (default), use the t-distribution to calculate p-values.
.. versionadded:: 1.7.0
random_state : int, RandomState, or Generator, optional
Pseudorandom number generator state used to generate permutations
(used only when `permutations` is not None).
.. versionadded:: 1.7.0
alternative : {'two-sided', 'less', 'greater'}, optional
Defines the alternative hypothesis.
The following options are available (default is 'two-sided'):
* 'two-sided'
* 'less': one-sided
* 'greater': one-sided
.. versionadded:: 1.6.0
Returns
-------
statistic : float or array
The calculated t-statistic.
pvalue : float or array
The two-tailed p-value.
Notes
-----
Suppose we observe two independent samples, e.g. flower petal lengths, and
we are considering whether the two samples were drawn from the same
population (e.g. the same species of flower or two species with similar
petal characteristics) or two different populations.
The t-test quantifies the difference between the arithmetic means
of the two samples. The p-value quantifies the probability of observing
as or more extreme values assuming the null hypothesis, that the
samples are drawn from populations with the same population means, is true.
A p-value larger than a chosen threshold (e.g. 5% or 1%) indicates that
our observation is not so unlikely to have occurred by chance. Therefore,
we do not reject the null hypothesis of equal population means.
If the p-value is smaller than our threshold, then we have evidence
against the null hypothesis of equal population means.
By default, the p-value is determined by comparing the t-statistic of the
observed data against a theoretical t-distribution, which assumes that the
populations are normally distributed.
When ``1 < permutations < factorial(n)``, where ``n`` is the total
number of data, the data are randomly assigned to either group `a`
or `b`, and the t-statistic is calculated. This process is performed
repeatedly (`permutation` times), generating a distribution of the
t-statistic under the null hypothesis, and the t-statistic of the observed
data is compared to this distribution to determine the p-value. When
``permutations >= factorial(n)``, an exact test is performed: the data are
permuted within and between the groups in each distinct way exactly once.
The permutation test can be computationally expensive and not necessarily
more accurate than the analytical test, but it does not make strong
assumptions about the shape of the underlying distribution.
References
----------
.. [1] https://en.wikipedia.org/wiki/T-test#Independent_two-sample_t-test
.. [2] https://en.wikipedia.org/wiki/Welch%27s_t-test
.. [3] http://en.wikipedia.org/wiki/Resampling_%28statistics%29
Examples
--------
>>> from scipy import stats
>>> np.random.seed(12345678)
Test with sample with identical means:
>>> rvs1 = stats.norm.rvs(loc=5, scale=10, size=500)
>>> rvs2 = stats.norm.rvs(loc=5, scale=10, size=500)
>>> stats.ttest_ind(rvs1, rvs2)
(0.26833823296239279, 0.78849443369564776)
>>> stats.ttest_ind(rvs1, rvs2, equal_var=False)
(0.26833823296239279, 0.78849452749500748)
`ttest_ind` underestimates p for unequal variances:
>>> rvs3 = stats.norm.rvs(loc=5, scale=20, size=500)
>>> stats.ttest_ind(rvs1, rvs3)
(-0.46580283298287162, 0.64145827413436174)
>>> stats.ttest_ind(rvs1, rvs3, equal_var=False)
(-0.46580283298287162, 0.64149646246569292)
When ``n1 != n2``, the equal variance t-statistic is no longer equal to the
unequal variance t-statistic:
>>> rvs4 = stats.norm.rvs(loc=5, scale=20, size=100)
>>> stats.ttest_ind(rvs1, rvs4)
(-0.99882539442782481, 0.3182832709103896)
>>> stats.ttest_ind(rvs1, rvs4, equal_var=False)
(-0.69712570584654099, 0.48716927725402048)
T-test with different means, variance, and n:
>>> rvs5 = stats.norm.rvs(loc=8, scale=20, size=100)
>>> stats.ttest_ind(rvs1, rvs5)
(-1.4679669854490653, 0.14263895620529152)
>>> stats.ttest_ind(rvs1, rvs5, equal_var=False)
(-0.94365973617132992, 0.34744170334794122)
When performing a permutation test, more permutations typically yields
more accurate results. Use a ``np.random.Generator`` to ensure
reproducibility:
>>> stats.ttest_ind(rvs1, rvs5, permutations=10000,
... random_state=np.random.default_rng(12345))
(-1.467966985449, 0.14)
"""
a, b, axis = _chk2_asarray(a, b, axis)
# check both a and b
cna, npa = _contains_nan(a, nan_policy)
cnb, npb = _contains_nan(b, nan_policy)
contains_nan = cna or cnb
if npa == 'omit' or npb == 'omit':
nan_policy = 'omit'
if contains_nan and nan_policy == 'omit':
if permutations or alternative != 'two-sided':
raise ValueError("nan-containing/masked inputs with "
"nan_policy='omit' are currently not "
"supported by permutation tests or one-sided"
"asymptotic tests.")
a = ma.masked_invalid(a)
b = ma.masked_invalid(b)
return mstats_basic.ttest_ind(a, b, axis, equal_var)
if a.size == 0 or b.size == 0:
return _ttest_nans(a, b, axis, Ttest_indResult)
if permutations:
if int(permutations) != permutations or permutations < 0:
raise ValueError("Permutations must be a positive integer.")
res = _permutation_ttest(a, b, permutations=permutations,
axis=axis, equal_var=equal_var,
nan_policy=nan_policy,
random_state=random_state,
alternative=alternative)
else:
v1 = np.var(a, axis, ddof=1)
v2 = np.var(b, axis, ddof=1)
n1 = a.shape[axis]
n2 = b.shape[axis]
if equal_var:
df, denom = _equal_var_ttest_denom(v1, n1, v2, n2)
else:
df, denom = _unequal_var_ttest_denom(v1, n1, v2, n2)
res = _ttest_ind_from_stats(np.mean(a, axis), np.mean(b, axis),
denom, df, alternative)
return Ttest_indResult(*res)
def _broadcast_concatenate(xs, axis):
"""Concatenate arrays along an axis with broadcasting"""
# move the axis we're concatenating along to the end
xs = [np.swapaxes(x, axis, -1) for x in xs]
# determine final shape of all but the last axis
shape = np.broadcast(*[x[..., 0] for x in xs]).shape
# broadcast along all but the last axis
xs = [np.broadcast_to(x, shape + (x.shape[-1],)) for x in xs]
# concatenate along last axis
res = np.concatenate(xs, axis = -1)
# move the last axis back to where it was
res = np.swapaxes(res, axis, -1)
return res
def _data_permutations(data, n, axis=-1, random_state=None):
"""Vectorized permutation of data, assumes `random_state` is already checked"""
random_state = check_random_state(random_state)
if axis < 0: # we'll be adding a new dimension at the end
axis = data.ndim + axis
# prepare permutation indices
m = data.shape[axis]
n_max = float_factorial(m) # number of distinct permutations
if n < n_max:
indices = np.array([random_state.permutation(m) for i in range(n)]).T
else:
n = n_max
indices = np.array(list(permutations(range(m)))).T
data = data.swapaxes(axis, -1) # so we can index along a new dimension
data = data[..., indices] # generate permutations
data = data.swapaxes(-2, axis) # restore original axis order
data = np.moveaxis(data, -1, 0) # permutations indexed along axis 0
return data, n
def _calc_t_stat(a, b, equal_var, axis=-1):
"""Calculate the t statistic along the given dimension"""
na = a.shape[axis]
nb = b.shape[axis]
avg_a = np.mean(a, axis=axis)
avg_b = np.mean(b, axis=axis)
var_a = np.var(a, axis=axis, ddof=1)
var_b = np.var(b, axis=axis, ddof=1)
if not equal_var:
denom = _unequal_var_ttest_denom(var_a, na, var_b, nb)[1]
else:
denom = _equal_var_ttest_denom(var_a, na, var_b, nb)[1]
return (avg_a-avg_b)/denom
def _permutation_ttest(a, b, permutations, axis=0, equal_var=True,
nan_policy='propagate', random_state=None,
alternative="two-sided"):
"""
Calculates the T-test for the means of TWO INDEPENDENT samples of scores
using permutation methods
This test is similar to `stats.ttest_ind`, except it doesn't rely on an
approximate normality assumption since it uses a permutation test.
This function is only called from ttest_ind when permutations is not None.
Parameters
----------
a, b : array_like
The arrays must be broadcastable, except along the dimension
corresponding to `axis` (the zeroth, by default).
axis : int, optional
The axis over which to operate on a and b.
permutations: int, optional
Number of permutations used to calculate p-value. If greater than or
equal to the number of distinct permutations, perform an exact test.
equal_var: bool, optional
If False, an equal variance (Welch's) t-test is conducted. Otherwise,
an ordinary t-test is conducted.
random_state : int, RandomState, or Generator, optional
Pseudorandom number generator state used for generating random
permutations.
Returns
-------
statistic : float or array
The calculated t-statistic.
pvalue : float or array
The two-tailed p-value.
"""
random_state = check_random_state(random_state)
t_stat_observed = _calc_t_stat(a, b, equal_var, axis=axis)
na = a.shape[axis]
mat = _broadcast_concatenate((a, b), axis=axis)
mat = np.moveaxis(mat, axis, -1)
mat_perm, permutations = _data_permutations(mat, n=permutations,
random_state=random_state)
a = mat_perm[..., :na]
b = mat_perm[..., na:]
t_stat = _calc_t_stat(a, b, equal_var)
compare = {"less": np.less_equal,
"greater": np.greater_equal,
"two-sided": lambda x, y: (x <= -np.abs(y)) | (x >= np.abs(y))}
# Calculate the p-values
cmps = compare[alternative](t_stat, t_stat_observed)
pvalues = cmps.sum(axis=0) / permutations
# nans propagate naturally in statistic calculation, but need to be
# propagated manually into pvalues
if nan_policy == 'propagate' and np.isnan(t_stat_observed).any():
if np.ndim(pvalues) == 0:
pvalues = np.float64(np.nan)
else:
pvalues[np.isnan(t_stat_observed)] = np.nan
return (t_stat_observed, pvalues)
def _get_len(a, axis, msg):
try:
n = a.shape[axis]
except IndexError:
raise np.AxisError(axis, a.ndim, msg) from None
return n
Ttest_relResult = namedtuple('Ttest_relResult', ('statistic', 'pvalue'))
def ttest_rel(a, b, axis=0, nan_policy='propagate', alternative="two-sided"):
"""
Calculate the t-test on TWO RELATED samples of scores, a and b.
This is a two-sided test for the null hypothesis that 2 related or
repeated samples have identical average (expected) values.
Parameters
----------
a, b : array_like
The arrays must have the same shape.
axis : int or None, optional
Axis along which to compute test. If None, compute over the whole
arrays, `a`, and `b`.
nan_policy : {'propagate', 'raise', 'omit'}, optional
Defines how to handle when input contains nan.
The following options are available (default is 'propagate'):
* 'propagate': returns nan
* 'raise': throws an error
* 'omit': performs the calculations ignoring nan values
alternative : {'two-sided', 'less', 'greater'}, optional
Defines the alternative hypothesis.
The following options are available (default is 'two-sided'):
* 'two-sided'
* 'less': one-sided
* 'greater': one-sided
.. versionadded:: 1.6.0
Returns
-------
statistic : float or array
t-statistic.
pvalue : float or array
Two-sided p-value.
Notes
-----
Examples for use are scores of the same set of student in
different exams, or repeated sampling from the same units. The
test measures whether the average score differs significantly
across samples (e.g. exams). If we observe a large p-value, for
example greater than 0.05 or 0.1 then we cannot reject the null
hypothesis of identical average scores. If the p-value is smaller
than the threshold, e.g. 1%, 5% or 10%, then we reject the null
hypothesis of equal averages. Small p-values are associated with
large t-statistics.
References
----------
https://en.wikipedia.org/wiki/T-test#Dependent_t-test_for_paired_samples
Examples
--------
>>> from scipy import stats
>>> np.random.seed(12345678) # fix random seed to get same numbers
>>> rvs1 = stats.norm.rvs(loc=5,scale=10,size=500)
>>> rvs2 = (stats.norm.rvs(loc=5,scale=10,size=500) +
... stats.norm.rvs(scale=0.2,size=500))
>>> stats.ttest_rel(rvs1,rvs2)
(0.24101764965300962, 0.80964043445811562)
>>> rvs3 = (stats.norm.rvs(loc=8,scale=10,size=500) +
... stats.norm.rvs(scale=0.2,size=500))
>>> stats.ttest_rel(rvs1,rvs3)
(-3.9995108708727933, 7.3082402191726459e-005)
"""
a, b, axis = _chk2_asarray(a, b, axis)
cna, npa = _contains_nan(a, nan_policy)
cnb, npb = _contains_nan(b, nan_policy)
contains_nan = cna or cnb
if npa == 'omit' or npb == 'omit':
nan_policy = 'omit'
if contains_nan and nan_policy == 'omit':
if alternative != 'two-sided':
raise ValueError("nan-containing/masked inputs with "
"nan_policy='omit' are currently not "
"supported by one-sided alternatives.")
a = ma.masked_invalid(a)
b = ma.masked_invalid(b)
m = ma.mask_or(ma.getmask(a), ma.getmask(b))
aa = ma.array(a, mask=m, copy=True)
bb = ma.array(b, mask=m, copy=True)
return mstats_basic.ttest_rel(aa, bb, axis)
na = _get_len(a, axis, "first argument")
nb = _get_len(b, axis, "second argument")
if na != nb:
raise ValueError('unequal length arrays')
if na == 0:
return _ttest_nans(a, b, axis, Ttest_relResult)
n = a.shape[axis]
df = n - 1
d = (a - b).astype(np.float64)
v = np.var(d, axis, ddof=1)
dm = np.mean(d, axis)
denom = np.sqrt(v / n)
with np.errstate(divide='ignore', invalid='ignore'):
t = np.divide(dm, denom)
t, prob = _ttest_finish(df, t, alternative)
return Ttest_relResult(t, prob)
# Map from names to lambda_ values used in power_divergence().
_power_div_lambda_names = {
"pearson": 1,
"log-likelihood": 0,
"freeman-tukey": -0.5,
"mod-log-likelihood": -1,
"neyman": -2,
"cressie-read": 2/3,
}
def _count(a, axis=None):
"""
Count the number of non-masked elements of an array.
This function behaves like np.ma.count(), but is much faster
for ndarrays.
"""
if hasattr(a, 'count'):
num = a.count(axis=axis)
if isinstance(num, np.ndarray) and num.ndim == 0:
# In some cases, the `count` method returns a scalar array (e.g.
# np.array(3)), but we want a plain integer.
num = int(num)
else:
if axis is None:
num = a.size
else:
num = a.shape[axis]
return num
def _m_broadcast_to(a, shape):
if np.ma.isMaskedArray(a):
return np.ma.masked_array(np.broadcast_to(a, shape),
mask=np.broadcast_to(a.mask, shape))
return np.broadcast_to(a, shape, subok=True)
Power_divergenceResult = namedtuple('Power_divergenceResult',
('statistic', 'pvalue'))
def power_divergence(f_obs, f_exp=None, ddof=0, axis=0, lambda_=None):
"""
Cressie-Read power divergence statistic and goodness of fit test.
This function tests the null hypothesis that the categorical data
has the given frequencies, using the Cressie-Read power divergence
statistic.
Parameters
----------
f_obs : array_like
Observed frequencies in each category.
f_exp : array_like, optional
Expected frequencies in each category. By default the categories are
assumed to be equally likely.
ddof : int, optional
"Delta degrees of freedom": adjustment to the degrees of freedom
for the p-value. The p-value is computed using a chi-squared
distribution with ``k - 1 - ddof`` degrees of freedom, where `k`
is the number of observed frequencies. The default value of `ddof`
is 0.
axis : int or None, optional
The axis of the broadcast result of `f_obs` and `f_exp` along which to
apply the test. If axis is None, all values in `f_obs` are treated
as a single data set. Default is 0.
lambda_ : float or str, optional
The power in the Cressie-Read power divergence statistic. The default
is 1. For convenience, `lambda_` may be assigned one of the following
strings, in which case the corresponding numerical value is used::
String Value Description
"pearson" 1 Pearson's chi-squared statistic.
In this case, the function is
equivalent to `stats.chisquare`.
"log-likelihood" 0 Log-likelihood ratio. Also known as
the G-test [3]_.
"freeman-tukey" -1/2 Freeman-Tukey statistic.
"mod-log-likelihood" -1 Modified log-likelihood ratio.
"neyman" -2 Neyman's statistic.
"cressie-read" 2/3 The power recommended in [5]_.
Returns
-------
statistic : float or ndarray
The Cressie-Read power divergence test statistic. The value is
a float if `axis` is None or if` `f_obs` and `f_exp` are 1-D.
pvalue : float or ndarray
The p-value of the test. The value is a float if `ddof` and the
return value `stat` are scalars.
See Also
--------
chisquare
Notes
-----
This test is invalid when the observed or expected frequencies in each
category are too small. A typical rule is that all of the observed
and expected frequencies should be at least 5.
Also, the sum of the observed and expected frequencies must be the same
for the test to be valid; `power_divergence` raises an error if the sums
do not agree within a relative tolerance of ``1e-8``.
When `lambda_` is less than zero, the formula for the statistic involves
dividing by `f_obs`, so a warning or error may be generated if any value
in `f_obs` is 0.
Similarly, a warning or error may be generated if any value in `f_exp` is
zero when `lambda_` >= 0.
The default degrees of freedom, k-1, are for the case when no parameters
of the distribution are estimated. If p parameters are estimated by
efficient maximum likelihood then the correct degrees of freedom are
k-1-p. If the parameters are estimated in a different way, then the
dof can be between k-1-p and k-1. However, it is also possible that
the asymptotic distribution is not a chisquare, in which case this
test is not appropriate.
This function handles masked arrays. If an element of `f_obs` or `f_exp`
is masked, then data at that position is ignored, and does not count
towards the size of the data set.
.. versionadded:: 0.13.0
References
----------
.. [1] Lowry, Richard. "Concepts and Applications of Inferential
Statistics". Chapter 8.
https://web.archive.org/web/20171015035606/http://faculty.vassar.edu/lowry/ch8pt1.html
.. [2] "Chi-squared test", https://en.wikipedia.org/wiki/Chi-squared_test
.. [3] "G-test", https://en.wikipedia.org/wiki/G-test
.. [4] Sokal, R. R. and Rohlf, F. J. "Biometry: the principles and
practice of statistics in biological research", New York: Freeman
(1981)
.. [5] Cressie, N. and Read, T. R. C., "Multinomial Goodness-of-Fit
Tests", J. Royal Stat. Soc. Series B, Vol. 46, No. 3 (1984),
pp. 440-464.
Examples
--------
(See `chisquare` for more examples.)
When just `f_obs` is given, it is assumed that the expected frequencies
are uniform and given by the mean of the observed frequencies. Here we
perform a G-test (i.e. use the log-likelihood ratio statistic):
>>> from scipy.stats import power_divergence
>>> power_divergence([16, 18, 16, 14, 12, 12], lambda_='log-likelihood')
(2.006573162632538, 0.84823476779463769)
The expected frequencies can be given with the `f_exp` argument:
>>> power_divergence([16, 18, 16, 14, 12, 12],
... f_exp=[16, 16, 16, 16, 16, 8],
... lambda_='log-likelihood')
(3.3281031458963746, 0.6495419288047497)
When `f_obs` is 2-D, by default the test is applied to each column.
>>> obs = np.array([[16, 18, 16, 14, 12, 12], [32, 24, 16, 28, 20, 24]]).T
>>> obs.shape
(6, 2)
>>> power_divergence(obs, lambda_="log-likelihood")
(array([ 2.00657316, 6.77634498]), array([ 0.84823477, 0.23781225]))
By setting ``axis=None``, the test is applied to all data in the array,
which is equivalent to applying the test to the flattened array.
>>> power_divergence(obs, axis=None)
(23.31034482758621, 0.015975692534127565)
>>> power_divergence(obs.ravel())
(23.31034482758621, 0.015975692534127565)
`ddof` is the change to make to the default degrees of freedom.
>>> power_divergence([16, 18, 16, 14, 12, 12], ddof=1)
(2.0, 0.73575888234288467)
The calculation of the p-values is done by broadcasting the
test statistic with `ddof`.
>>> power_divergence([16, 18, 16, 14, 12, 12], ddof=[0,1,2])
(2.0, array([ 0.84914504, 0.73575888, 0.5724067 ]))
`f_obs` and `f_exp` are also broadcast. In the following, `f_obs` has
shape (6,) and `f_exp` has shape (2, 6), so the result of broadcasting
`f_obs` and `f_exp` has shape (2, 6). To compute the desired chi-squared
statistics, we must use ``axis=1``:
>>> power_divergence([16, 18, 16, 14, 12, 12],
... f_exp=[[16, 16, 16, 16, 16, 8],
... [8, 20, 20, 16, 12, 12]],
... axis=1)
(array([ 3.5 , 9.25]), array([ 0.62338763, 0.09949846]))
"""
# Convert the input argument `lambda_` to a numerical value.
if isinstance(lambda_, str):
if lambda_ not in _power_div_lambda_names:
names = repr(list(_power_div_lambda_names.keys()))[1:-1]
raise ValueError("invalid string for lambda_: {0!r}. Valid strings "
"are {1}".format(lambda_, names))
lambda_ = _power_div_lambda_names[lambda_]
elif lambda_ is None:
lambda_ = 1
f_obs = np.asanyarray(f_obs)
f_obs_float = f_obs.astype(np.float64)
if f_exp is not None:
f_exp = np.asanyarray(f_exp)
bshape = _broadcast_shapes(f_obs_float.shape, f_exp.shape)
f_obs_float = _m_broadcast_to(f_obs_float, bshape)
f_exp = _m_broadcast_to(f_exp, bshape)
rtol = 1e-8 # to pass existing tests
with np.errstate(invalid='ignore'):
f_obs_sum = f_obs_float.sum(axis=axis)
f_exp_sum = f_exp.sum(axis=axis)
relative_diff = (np.abs(f_obs_sum - f_exp_sum) /
np.minimum(f_obs_sum, f_exp_sum))
diff_gt_tol = (relative_diff > rtol).any()
if diff_gt_tol:
msg = (f"For each axis slice, the sum of the observed "
f"frequencies must agree with the sum of the "
f"expected frequencies to a relative tolerance "
f"of {rtol}, but the percent differences are:\n"
f"{relative_diff}")
raise ValueError(msg)
else:
# Ignore 'invalid' errors so the edge case of a data set with length 0
# is handled without spurious warnings.
with np.errstate(invalid='ignore'):
f_exp = f_obs.mean(axis=axis, keepdims=True)
# `terms` is the array of terms that are summed along `axis` to create
# the test statistic. We use some specialized code for a few special
# cases of lambda_.
if lambda_ == 1:
# Pearson's chi-squared statistic
terms = (f_obs_float - f_exp)**2 / f_exp
elif lambda_ == 0:
# Log-likelihood ratio (i.e. G-test)
terms = 2.0 * special.xlogy(f_obs, f_obs / f_exp)
elif lambda_ == -1:
# Modified log-likelihood ratio
terms = 2.0 * special.xlogy(f_exp, f_exp / f_obs)
else:
# General Cressie-Read power divergence.
terms = f_obs * ((f_obs / f_exp)**lambda_ - 1)
terms /= 0.5 * lambda_ * (lambda_ + 1)
stat = terms.sum(axis=axis)
num_obs = _count(terms, axis=axis)
ddof = asarray(ddof)
p = distributions.chi2.sf(stat, num_obs - 1 - ddof)
return Power_divergenceResult(stat, p)
def chisquare(f_obs, f_exp=None, ddof=0, axis=0):
"""
Calculate a one-way chi-square test.
The chi-square test tests the null hypothesis that the categorical data
has the given frequencies.
Parameters
----------
f_obs : array_like
Observed frequencies in each category.
f_exp : array_like, optional
Expected frequencies in each category. By default the categories are
assumed to be equally likely.
ddof : int, optional
"Delta degrees of freedom": adjustment to the degrees of freedom
for the p-value. The p-value is computed using a chi-squared
distribution with ``k - 1 - ddof`` degrees of freedom, where `k`
is the number of observed frequencies. The default value of `ddof`
is 0.
axis : int or None, optional
The axis of the broadcast result of `f_obs` and `f_exp` along which to
apply the test. If axis is None, all values in `f_obs` are treated
as a single data set. Default is 0.
Returns
-------
chisq : float or ndarray
The chi-squared test statistic. The value is a float if `axis` is
None or `f_obs` and `f_exp` are 1-D.
p : float or ndarray
The p-value of the test. The value is a float if `ddof` and the
return value `chisq` are scalars.
See Also
--------
scipy.stats.power_divergence
Notes
-----
This test is invalid when the observed or expected frequencies in each
category are too small. A typical rule is that all of the observed
and expected frequencies should be at least 5.
Also, the sum of the observed and expected frequencies must be the same
for the test to be valid; `chisquare` raises an error if the sums do not
agree within a relative tolerance of ``1e-8``.
The default degrees of freedom, k-1, are for the case when no parameters
of the distribution are estimated. If p parameters are estimated by
efficient maximum likelihood then the correct degrees of freedom are
k-1-p. If the parameters are estimated in a different way, then the
dof can be between k-1-p and k-1. However, it is also possible that
the asymptotic distribution is not chi-square, in which case this test
is not appropriate.
References
----------
.. [1] Lowry, Richard. "Concepts and Applications of Inferential
Statistics". Chapter 8.
https://web.archive.org/web/20171022032306/http://vassarstats.net:80/textbook/ch8pt1.html
.. [2] "Chi-squared test", https://en.wikipedia.org/wiki/Chi-squared_test
Examples
--------
When just `f_obs` is given, it is assumed that the expected frequencies
are uniform and given by the mean of the observed frequencies.
>>> from scipy.stats import chisquare
>>> chisquare([16, 18, 16, 14, 12, 12])
(2.0, 0.84914503608460956)
With `f_exp` the expected frequencies can be given.
>>> chisquare([16, 18, 16, 14, 12, 12], f_exp=[16, 16, 16, 16, 16, 8])
(3.5, 0.62338762774958223)
When `f_obs` is 2-D, by default the test is applied to each column.
>>> obs = np.array([[16, 18, 16, 14, 12, 12], [32, 24, 16, 28, 20, 24]]).T
>>> obs.shape
(6, 2)
>>> chisquare(obs)
(array([ 2. , 6.66666667]), array([ 0.84914504, 0.24663415]))
By setting ``axis=None``, the test is applied to all data in the array,
which is equivalent to applying the test to the flattened array.
>>> chisquare(obs, axis=None)
(23.31034482758621, 0.015975692534127565)
>>> chisquare(obs.ravel())
(23.31034482758621, 0.015975692534127565)
`ddof` is the change to make to the default degrees of freedom.
>>> chisquare([16, 18, 16, 14, 12, 12], ddof=1)
(2.0, 0.73575888234288467)
The calculation of the p-values is done by broadcasting the
chi-squared statistic with `ddof`.
>>> chisquare([16, 18, 16, 14, 12, 12], ddof=[0,1,2])
(2.0, array([ 0.84914504, 0.73575888, 0.5724067 ]))
`f_obs` and `f_exp` are also broadcast. In the following, `f_obs` has
shape (6,) and `f_exp` has shape (2, 6), so the result of broadcasting
`f_obs` and `f_exp` has shape (2, 6). To compute the desired chi-squared
statistics, we use ``axis=1``:
>>> chisquare([16, 18, 16, 14, 12, 12],
... f_exp=[[16, 16, 16, 16, 16, 8], [8, 20, 20, 16, 12, 12]],
... axis=1)
(array([ 3.5 , 9.25]), array([ 0.62338763, 0.09949846]))
"""
return power_divergence(f_obs, f_exp=f_exp, ddof=ddof, axis=axis,
lambda_="pearson")
KstestResult = namedtuple('KstestResult', ('statistic', 'pvalue'))
def _compute_dplus(cdfvals):
"""Computes D+ as used in the Kolmogorov-Smirnov test.
Parameters
----------
cdfvals: array_like
Sorted array of CDF values between 0 and 1
Returns
-------
Maximum distance of the CDF values below Uniform(0, 1)
"""
n = len(cdfvals)
return (np.arange(1.0, n + 1) / n - cdfvals).max()
def _compute_dminus(cdfvals):
"""Computes D- as used in the Kolmogorov-Smirnov test.
Parameters
----------
cdfvals: array_like
Sorted array of CDF values between 0 and 1
Returns
-------
Maximum distance of the CDF values above Uniform(0, 1)
"""
n = len(cdfvals)
return (cdfvals - np.arange(0.0, n)/n).max()
def ks_1samp(x, cdf, args=(), alternative='two-sided', mode='auto'):
"""
Performs the Kolmogorov-Smirnov test for goodness of fit.
This performs a test of the distribution F(x) of an observed
random variable against a given distribution G(x). Under the null
hypothesis, the two distributions are identical, F(x)=G(x). The
alternative hypothesis can be either 'two-sided' (default), 'less'
or 'greater'. The KS test is only valid for continuous distributions.
Parameters
----------
x : array_like
a 1-D array of observations of iid random variables.
cdf : callable
callable used to calculate the cdf.
args : tuple, sequence, optional
Distribution parameters, used with `cdf`.
alternative : {'two-sided', 'less', 'greater'}, optional
Defines the alternative hypothesis.
The following options are available (default is 'two-sided'):
* 'two-sided'
* 'less': one-sided, see explanation in Notes
* 'greater': one-sided, see explanation in Notes
mode : {'auto', 'exact', 'approx', 'asymp'}, optional
Defines the distribution used for calculating the p-value.
The following options are available (default is 'auto'):
* 'auto' : selects one of the other options.
* 'exact' : uses the exact distribution of test statistic.
* 'approx' : approximates the two-sided probability with twice the one-sided probability
* 'asymp': uses asymptotic distribution of test statistic
Returns
-------
statistic : float
KS test statistic, either D, D+ or D- (depending on the value of 'alternative')
pvalue : float
One-tailed or two-tailed p-value.
See Also
--------
ks_2samp, kstest
Notes
-----
In the one-sided test, the alternative is that the empirical
cumulative distribution function of the random variable is "less"
or "greater" than the cumulative distribution function G(x) of the
hypothesis, ``F(x)<=G(x)``, resp. ``F(x)>=G(x)``.
Examples
--------
>>> from scipy import stats
>>> x = np.linspace(-15, 15, 9)
>>> stats.ks_1samp(x, stats.norm.cdf)
(0.44435602715924361, 0.038850142705171065)
>>> np.random.seed(987654321) # set random seed to get the same result
>>> stats.ks_1samp(stats.norm.rvs(size=100), stats.norm.cdf)
(0.058352892479417884, 0.8653960860778898)
*Test against one-sided alternative hypothesis*
Shift distribution to larger values, so that `` CDF(x) < norm.cdf(x)``:
>>> np.random.seed(987654321)
>>> x = stats.norm.rvs(loc=0.2, size=100)
>>> stats.ks_1samp(x, stats.norm.cdf, alternative='less')
(0.12464329735846891, 0.040989164077641749)
Reject equal distribution against alternative hypothesis: less
>>> stats.ks_1samp(x, stats.norm.cdf, alternative='greater')
(0.0072115233216311081, 0.98531158590396395)
Don't reject equal distribution against alternative hypothesis: greater
>>> stats.ks_1samp(x, stats.norm.cdf)
(0.12464329735846891, 0.08197335233541582)
Don't reject equal distribution against alternative hypothesis: two-sided
*Testing t distributed random variables against normal distribution*
With 100 degrees of freedom the t distribution looks close to the normal
distribution, and the K-S test does not reject the hypothesis that the
sample came from the normal distribution:
>>> np.random.seed(987654321)
>>> stats.ks_1samp(stats.t.rvs(100,size=100), stats.norm.cdf)
(0.072018929165471257, 0.6505883498379312)
With 3 degrees of freedom the t distribution looks sufficiently different
from the normal distribution, that we can reject the hypothesis that the
sample came from the normal distribution at the 10% level:
>>> np.random.seed(987654321)
>>> stats.ks_1samp(stats.t.rvs(3,size=100), stats.norm.cdf)
(0.131016895759829, 0.058826222555312224)
"""
alternative = {'t': 'two-sided', 'g': 'greater', 'l': 'less'}.get(
alternative.lower()[0], alternative)
if alternative not in ['two-sided', 'greater', 'less']:
raise ValueError("Unexpected alternative %s" % alternative)
if np.ma.is_masked(x):
x = x.compressed()
N = len(x)
x = np.sort(x)
cdfvals = cdf(x, *args)
if alternative == 'greater':
Dplus = _compute_dplus(cdfvals)
return KstestResult(Dplus, distributions.ksone.sf(Dplus, N))
if alternative == 'less':
Dminus = _compute_dminus(cdfvals)
return KstestResult(Dminus, distributions.ksone.sf(Dminus, N))
# alternative == 'two-sided':
Dplus = _compute_dplus(cdfvals)
Dminus = _compute_dminus(cdfvals)
D = np.max([Dplus, Dminus])
if mode == 'auto': # Always select exact
mode = 'exact'
if mode == 'exact':
prob = distributions.kstwo.sf(D, N)
elif mode == 'asymp':
prob = distributions.kstwobign.sf(D * np.sqrt(N))
else:
# mode == 'approx'
prob = 2 * distributions.ksone.sf(D, N)
prob = np.clip(prob, 0, 1)
return KstestResult(D, prob)
Ks_2sampResult = KstestResult
def _compute_prob_inside_method(m, n, g, h):
"""
Count the proportion of paths that stay strictly inside two diagonal lines.
Parameters
----------
m : integer
m > 0
n : integer
n > 0
g : integer
g is greatest common divisor of m and n
h : integer
0 <= h <= lcm(m,n)
Returns
-------
p : float
The proportion of paths that stay inside the two lines.
Count the integer lattice paths from (0, 0) to (m, n) which satisfy
|x/m - y/n| < h / lcm(m, n).
The paths make steps of size +1 in either positive x or positive y directions.
We generally follow Hodges' treatment of Drion/Gnedenko/Korolyuk.
Hodges, J.L. Jr.,
"The Significance Probability of the Smirnov Two-Sample Test,"
Arkiv fiur Matematik, 3, No. 43 (1958), 469-86.
"""
# Probability is symmetrical in m, n. Computation below uses m >= n.
if m < n:
m, n = n, m
mg = m // g
ng = n // g
# Count the integer lattice paths from (0, 0) to (m, n) which satisfy
# |nx/g - my/g| < h.
# Compute matrix A such that:
# A(x, 0) = A(0, y) = 1
# A(x, y) = A(x, y-1) + A(x-1, y), for x,y>=1, except that
# A(x, y) = 0 if |x/m - y/n|>= h
# Probability is A(m, n)/binom(m+n, n)
# Optimizations exist for m==n, m==n*p.
# Only need to preserve a single column of A, and only a sliding window of it.
# minj keeps track of the slide.
minj, maxj = 0, min(int(np.ceil(h / mg)), n + 1)
curlen = maxj - minj
# Make a vector long enough to hold maximum window needed.
lenA = min(2 * maxj + 2, n + 1)
# This is an integer calculation, but the entries are essentially
# binomial coefficients, hence grow quickly.
# Scaling after each column is computed avoids dividing by a
# large binomial coefficent at the end, but is not sufficient to avoid
# the large dyanamic range which appears during the calculation.
# Instead we rescale based on the magnitude of the right most term in
# the column and keep track of an exponent separately and apply
# it at the end of the calculation. Similarly when multiplying by
# the binomial coefficint
dtype = np.float64
A = np.zeros(lenA, dtype=dtype)
# Initialize the first column
A[minj:maxj] = 1
expnt = 0
for i in range(1, m + 1):
# Generate the next column.
# First calculate the sliding window
lastminj, lastlen = minj, curlen
minj = max(int(np.floor((ng * i - h) / mg)) + 1, 0)
minj = min(minj, n)
maxj = min(int(np.ceil((ng * i + h) / mg)), n + 1)
if maxj <= minj:
return 0
# Now fill in the values
A[0:maxj - minj] = np.cumsum(A[minj - lastminj:maxj - lastminj])
curlen = maxj - minj
if lastlen > curlen:
# Set some carried-over elements to 0
A[maxj - minj:maxj - minj + (lastlen - curlen)] = 0
# Rescale if the right most value is over 2**900
val = A[maxj - minj - 1]
_, valexpt = math.frexp(val)
if valexpt > 900:
# Scaling to bring down to about 2**800 appears
# sufficient for sizes under 10000.
valexpt -= 800
A = np.ldexp(A, -valexpt)
expnt += valexpt
val = A[maxj - minj - 1]
# Now divide by the binomial (m+n)!/m!/n!
for i in range(1, n + 1):
val = (val * i) / (m + i)
_, valexpt = math.frexp(val)
if valexpt < -128:
val = np.ldexp(val, -valexpt)
expnt += valexpt
# Finally scale if needed.
return np.ldexp(val, expnt)
def _compute_prob_outside_square(n, h):
"""
Compute the proportion of paths that pass outside the two diagonal lines.
Parameters
----------
n : integer
n > 0
h : integer
0 <= h <= n
Returns
-------
p : float
The proportion of paths that pass outside the lines x-y = +/-h.
"""
# Compute Pr(D_{n,n} >= h/n)
# Prob = 2 * ( binom(2n, n-h) - binom(2n, n-2a) + binom(2n, n-3a) - ... ) / binom(2n, n)
# This formulation exhibits subtractive cancellation.
# Instead divide each term by binom(2n, n), then factor common terms
# and use a Horner-like algorithm
# P = 2 * A0 * (1 - A1*(1 - A2*(1 - A3*(1 - A4*(...)))))
P = 0.0
k = int(np.floor(n / h))
while k >= 0:
p1 = 1.0
# Each of the Ai terms has numerator and denominator with h simple terms.
for j in range(h):
p1 = (n - k * h - j) * p1 / (n + k * h + j + 1)
P = p1 * (1.0 - P)
k -= 1
return 2 * P
def _count_paths_outside_method(m, n, g, h):
"""
Count the number of paths that pass outside the specified diagonal.
Parameters
----------
m : integer
m > 0
n : integer
n > 0
g : integer
g is greatest common divisor of m and n
h : integer
0 <= h <= lcm(m,n)
Returns
-------
p : float
The number of paths that go low.
The calculation may overflow - check for a finite answer.
Raises
------
FloatingPointError: Raised if the intermediate computation goes outside
the range of a float.
Notes
-----
Count the integer lattice paths from (0, 0) to (m, n), which at some
point (x, y) along the path, satisfy:
m*y <= n*x - h*g
The paths make steps of size +1 in either positive x or positive y directions.
We generally follow Hodges' treatment of Drion/Gnedenko/Korolyuk.
Hodges, J.L. Jr.,
"The Significance Probability of the Smirnov Two-Sample Test,"
Arkiv fiur Matematik, 3, No. 43 (1958), 469-86.
"""
# Compute #paths which stay lower than x/m-y/n = h/lcm(m,n)
# B(x, y) = #{paths from (0,0) to (x,y) without previously crossing the boundary}
# = binom(x, y) - #{paths which already reached the boundary}
# Multiply by the number of path extensions going from (x, y) to (m, n)
# Sum.
# Probability is symmetrical in m, n. Computation below assumes m >= n.
if m < n:
m, n = n, m
mg = m // g
ng = n // g
# Not every x needs to be considered.
# xj holds the list of x values to be checked.
# Wherever n*x/m + ng*h crosses an integer
lxj = n + (mg-h)//mg
xj = [(h + mg * j + ng-1)//ng for j in range(lxj)]
# B is an array just holding a few values of B(x,y), the ones needed.
# B[j] == B(x_j, j)
if lxj == 0:
return np.round(special.binom(m + n, n))
B = np.zeros(lxj)
B[0] = 1
# Compute the B(x, y) terms
# The binomial coefficient is an integer, but special.binom() may return a float.
# Round it to the nearest integer.
for j in range(1, lxj):
Bj = np.round(special.binom(xj[j] + j, j))
if not np.isfinite(Bj):
raise FloatingPointError()
for i in range(j):
bin = np.round(special.binom(xj[j] - xj[i] + j - i, j-i))
Bj -= bin * B[i]
B[j] = Bj
if not np.isfinite(Bj):
raise FloatingPointError()
# Compute the number of path extensions...
num_paths = 0
for j in range(lxj):
bin = np.round(special.binom((m-xj[j]) + (n - j), n-j))
term = B[j] * bin
if not np.isfinite(term):
raise FloatingPointError()
num_paths += term
return np.round(num_paths)
def _attempt_exact_2kssamp(n1, n2, g, d, alternative):
"""Attempts to compute the exact 2sample probability.
n1, n2 are the sample sizes
g is the gcd(n1, n2)
d is the computed max difference in ECDFs
Returns (success, d, probability)
"""
lcm = (n1 // g) * n2
h = int(np.round(d * lcm))
d = h * 1.0 / lcm
if h == 0:
return True, d, 1.0
saw_fp_error, prob = False, np.nan
try:
if alternative == 'two-sided':
if n1 == n2:
prob = _compute_prob_outside_square(n1, h)
else:
prob = 1 - _compute_prob_inside_method(n1, n2, g, h)
else:
if n1 == n2:
# prob = binom(2n, n-h) / binom(2n, n)
# Evaluating in that form incurs roundoff errors
# from special.binom. Instead calculate directly
jrange = np.arange(h)
prob = np.prod((n1 - jrange) / (n1 + jrange + 1.0))
else:
num_paths = _count_paths_outside_method(n1, n2, g, h)
bin = special.binom(n1 + n2, n1)
if not np.isfinite(bin) or not np.isfinite(num_paths) or num_paths > bin:
saw_fp_error = True
else:
prob = num_paths / bin
except FloatingPointError:
saw_fp_error = True
if saw_fp_error:
return False, d, np.nan
if not (0 <= prob <= 1):
return False, d, prob
return True, d, prob
def ks_2samp(data1, data2, alternative='two-sided', mode='auto'):
"""
Compute the Kolmogorov-Smirnov statistic on 2 samples.
This is a two-sided test for the null hypothesis that 2 independent samples
are drawn from the same continuous distribution. The alternative hypothesis
can be either 'two-sided' (default), 'less' or 'greater'.
Parameters
----------
data1, data2 : array_like, 1-Dimensional
Two arrays of sample observations assumed to be drawn from a continuous
distribution, sample sizes can be different.
alternative : {'two-sided', 'less', 'greater'}, optional
Defines the alternative hypothesis.
The following options are available (default is 'two-sided'):
* 'two-sided'
* 'less': one-sided, see explanation in Notes
* 'greater': one-sided, see explanation in Notes
mode : {'auto', 'exact', 'asymp'}, optional
Defines the method used for calculating the p-value.
The following options are available (default is 'auto'):
* 'auto' : use 'exact' for small size arrays, 'asymp' for large
* 'exact' : use exact distribution of test statistic
* 'asymp' : use asymptotic distribution of test statistic
Returns
-------
statistic : float
KS statistic.
pvalue : float
Two-tailed p-value.
See Also
--------
kstest, ks_1samp, epps_singleton_2samp, anderson_ksamp
Notes
-----
This tests whether 2 samples are drawn from the same distribution. Note
that, like in the case of the one-sample KS test, the distribution is
assumed to be continuous.
In the one-sided test, the alternative is that the empirical
cumulative distribution function F(x) of the data1 variable is "less"
or "greater" than the empirical cumulative distribution function G(x)
of the data2 variable, ``F(x)<=G(x)``, resp. ``F(x)>=G(x)``.
If the KS statistic is small or the p-value is high, then we cannot
reject the hypothesis that the distributions of the two samples
are the same.
If the mode is 'auto', the computation is exact if the sample sizes are
less than 10000. For larger sizes, the computation uses the
Kolmogorov-Smirnov distributions to compute an approximate value.
The 'two-sided' 'exact' computation computes the complementary probability
and then subtracts from 1. As such, the minimum probability it can return
is about 1e-16. While the algorithm itself is exact, numerical
errors may accumulate for large sample sizes. It is most suited to
situations in which one of the sample sizes is only a few thousand.
We generally follow Hodges' treatment of Drion/Gnedenko/Korolyuk [1]_.
References
----------
.. [1] Hodges, J.L. Jr., "The Significance Probability of the Smirnov
Two-Sample Test," Arkiv fiur Matematik, 3, No. 43 (1958), 469-86.
Examples
--------
>>> from scipy import stats
>>> np.random.seed(12345678) #fix random seed to get the same result
>>> n1 = 200 # size of first sample
>>> n2 = 300 # size of second sample
For a different distribution, we can reject the null hypothesis since the
pvalue is below 1%:
>>> rvs1 = stats.norm.rvs(size=n1, loc=0., scale=1)
>>> rvs2 = stats.norm.rvs(size=n2, loc=0.5, scale=1.5)
>>> stats.ks_2samp(rvs1, rvs2)
(0.20833333333333334, 5.129279597781977e-05)
For a slightly different distribution, we cannot reject the null hypothesis
at a 10% or lower alpha since the p-value at 0.144 is higher than 10%
>>> rvs3 = stats.norm.rvs(size=n2, loc=0.01, scale=1.0)
>>> stats.ks_2samp(rvs1, rvs3)
(0.10333333333333333, 0.14691437867433876)
For an identical distribution, we cannot reject the null hypothesis since
the p-value is high, 41%:
>>> rvs4 = stats.norm.rvs(size=n2, loc=0.0, scale=1.0)
>>> stats.ks_2samp(rvs1, rvs4)
(0.07999999999999996, 0.41126949729859719)
"""
if mode not in ['auto', 'exact', 'asymp']:
raise ValueError(f'Invalid value for mode: {mode}')
alternative = {'t': 'two-sided', 'g': 'greater', 'l': 'less'}.get(
alternative.lower()[0], alternative)
if alternative not in ['two-sided', 'less', 'greater']:
raise ValueError(f'Invalid value for alternative: {alternative}')
MAX_AUTO_N = 10000 # 'auto' will attempt to be exact if n1,n2 <= MAX_AUTO_N
if np.ma.is_masked(data1):
data1 = data1.compressed()
if np.ma.is_masked(data2):
data2 = data2.compressed()
data1 = np.sort(data1)
data2 = np.sort(data2)
n1 = data1.shape[0]
n2 = data2.shape[0]
if min(n1, n2) == 0:
raise ValueError('Data passed to ks_2samp must not be empty')
data_all = np.concatenate([data1, data2])
# using searchsorted solves equal data problem
cdf1 = np.searchsorted(data1, data_all, side='right') / n1
cdf2 = np.searchsorted(data2, data_all, side='right') / n2
cddiffs = cdf1 - cdf2
minS = np.clip(-np.min(cddiffs), 0, 1) # Ensure sign of minS is not negative.
maxS = np.max(cddiffs)
alt2Dvalue = {'less': minS, 'greater': maxS, 'two-sided': max(minS, maxS)}
d = alt2Dvalue[alternative]
g = gcd(n1, n2)
n1g = n1 // g
n2g = n2 // g
prob = -np.inf
original_mode = mode
if mode == 'auto':
mode = 'exact' if max(n1, n2) <= MAX_AUTO_N else 'asymp'
elif mode == 'exact':
# If lcm(n1, n2) is too big, switch from exact to asymp
if n1g >= np.iinfo(np.int_).max / n2g:
mode = 'asymp'
warnings.warn(
f"Exact ks_2samp calculation not possible with samples sizes "
f"{n1} and {n2}. Switching to 'asymp'.", RuntimeWarning)
if mode == 'exact':
success, d, prob = _attempt_exact_2kssamp(n1, n2, g, d, alternative)
if not success:
mode = 'asymp'
if original_mode == 'exact':
warnings.warn(f"ks_2samp: Exact calculation unsuccessful. "
f"Switching to mode={mode}.", RuntimeWarning)
if mode == 'asymp':
# The product n1*n2 is large. Use Smirnov's asymptoptic formula.
# Ensure float to avoid overflow in multiplication
# sorted because the one-sided formula is not symmetric in n1, n2
m, n = sorted([float(n1), float(n2)], reverse=True)
en = m * n / (m + n)
if alternative == 'two-sided':
prob = distributions.kstwo.sf(d, np.round(en))
else:
z = np.sqrt(en) * d
# Use Hodges' suggested approximation Eqn 5.3
# Requires m to be the larger of (n1, n2)
expt = -2 * z**2 - 2 * z * (m + 2*n)/np.sqrt(m*n*(m+n))/3.0
prob = np.exp(expt)
prob = np.clip(prob, 0, 1)
return KstestResult(d, prob)
def _parse_kstest_args(data1, data2, args, N):
# kstest allows many different variations of arguments.
# Pull out the parsing into a separate function
# (xvals, yvals, ) # 2sample
# (xvals, cdf function,..)
# (xvals, name of distribution, ...)
# (name of distribution, name of distribution, ...)
# Returns xvals, yvals, cdf
# where cdf is a cdf function, or None
# and yvals is either an array_like of values, or None
# and xvals is array_like.
rvsfunc, cdf = None, None
if isinstance(data1, str):
rvsfunc = getattr(distributions, data1).rvs
elif callable(data1):
rvsfunc = data1
if isinstance(data2, str):
cdf = getattr(distributions, data2).cdf
data2 = None
elif callable(data2):
cdf = data2
data2 = None
data1 = np.sort(rvsfunc(*args, size=N) if rvsfunc else data1)
return data1, data2, cdf
def kstest(rvs, cdf, args=(), N=20, alternative='two-sided', mode='auto'):
"""
Performs the (one sample or two samples) Kolmogorov-Smirnov test for goodness of fit.
The one-sample test performs a test of the distribution F(x) of an observed
random variable against a given distribution G(x). Under the null
hypothesis, the two distributions are identical, F(x)=G(x). The
alternative hypothesis can be either 'two-sided' (default), 'less'
or 'greater'. The KS test is only valid for continuous distributions.
The two-sample test tests whether the two independent samples are drawn
from the same continuous distribution.
Parameters
----------
rvs : str, array_like, or callable
If an array, it should be a 1-D array of observations of random
variables.
If a callable, it should be a function to generate random variables;
it is required to have a keyword argument `size`.
If a string, it should be the name of a distribution in `scipy.stats`,
which will be used to generate random variables.
cdf : str, array_like or callable
If array_like, it should be a 1-D array of observations of random
variables, and the two-sample test is performed (and rvs must be array_like)
If a callable, that callable is used to calculate the cdf.
If a string, it should be the name of a distribution in `scipy.stats`,
which will be used as the cdf function.
args : tuple, sequence, optional
Distribution parameters, used if `rvs` or `cdf` are strings or callables.
N : int, optional
Sample size if `rvs` is string or callable. Default is 20.
alternative : {'two-sided', 'less', 'greater'}, optional
Defines the alternative hypothesis.
The following options are available (default is 'two-sided'):
* 'two-sided'
* 'less': one-sided, see explanation in Notes
* 'greater': one-sided, see explanation in Notes
mode : {'auto', 'exact', 'approx', 'asymp'}, optional
Defines the distribution used for calculating the p-value.
The following options are available (default is 'auto'):
* 'auto' : selects one of the other options.
* 'exact' : uses the exact distribution of test statistic.
* 'approx' : approximates the two-sided probability with twice the one-sided probability
* 'asymp': uses asymptotic distribution of test statistic
Returns
-------
statistic : float
KS test statistic, either D, D+ or D-.
pvalue : float
One-tailed or two-tailed p-value.
See Also
--------
ks_2samp
Notes
-----
In the one-sided test, the alternative is that the empirical
cumulative distribution function of the random variable is "less"
or "greater" than the cumulative distribution function G(x) of the
hypothesis, ``F(x)<=G(x)``, resp. ``F(x)>=G(x)``.
Examples
--------
>>> from scipy import stats
>>> x = np.linspace(-15, 15, 9)
>>> stats.kstest(x, 'norm')
(0.44435602715924361, 0.038850142705171065)
>>> np.random.seed(987654321) # set random seed to get the same result
>>> stats.kstest(stats.norm.rvs(size=100), stats.norm.cdf)
(0.058352892479417884, 0.8653960860778898)
The above lines are equivalent to:
>>> np.random.seed(987654321)
>>> stats.kstest(stats.norm.rvs, 'norm', N=100)
(0.058352892479417884, 0.8653960860778898)
*Test against one-sided alternative hypothesis*
Shift distribution to larger values, so that ``CDF(x) < norm.cdf(x)``:
>>> np.random.seed(987654321)
>>> x = stats.norm.rvs(loc=0.2, size=100)
>>> stats.kstest(x, 'norm', alternative='less')
(0.12464329735846891, 0.040989164077641749)
Reject equal distribution against alternative hypothesis: less
>>> stats.kstest(x, 'norm', alternative='greater')
(0.0072115233216311081, 0.98531158590396395)
Don't reject equal distribution against alternative hypothesis: greater
>>> stats.kstest(x, 'norm')
(0.12464329735846891, 0.08197335233541582)
*Testing t distributed random variables against normal distribution*
With 100 degrees of freedom the t distribution looks close to the normal
distribution, and the K-S test does not reject the hypothesis that the
sample came from the normal distribution:
>>> np.random.seed(987654321)
>>> stats.kstest(stats.t.rvs(100, size=100), 'norm')
(0.072018929165471257, 0.6505883498379312)
With 3 degrees of freedom the t distribution looks sufficiently different
from the normal distribution, that we can reject the hypothesis that the
sample came from the normal distribution at the 10% level:
>>> np.random.seed(987654321)
>>> stats.kstest(stats.t.rvs(3, size=100), 'norm')
(0.131016895759829, 0.058826222555312224)
"""
# to not break compatibility with existing code
if alternative == 'two_sided':
alternative = 'two-sided'
if alternative not in ['two-sided', 'greater', 'less']:
raise ValueError("Unexpected alternative %s" % alternative)
xvals, yvals, cdf = _parse_kstest_args(rvs, cdf, args, N)
if cdf:
return ks_1samp(xvals, cdf, args=args, alternative=alternative, mode=mode)
return ks_2samp(xvals, yvals, alternative=alternative, mode=mode)
def tiecorrect(rankvals):
"""
Tie correction factor for Mann-Whitney U and Kruskal-Wallis H tests.
Parameters
----------
rankvals : array_like
A 1-D sequence of ranks. Typically this will be the array
returned by `~scipy.stats.rankdata`.
Returns
-------
factor : float
Correction factor for U or H.
See Also
--------
rankdata : Assign ranks to the data
mannwhitneyu : Mann-Whitney rank test
kruskal : Kruskal-Wallis H test
References
----------
.. [1] Siegel, S. (1956) Nonparametric Statistics for the Behavioral
Sciences. New York: McGraw-Hill.
Examples
--------
>>> from scipy.stats import tiecorrect, rankdata
>>> tiecorrect([1, 2.5, 2.5, 4])
0.9
>>> ranks = rankdata([1, 3, 2, 4, 5, 7, 2, 8, 4])
>>> ranks
array([ 1. , 4. , 2.5, 5.5, 7. , 8. , 2.5, 9. , 5.5])
>>> tiecorrect(ranks)
0.9833333333333333
"""
arr = np.sort(rankvals)
idx = np.nonzero(np.r_[True, arr[1:] != arr[:-1], True])[0]
cnt = np.diff(idx).astype(np.float64)
size = np.float64(arr.size)
return 1.0 if size < 2 else 1.0 - (cnt**3 - cnt).sum() / (size**3 - size)
MannwhitneyuResult = namedtuple('MannwhitneyuResult', ('statistic', 'pvalue'))
def mannwhitneyu(x, y, use_continuity=True, alternative=None):
"""
Compute the Mann-Whitney rank test on samples x and y.
Parameters
----------
x, y : array_like
Array of samples, should be one-dimensional.
use_continuity : bool, optional
Whether a continuity correction (1/2.) should be taken into
account. Default is True.
alternative : {None, 'two-sided', 'less', 'greater'}, optional
Defines the alternative hypothesis.
The following options are available (default is None):
* None: computes p-value half the size of the 'two-sided' p-value and
a different U statistic. The default behavior is not the same as
using 'less' or 'greater'; it only exists for backward compatibility
and is deprecated.
* 'two-sided'
* 'less': one-sided
* 'greater': one-sided
Use of the None option is deprecated.
Returns
-------
statistic : float
The Mann-Whitney U statistic, equal to min(U for x, U for y) if
`alternative` is equal to None (deprecated; exists for backward
compatibility), and U for y otherwise.
pvalue : float
p-value assuming an asymptotic normal distribution. One-sided or
two-sided, depending on the choice of `alternative`.
Notes
-----
Use only when the number of observation in each sample is > 20 and
you have 2 independent samples of ranks. Mann-Whitney U is
significant if the u-obtained is LESS THAN or equal to the critical
value of U.
This test corrects for ties and by default uses a continuity correction.
References
----------
.. [1] https://en.wikipedia.org/wiki/Mann-Whitney_U_test
.. [2] H.B. Mann and D.R. Whitney, "On a Test of Whether one of Two Random
Variables is Stochastically Larger than the Other," The Annals of
Mathematical Statistics, vol. 18, no. 1, pp. 50-60, 1947.
"""
if alternative is None:
warnings.warn("Calling `mannwhitneyu` without specifying "
"`alternative` is deprecated.", DeprecationWarning)
x = np.asarray(x)
y = np.asarray(y)
n1 = len(x)
n2 = len(y)
ranked = rankdata(np.concatenate((x, y)))
rankx = ranked[0:n1] # get the x-ranks
u1 = n1*n2 + (n1*(n1+1))/2.0 - np.sum(rankx, axis=0) # calc U for x
u2 = n1*n2 - u1 # remainder is U for y
T = tiecorrect(ranked)
if T == 0:
raise ValueError('All numbers are identical in mannwhitneyu')
sd = np.sqrt(T * n1 * n2 * (n1+n2+1) / 12.0)
meanrank = n1*n2/2.0 + 0.5 * use_continuity
if alternative is None or alternative == 'two-sided':
bigu = max(u1, u2)
elif alternative == 'less':
bigu = u1
elif alternative == 'greater':
bigu = u2
else:
raise ValueError("alternative should be None, 'less', 'greater' "
"or 'two-sided'")
z = (bigu - meanrank) / sd
if alternative is None:
# This behavior, equal to half the size of the two-sided
# p-value, is deprecated.
p = distributions.norm.sf(abs(z))
elif alternative == 'two-sided':
p = 2 * distributions.norm.sf(abs(z))
else:
p = distributions.norm.sf(z)
u = u2
# This behavior is deprecated.
if alternative is None:
u = min(u1, u2)
return MannwhitneyuResult(u, p)
RanksumsResult = namedtuple('RanksumsResult', ('statistic', 'pvalue'))
def ranksums(x, y):
"""
Compute the Wilcoxon rank-sum statistic for two samples.
The Wilcoxon rank-sum test tests the null hypothesis that two sets
of measurements are drawn from the same distribution. The alternative
hypothesis is that values in one sample are more likely to be
larger than the values in the other sample.
This test should be used to compare two samples from continuous
distributions. It does not handle ties between measurements
in x and y. For tie-handling and an optional continuity correction
see `scipy.stats.mannwhitneyu`.
Parameters
----------
x,y : array_like
The data from the two samples.
Returns
-------
statistic : float
The test statistic under the large-sample approximation that the
rank sum statistic is normally distributed.
pvalue : float
The two-sided p-value of the test.
References
----------
.. [1] https://en.wikipedia.org/wiki/Wilcoxon_rank-sum_test
Examples
--------
We can test the hypothesis that two independent unequal-sized samples are
drawn from the same distribution with computing the Wilcoxon rank-sum
statistic.
>>> from scipy.stats import ranksums
>>> sample1 = np.random.uniform(-1, 1, 200)
>>> sample2 = np.random.uniform(-0.5, 1.5, 300) # a shifted distribution
>>> ranksums(sample1, sample2)
RanksumsResult(statistic=-7.887059, pvalue=3.09390448e-15) # may vary
The p-value of less than ``0.05`` indicates that this test rejects the
hypothesis at the 5% significance level.
"""
x, y = map(np.asarray, (x, y))
n1 = len(x)
n2 = len(y)
alldata = np.concatenate((x, y))
ranked = rankdata(alldata)
x = ranked[:n1]
s = np.sum(x, axis=0)
expected = n1 * (n1+n2+1) / 2.0
z = (s - expected) / np.sqrt(n1*n2*(n1+n2+1)/12.0)
prob = 2 * distributions.norm.sf(abs(z))
return RanksumsResult(z, prob)
KruskalResult = namedtuple('KruskalResult', ('statistic', 'pvalue'))
def kruskal(*args, nan_policy='propagate'):
"""
Compute the Kruskal-Wallis H-test for independent samples.
The Kruskal-Wallis H-test tests the null hypothesis that the population
median of all of the groups are equal. It is a non-parametric version of
ANOVA. The test works on 2 or more independent samples, which may have
different sizes. Note that rejecting the null hypothesis does not
indicate which of the groups differs. Post hoc comparisons between
groups are required to determine which groups are different.
Parameters
----------
sample1, sample2, ... : array_like
Two or more arrays with the sample measurements can be given as
arguments. Samples must be one-dimensional.
nan_policy : {'propagate', 'raise', 'omit'}, optional
Defines how to handle when input contains nan.
The following options are available (default is 'propagate'):
* 'propagate': returns nan
* 'raise': throws an error
* 'omit': performs the calculations ignoring nan values
Returns
-------
statistic : float
The Kruskal-Wallis H statistic, corrected for ties.
pvalue : float
The p-value for the test using the assumption that H has a chi
square distribution. The p-value returned is the survival function of
the chi square distribution evaluated at H.
See Also
--------
f_oneway : 1-way ANOVA.
mannwhitneyu : Mann-Whitney rank test on two samples.
friedmanchisquare : Friedman test for repeated measurements.
Notes
-----
Due to the assumption that H has a chi square distribution, the number
of samples in each group must not be too small. A typical rule is
that each sample must have at least 5 measurements.
References
----------
.. [1] W. H. Kruskal & W. W. Wallis, "Use of Ranks in
One-Criterion Variance Analysis", Journal of the American Statistical
Association, Vol. 47, Issue 260, pp. 583-621, 1952.
.. [2] https://en.wikipedia.org/wiki/Kruskal-Wallis_one-way_analysis_of_variance
Examples
--------
>>> from scipy import stats
>>> x = [1, 3, 5, 7, 9]
>>> y = [2, 4, 6, 8, 10]
>>> stats.kruskal(x, y)
KruskalResult(statistic=0.2727272727272734, pvalue=0.6015081344405895)
>>> x = [1, 1, 1]
>>> y = [2, 2, 2]
>>> z = [2, 2]
>>> stats.kruskal(x, y, z)
KruskalResult(statistic=7.0, pvalue=0.0301973834223185)
"""
args = list(map(np.asarray, args))
num_groups = len(args)
if num_groups < 2:
raise ValueError("Need at least two groups in stats.kruskal()")
for arg in args:
if arg.size == 0:
return KruskalResult(np.nan, np.nan)
elif arg.ndim != 1:
raise ValueError("Samples must be one-dimensional.")
n = np.asarray(list(map(len, args)))
if nan_policy not in ('propagate', 'raise', 'omit'):
raise ValueError("nan_policy must be 'propagate', 'raise' or 'omit'")
contains_nan = False
for arg in args:
cn = _contains_nan(arg, nan_policy)
if cn[0]:
contains_nan = True
break
if contains_nan and nan_policy == 'omit':
for a in args:
a = ma.masked_invalid(a)
return mstats_basic.kruskal(*args)
if contains_nan and nan_policy == 'propagate':
return KruskalResult(np.nan, np.nan)
alldata = np.concatenate(args)
ranked = rankdata(alldata)
ties = tiecorrect(ranked)
if ties == 0:
raise ValueError('All numbers are identical in kruskal')
# Compute sum^2/n for each group and sum
j = np.insert(np.cumsum(n), 0, 0)
ssbn = 0
for i in range(num_groups):
ssbn += _square_of_sums(ranked[j[i]:j[i+1]]) / n[i]
totaln = np.sum(n, dtype=float)
h = 12.0 / (totaln * (totaln + 1)) * ssbn - 3 * (totaln + 1)
df = num_groups - 1
h /= ties
return KruskalResult(h, distributions.chi2.sf(h, df))
FriedmanchisquareResult = namedtuple('FriedmanchisquareResult',
('statistic', 'pvalue'))
def friedmanchisquare(*args):
"""
Compute the Friedman test for repeated measurements.
The Friedman test tests the null hypothesis that repeated measurements of
the same individuals have the same distribution. It is often used
to test for consistency among measurements obtained in different ways.
For example, if two measurement techniques are used on the same set of
individuals, the Friedman test can be used to determine if the two
measurement techniques are consistent.
Parameters
----------
measurements1, measurements2, measurements3... : array_like
Arrays of measurements. All of the arrays must have the same number
of elements. At least 3 sets of measurements must be given.
Returns
-------
statistic : float
The test statistic, correcting for ties.
pvalue : float
The associated p-value assuming that the test statistic has a chi
squared distribution.
Notes
-----
Due to the assumption that the test statistic has a chi squared
distribution, the p-value is only reliable for n > 10 and more than
6 repeated measurements.
References
----------
.. [1] https://en.wikipedia.org/wiki/Friedman_test
"""
k = len(args)
if k < 3:
raise ValueError('At least 3 sets of measurements must be given for Friedman test, got {}.'.format(k))
n = len(args[0])
for i in range(1, k):
if len(args[i]) != n:
raise ValueError('Unequal N in friedmanchisquare. Aborting.')
# Rank data
data = np.vstack(args).T
data = data.astype(float)
for i in range(len(data)):
data[i] = rankdata(data[i])
# Handle ties
ties = 0
for i in range(len(data)):
replist, repnum = find_repeats(array(data[i]))
for t in repnum:
ties += t * (t*t - 1)
c = 1 - ties / (k*(k*k - 1)*n)
ssbn = np.sum(data.sum(axis=0)**2)
chisq = (12.0 / (k*n*(k+1)) * ssbn - 3*n*(k+1)) / c
return FriedmanchisquareResult(chisq, distributions.chi2.sf(chisq, k - 1))
BrunnerMunzelResult = namedtuple('BrunnerMunzelResult',
('statistic', 'pvalue'))
def brunnermunzel(x, y, alternative="two-sided", distribution="t",
nan_policy='propagate'):
"""
Compute the Brunner-Munzel test on samples x and y.
The Brunner-Munzel test is a nonparametric test of the null hypothesis that
when values are taken one by one from each group, the probabilities of
getting large values in both groups are equal.
Unlike the Wilcoxon-Mann-Whitney's U test, this does not require the
assumption of equivariance of two groups. Note that this does not assume
the distributions are same. This test works on two independent samples,
which may have different sizes.
Parameters
----------
x, y : array_like
Array of samples, should be one-dimensional.
alternative : {'two-sided', 'less', 'greater'}, optional
Defines the alternative hypothesis.
The following options are available (default is 'two-sided'):
* 'two-sided'
* 'less': one-sided
* 'greater': one-sided
distribution : {'t', 'normal'}, optional
Defines how to get the p-value.
The following options are available (default is 't'):
* 't': get the p-value by t-distribution
* 'normal': get the p-value by standard normal distribution.
nan_policy : {'propagate', 'raise', 'omit'}, optional
Defines how to handle when input contains nan.
The following options are available (default is 'propagate'):
* 'propagate': returns nan
* 'raise': throws an error
* 'omit': performs the calculations ignoring nan values
Returns
-------
statistic : float
The Brunner-Munzer W statistic.
pvalue : float
p-value assuming an t distribution. One-sided or
two-sided, depending on the choice of `alternative` and `distribution`.
See Also
--------
mannwhitneyu : Mann-Whitney rank test on two samples.
Notes
-----
Brunner and Munzel recommended to estimate the p-value by t-distribution
when the size of data is 50 or less. If the size is lower than 10, it would
be better to use permuted Brunner Munzel test (see [2]_).
References
----------
.. [1] Brunner, E. and Munzel, U. "The nonparametric Benhrens-Fisher
problem: Asymptotic theory and a small-sample approximation".
Biometrical Journal. Vol. 42(2000): 17-25.
.. [2] Neubert, K. and Brunner, E. "A studentized permutation test for the
non-parametric Behrens-Fisher problem". Computational Statistics and
Data Analysis. Vol. 51(2007): 5192-5204.
Examples
--------
>>> from scipy import stats
>>> x1 = [1,2,1,1,1,1,1,1,1,1,2,4,1,1]
>>> x2 = [3,3,4,3,1,2,3,1,1,5,4]
>>> w, p_value = stats.brunnermunzel(x1, x2)
>>> w
3.1374674823029505
>>> p_value
0.0057862086661515377
"""
x = np.asarray(x)
y = np.asarray(y)
# check both x and y
cnx, npx = _contains_nan(x, nan_policy)
cny, npy = _contains_nan(y, nan_policy)
contains_nan = cnx or cny
if npx == "omit" or npy == "omit":
nan_policy = "omit"
if contains_nan and nan_policy == "propagate":
return BrunnerMunzelResult(np.nan, np.nan)
elif contains_nan and nan_policy == "omit":
x = ma.masked_invalid(x)
y = ma.masked_invalid(y)
return mstats_basic.brunnermunzel(x, y, alternative, distribution)
nx = len(x)
ny = len(y)
if nx == 0 or ny == 0:
return BrunnerMunzelResult(np.nan, np.nan)
rankc = rankdata(np.concatenate((x, y)))
rankcx = rankc[0:nx]
rankcy = rankc[nx:nx+ny]
rankcx_mean = np.mean(rankcx)
rankcy_mean = np.mean(rankcy)
rankx = rankdata(x)
ranky = rankdata(y)
rankx_mean = np.mean(rankx)
ranky_mean = np.mean(ranky)
Sx = np.sum(np.power(rankcx - rankx - rankcx_mean + rankx_mean, 2.0))
Sx /= nx - 1
Sy = np.sum(np.power(rankcy - ranky - rankcy_mean + ranky_mean, 2.0))
Sy /= ny - 1
wbfn = nx * ny * (rankcy_mean - rankcx_mean)
wbfn /= (nx + ny) * np.sqrt(nx * Sx + ny * Sy)
if distribution == "t":
df_numer = np.power(nx * Sx + ny * Sy, 2.0)
df_denom = np.power(nx * Sx, 2.0) / (nx - 1)
df_denom += np.power(ny * Sy, 2.0) / (ny - 1)
df = df_numer / df_denom
p = distributions.t.cdf(wbfn, df)
elif distribution == "normal":
p = distributions.norm.cdf(wbfn)
else:
raise ValueError(
"distribution should be 't' or 'normal'")
if alternative == "greater":
pass
elif alternative == "less":
p = 1 - p
elif alternative == "two-sided":
p = 2 * np.min([p, 1-p])
else:
raise ValueError(
"alternative should be 'less', 'greater' or 'two-sided'")
return BrunnerMunzelResult(wbfn, p)
def combine_pvalues(pvalues, method='fisher', weights=None):
"""
Combine p-values from independent tests bearing upon the same hypothesis.
Parameters
----------
pvalues : array_like, 1-D
Array of p-values assumed to come from independent tests.
method : {'fisher', 'pearson', 'tippett', 'stouffer', 'mudholkar_george'}, optional
Name of method to use to combine p-values.
The following methods are available (default is 'fisher'):
* 'fisher': Fisher's method (Fisher's combined probability test), the
sum of the logarithm of the p-values
* 'pearson': Pearson's method (similar to Fisher's but uses sum of the
complement of the p-values inside the logarithms)
* 'tippett': Tippett's method (minimum of p-values)
* 'stouffer': Stouffer's Z-score method
* 'mudholkar_george': the difference of Fisher's and Pearson's methods
divided by 2
weights : array_like, 1-D, optional
Optional array of weights used only for Stouffer's Z-score method.
Returns
-------
statistic: float
The statistic calculated by the specified method.
pval: float
The combined p-value.
Notes
-----
Fisher's method (also known as Fisher's combined probability test) [1]_ uses
a chi-squared statistic to compute a combined p-value. The closely related
Stouffer's Z-score method [2]_ uses Z-scores rather than p-values. The
advantage of Stouffer's method is that it is straightforward to introduce
weights, which can make Stouffer's method more powerful than Fisher's
method when the p-values are from studies of different size [6]_ [7]_.
The Pearson's method uses :math:`log(1-p_i)` inside the sum whereas Fisher's
method uses :math:`log(p_i)` [4]_. For Fisher's and Pearson's method, the
sum of the logarithms is multiplied by -2 in the implementation. This
quantity has a chi-square distribution that determines the p-value. The
`mudholkar_george` method is the difference of the Fisher's and Pearson's
test statistics, each of which include the -2 factor [4]_. However, the
`mudholkar_george` method does not include these -2 factors. The test
statistic of `mudholkar_george` is the sum of logisitic random variables and
equation 3.6 in [3]_ is used to approximate the p-value based on Student's
t-distribution.
Fisher's method may be extended to combine p-values from dependent tests
[5]_. Extensions such as Brown's method and Kost's method are not currently
implemented.
.. versionadded:: 0.15.0
References
----------
.. [1] https://en.wikipedia.org/wiki/Fisher%27s_method
.. [2] https://en.wikipedia.org/wiki/Fisher%27s_method#Relation_to_Stouffer.27s_Z-score_method
.. [3] George, E. O., and G. S. Mudholkar. "On the convolution of logistic
random variables." Metrika 30.1 (1983): 1-13.
.. [4] Heard, N. and Rubin-Delanchey, P. "Choosing between methods of
combining p-values." Biometrika 105.1 (2018): 239-246.
.. [5] Whitlock, M. C. "Combining probability from independent tests: the
weighted Z-method is superior to Fisher's approach." Journal of
Evolutionary Biology 18, no. 5 (2005): 1368-1373.
.. [6] Zaykin, Dmitri V. "Optimally weighted Z-test is a powerful method
for combining probabilities in meta-analysis." Journal of
Evolutionary Biology 24, no. 8 (2011): 1836-1841.
.. [7] https://en.wikipedia.org/wiki/Extensions_of_Fisher%27s_method
"""
pvalues = np.asarray(pvalues)
if pvalues.ndim != 1:
raise ValueError("pvalues is not 1-D")
if method == 'fisher':
statistic = -2 * np.sum(np.log(pvalues))
pval = distributions.chi2.sf(statistic, 2 * len(pvalues))
elif method == 'pearson':
statistic = -2 * np.sum(np.log1p(-pvalues))
pval = distributions.chi2.sf(statistic, 2 * len(pvalues))
elif method == 'mudholkar_george':
normalizing_factor = np.sqrt(3/len(pvalues))/np.pi
statistic = -np.sum(np.log(pvalues)) + np.sum(np.log1p(-pvalues))
nu = 5 * len(pvalues) + 4
approx_factor = np.sqrt(nu / (nu - 2))
pval = distributions.t.sf(statistic * normalizing_factor * approx_factor, nu)
elif method == 'tippett':
statistic = np.min(pvalues)
pval = distributions.beta.sf(statistic, 1, len(pvalues))
elif method == 'stouffer':
if weights is None:
weights = np.ones_like(pvalues)
elif len(weights) != len(pvalues):
raise ValueError("pvalues and weights must be of the same size.")
weights = np.asarray(weights)
if weights.ndim != 1:
raise ValueError("weights is not 1-D")
Zi = distributions.norm.isf(pvalues)
statistic = np.dot(weights, Zi) / np.linalg.norm(weights)
pval = distributions.norm.sf(statistic)
else:
raise ValueError(
"Invalid method '%s'. Options are 'fisher', 'pearson', \
'mudholkar_george', 'tippett', 'or 'stouffer'", method)
return (statistic, pval)
#####################################
# STATISTICAL DISTANCES #
#####################################
def wasserstein_distance(u_values, v_values, u_weights=None, v_weights=None):
r"""
Compute the first Wasserstein distance between two 1D distributions.
This distance is also known as the earth mover's distance, since it can be
seen as the minimum amount of "work" required to transform :math:`u` into
:math:`v`, where "work" is measured as the amount of distribution weight
that must be moved, multiplied by the distance it has to be moved.
.. versionadded:: 1.0.0
Parameters
----------
u_values, v_values : array_like
Values observed in the (empirical) distribution.
u_weights, v_weights : array_like, optional
Weight for each value. If unspecified, each value is assigned the same
weight.
`u_weights` (resp. `v_weights`) must have the same length as
`u_values` (resp. `v_values`). If the weight sum differs from 1, it
must still be positive and finite so that the weights can be normalized
to sum to 1.
Returns
-------
distance : float
The computed distance between the distributions.
Notes
-----
The first Wasserstein distance between the distributions :math:`u` and
:math:`v` is:
.. math::
l_1 (u, v) = \inf_{\pi \in \Gamma (u, v)} \int_{\mathbb{R} \times
\mathbb{R}} |x-y| \mathrm{d} \pi (x, y)
where :math:`\Gamma (u, v)` is the set of (probability) distributions on
:math:`\mathbb{R} \times \mathbb{R}` whose marginals are :math:`u` and
:math:`v` on the first and second factors respectively.
If :math:`U` and :math:`V` are the respective CDFs of :math:`u` and
:math:`v`, this distance also equals to:
.. math::
l_1(u, v) = \int_{-\infty}^{+\infty} |U-V|
See [2]_ for a proof of the equivalence of both definitions.
The input distributions can be empirical, therefore coming from samples
whose values are effectively inputs of the function, or they can be seen as
generalized functions, in which case they are weighted sums of Dirac delta
functions located at the specified values.
References
----------
.. [1] "Wasserstein metric", https://en.wikipedia.org/wiki/Wasserstein_metric
.. [2] Ramdas, Garcia, Cuturi "On Wasserstein Two Sample Testing and Related
Families of Nonparametric Tests" (2015). :arXiv:`1509.02237`.
Examples
--------
>>> from scipy.stats import wasserstein_distance
>>> wasserstein_distance([0, 1, 3], [5, 6, 8])
5.0
>>> wasserstein_distance([0, 1], [0, 1], [3, 1], [2, 2])
0.25
>>> wasserstein_distance([3.4, 3.9, 7.5, 7.8], [4.5, 1.4],
... [1.4, 0.9, 3.1, 7.2], [3.2, 3.5])
4.0781331438047861
"""
return _cdf_distance(1, u_values, v_values, u_weights, v_weights)
def energy_distance(u_values, v_values, u_weights=None, v_weights=None):
r"""
Compute the energy distance between two 1D distributions.
.. versionadded:: 1.0.0
Parameters
----------
u_values, v_values : array_like
Values observed in the (empirical) distribution.
u_weights, v_weights : array_like, optional
Weight for each value. If unspecified, each value is assigned the same
weight.
`u_weights` (resp. `v_weights`) must have the same length as
`u_values` (resp. `v_values`). If the weight sum differs from 1, it
must still be positive and finite so that the weights can be normalized
to sum to 1.
Returns
-------
distance : float
The computed distance between the distributions.
Notes
-----
The energy distance between two distributions :math:`u` and :math:`v`, whose
respective CDFs are :math:`U` and :math:`V`, equals to:
.. math::
D(u, v) = \left( 2\mathbb E|X - Y| - \mathbb E|X - X'| -
\mathbb E|Y - Y'| \right)^{1/2}
where :math:`X` and :math:`X'` (resp. :math:`Y` and :math:`Y'`) are
independent random variables whose probability distribution is :math:`u`
(resp. :math:`v`).
As shown in [2]_, for one-dimensional real-valued variables, the energy
distance is linked to the non-distribution-free version of the Cramér-von
Mises distance:
.. math::
D(u, v) = \sqrt{2} l_2(u, v) = \left( 2 \int_{-\infty}^{+\infty} (U-V)^2
\right)^{1/2}
Note that the common Cramér-von Mises criterion uses the distribution-free
version of the distance. See [2]_ (section 2), for more details about both
versions of the distance.
The input distributions can be empirical, therefore coming from samples
whose values are effectively inputs of the function, or they can be seen as
generalized functions, in which case they are weighted sums of Dirac delta
functions located at the specified values.
References
----------
.. [1] "Energy distance", https://en.wikipedia.org/wiki/Energy_distance
.. [2] Szekely "E-statistics: The energy of statistical samples." Bowling
Green State University, Department of Mathematics and Statistics,
Technical Report 02-16 (2002).
.. [3] Rizzo, Szekely "Energy distance." Wiley Interdisciplinary Reviews:
Computational Statistics, 8(1):27-38 (2015).
.. [4] Bellemare, Danihelka, Dabney, Mohamed, Lakshminarayanan, Hoyer,
Munos "The Cramer Distance as a Solution to Biased Wasserstein
Gradients" (2017). :arXiv:`1705.10743`.
Examples
--------
>>> from scipy.stats import energy_distance
>>> energy_distance([0], [2])
2.0000000000000004
>>> energy_distance([0, 8], [0, 8], [3, 1], [2, 2])
1.0000000000000002
>>> energy_distance([0.7, 7.4, 2.4, 6.8], [1.4, 8. ],
... [2.1, 4.2, 7.4, 8. ], [7.6, 8.8])
0.88003340976158217
"""
return np.sqrt(2) * _cdf_distance(2, u_values, v_values,
u_weights, v_weights)
def _cdf_distance(p, u_values, v_values, u_weights=None, v_weights=None):
r"""
Compute, between two one-dimensional distributions :math:`u` and
:math:`v`, whose respective CDFs are :math:`U` and :math:`V`, the
statistical distance that is defined as:
.. math::
l_p(u, v) = \left( \int_{-\infty}^{+\infty} |U-V|^p \right)^{1/p}
p is a positive parameter; p = 1 gives the Wasserstein distance, p = 2
gives the energy distance.
Parameters
----------
u_values, v_values : array_like
Values observed in the (empirical) distribution.
u_weights, v_weights : array_like, optional
Weight for each value. If unspecified, each value is assigned the same
weight.
`u_weights` (resp. `v_weights`) must have the same length as
`u_values` (resp. `v_values`). If the weight sum differs from 1, it
must still be positive and finite so that the weights can be normalized
to sum to 1.
Returns
-------
distance : float
The computed distance between the distributions.
Notes
-----
The input distributions can be empirical, therefore coming from samples
whose values are effectively inputs of the function, or they can be seen as
generalized functions, in which case they are weighted sums of Dirac delta
functions located at the specified values.
References
----------
.. [1] Bellemare, Danihelka, Dabney, Mohamed, Lakshminarayanan, Hoyer,
Munos "The Cramer Distance as a Solution to Biased Wasserstein
Gradients" (2017). :arXiv:`1705.10743`.
"""
u_values, u_weights = _validate_distribution(u_values, u_weights)
v_values, v_weights = _validate_distribution(v_values, v_weights)
u_sorter = np.argsort(u_values)
v_sorter = np.argsort(v_values)
all_values = np.concatenate((u_values, v_values))
all_values.sort(kind='mergesort')
# Compute the differences between pairs of successive values of u and v.
deltas = np.diff(all_values)
# Get the respective positions of the values of u and v among the values of
# both distributions.
u_cdf_indices = u_values[u_sorter].searchsorted(all_values[:-1], 'right')
v_cdf_indices = v_values[v_sorter].searchsorted(all_values[:-1], 'right')
# Calculate the CDFs of u and v using their weights, if specified.
if u_weights is None:
u_cdf = u_cdf_indices / u_values.size
else:
u_sorted_cumweights = np.concatenate(([0],
np.cumsum(u_weights[u_sorter])))
u_cdf = u_sorted_cumweights[u_cdf_indices] / u_sorted_cumweights[-1]
if v_weights is None:
v_cdf = v_cdf_indices / v_values.size
else:
v_sorted_cumweights = np.concatenate(([0],
np.cumsum(v_weights[v_sorter])))
v_cdf = v_sorted_cumweights[v_cdf_indices] / v_sorted_cumweights[-1]
# Compute the value of the integral based on the CDFs.
# If p = 1 or p = 2, we avoid using np.power, which introduces an overhead
# of about 15%.
if p == 1:
return np.sum(np.multiply(np.abs(u_cdf - v_cdf), deltas))
if p == 2:
return np.sqrt(np.sum(np.multiply(np.square(u_cdf - v_cdf), deltas)))
return np.power(np.sum(np.multiply(np.power(np.abs(u_cdf - v_cdf), p),
deltas)), 1/p)
def _validate_distribution(values, weights):
"""
Validate the values and weights from a distribution input of `cdf_distance`
and return them as ndarray objects.
Parameters
----------
values : array_like
Values observed in the (empirical) distribution.
weights : array_like
Weight for each value.
Returns
-------
values : ndarray
Values as ndarray.
weights : ndarray
Weights as ndarray.
"""
# Validate the value array.
values = np.asarray(values, dtype=float)
if len(values) == 0:
raise ValueError("Distribution can't be empty.")
# Validate the weight array, if specified.
if weights is not None:
weights = np.asarray(weights, dtype=float)
if len(weights) != len(values):
raise ValueError('Value and weight array-likes for the same '
'empirical distribution must be of the same size.')
if np.any(weights < 0):
raise ValueError('All weights must be non-negative.')
if not 0 < np.sum(weights) < np.inf:
raise ValueError('Weight array-like sum must be positive and '
'finite. Set as None for an equal distribution of '
'weight.')
return values, weights
return values, None
#####################################
# SUPPORT FUNCTIONS #
#####################################
RepeatedResults = namedtuple('RepeatedResults', ('values', 'counts'))
def find_repeats(arr):
"""
Find repeats and repeat counts.
Parameters
----------
arr : array_like
Input array. This is cast to float64.
Returns
-------
values : ndarray
The unique values from the (flattened) input that are repeated.
counts : ndarray
Number of times the corresponding 'value' is repeated.
Notes
-----
In numpy >= 1.9 `numpy.unique` provides similar functionality. The main
difference is that `find_repeats` only returns repeated values.
Examples
--------
>>> from scipy import stats
>>> stats.find_repeats([2, 1, 2, 3, 2, 2, 5])
RepeatedResults(values=array([2.]), counts=array([4]))
>>> stats.find_repeats([[10, 20, 1, 2], [5, 5, 4, 4]])
RepeatedResults(values=array([4., 5.]), counts=array([2, 2]))
"""
# Note: always copies.
return RepeatedResults(*_find_repeats(np.array(arr, dtype=np.float64)))
def _sum_of_squares(a, axis=0):
"""
Square each element of the input array, and return the sum(s) of that.
Parameters
----------
a : array_like
Input array.
axis : int or None, optional
Axis along which to calculate. Default is 0. If None, compute over
the whole array `a`.
Returns
-------
sum_of_squares : ndarray
The sum along the given axis for (a**2).
See Also
--------
_square_of_sums : The square(s) of the sum(s) (the opposite of
`_sum_of_squares`).
"""
a, axis = _chk_asarray(a, axis)
return np.sum(a*a, axis)
def _square_of_sums(a, axis=0):
"""
Sum elements of the input array, and return the square(s) of that sum.
Parameters
----------
a : array_like
Input array.
axis : int or None, optional
Axis along which to calculate. Default is 0. If None, compute over
the whole array `a`.
Returns
-------
square_of_sums : float or ndarray
The square of the sum over `axis`.
See Also
--------
_sum_of_squares : The sum of squares (the opposite of `square_of_sums`).
"""
a, axis = _chk_asarray(a, axis)
s = np.sum(a, axis)
if not np.isscalar(s):
return s.astype(float) * s
else:
return float(s) * s
def rankdata(a, method='average', *, axis=None):
"""
Assign ranks to data, dealing with ties appropriately.
By default (``axis=None``), the data array is first flattened, and a flat
array of ranks is returned. Separately reshape the rank array to the
shape of the data array if desired (see Examples).
Ranks begin at 1. The `method` argument controls how ranks are assigned
to equal values. See [1]_ for further discussion of ranking methods.
Parameters
----------
a : array_like
The array of values to be ranked.
method : {'average', 'min', 'max', 'dense', 'ordinal'}, optional
The method used to assign ranks to tied elements.
The following methods are available (default is 'average'):
* 'average': The average of the ranks that would have been assigned to
all the tied values is assigned to each value.
* 'min': The minimum of the ranks that would have been assigned to all
the tied values is assigned to each value. (This is also
referred to as "competition" ranking.)
* 'max': The maximum of the ranks that would have been assigned to all
the tied values is assigned to each value.
* 'dense': Like 'min', but the rank of the next highest element is
assigned the rank immediately after those assigned to the tied
elements.
* 'ordinal': All values are given a distinct rank, corresponding to
the order that the values occur in `a`.
axis : {None, int}, optional
Axis along which to perform the ranking. If ``None``, the data array
is first flattened.
Returns
-------
ranks : ndarray
An array of size equal to the size of `a`, containing rank
scores.
References
----------
.. [1] "Ranking", https://en.wikipedia.org/wiki/Ranking
Examples
--------
>>> from scipy.stats import rankdata
>>> rankdata([0, 2, 3, 2])
array([ 1. , 2.5, 4. , 2.5])
>>> rankdata([0, 2, 3, 2], method='min')
array([ 1, 2, 4, 2])
>>> rankdata([0, 2, 3, 2], method='max')
array([ 1, 3, 4, 3])
>>> rankdata([0, 2, 3, 2], method='dense')
array([ 1, 2, 3, 2])
>>> rankdata([0, 2, 3, 2], method='ordinal')
array([ 1, 2, 4, 3])
>>> rankdata([[0, 2], [3, 2]]).reshape(2,2)
array([[1. , 2.5],
[4. , 2.5]])
>>> rankdata([[0, 2, 2], [3, 2, 5]], axis=1)
array([[1. , 2.5, 2.5],
[2. , 1. , 3. ]])
"""
if method not in ('average', 'min', 'max', 'dense', 'ordinal'):
raise ValueError('unknown method "{0}"'.format(method))
if axis is not None:
a = np.asarray(a)
if a.size == 0:
# The return values of `normalize_axis_index` are ignored. The
# call validates `axis`, even though we won't use it.
# use scipy._lib._util._normalize_axis_index when available
np.core.multiarray.normalize_axis_index(axis, a.ndim)
dt = np.float64 if method == 'average' else np.int_
return np.empty(a.shape, dtype=dt)
return np.apply_along_axis(rankdata, axis, a, method)
arr = np.ravel(np.asarray(a))
algo = 'mergesort' if method == 'ordinal' else 'quicksort'
sorter = np.argsort(arr, kind=algo)
inv = np.empty(sorter.size, dtype=np.intp)
inv[sorter] = np.arange(sorter.size, dtype=np.intp)
if method == 'ordinal':
return inv + 1
arr = arr[sorter]
obs = np.r_[True, arr[1:] != arr[:-1]]
dense = obs.cumsum()[inv]
if method == 'dense':
return dense
# cumulative counts of each unique value
count = np.r_[np.nonzero(obs)[0], len(obs)]
if method == 'max':
return count[dense]
if method == 'min':
return count[dense - 1] + 1
# average method
return .5 * (count[dense] + count[dense - 1] + 1)
|
the-stack_0_8535 | #****************************************************#
# This file is part of OPTALG. #
# #
# Copyright (c) 2019, Tomas Tinoco De Rubira. #
# #
# OPTALG is released under the BSD 2-clause license. #
#****************************************************#
from __future__ import print_function
import numpy as np
from functools import reduce
from .opt_solver_error import *
from .problem import cast_problem, OptProblem
from .opt_solver import OptSolver
from optalg.lin_solver import new_linsolver
from scipy.sparse import bmat,eye,coo_matrix,tril
class OptSolverAugL(OptSolver):
parameters = {'beta_large' : 0.9, # for decreasing sigma when progress
'beta_med' : 0.5, # for decreasing sigma when forcing
'beta_small' : 0.1, # for decreasing sigma
'feastol' : 1e-4, # feasibility tolerance
'optol' : 1e-4, # optimality tolerance
'gamma' : 0.1, # for determining required decrease in ||f||
'tau' : 0.1, # for reductions in ||GradF||
'kappa' : 1e-2, # for initializing sigma
'maxiter' : 1000, # maximum iterations
'sigma_min' : 1e-12, # minimum sigma
'sigma_init_min' : 1e-3, # minimum initial sigma
'sigma_init_max' : 1e8, # maximum initial sigma
'theta_min' : 1e-6, # minimum barrier parameter
'theta_max' : 1e0 , # maximum initial barrier parameter
'lam_reg' : 1e-4, # regularization of first order dual update
'subprob_force' : 10, # for periodic sigma decrease
'subprob_maxiter' : 150, # maximum subproblem iterations
'linsolver' : 'default', # linear solver
'quiet' : False} # flag for omitting output
def __init__(self):
"""
Augmented Lagrangian algorithm.
"""
OptSolver.__init__(self)
self.parameters = OptSolverAugL.parameters.copy()
self.linsolver1 = None
self.linsolver2 = None
self.barrier = None
def supports_properties(self, properties):
for p in properties:
if p not in [OptProblem.PROP_CURV_LINEAR,
OptProblem.PROP_CURV_QUADRATIC,
OptProblem.PROP_CURV_NONLINEAR,
OptProblem.PROP_VAR_CONTINUOUS,
OptProblem.PROP_TYPE_FEASIBILITY,
OptProblem.PROP_TYPE_OPTIMIZATION]:
return False
return True
def solve(self, problem):
# Local vars
norm2 = self.norm2
norminf = self.norminf
params = self.parameters
# Parameters
tau = params['tau']
gamma = params['gamma']
kappa = params['kappa']
optol = params['optol']
feastol = params['feastol']
beta_small = params['beta_small']
beta_large = params['beta_large']
sigma_init_min = params['sigma_init_min']
sigma_init_max = params['sigma_init_max']
theta_max = params['theta_max']
theta_min = params['theta_min']
# Problem
problem = cast_problem(problem)
self.problem = problem
# Linear solver
self.linsolver1 = new_linsolver(params['linsolver'],'symmetric')
self.linsolver2 = new_linsolver(params['linsolver'],'symmetric')
# Reset
self.reset()
# Barrier
self.barrier = AugLBarrier(problem.get_num_primal_variables(),
problem.l,
problem.u,
eps=feastol/10.)
# Init primal
if problem.x is not None:
self.x = self.barrier.to_interior(problem.x.copy(),
eps=feastol/10.)
else:
self.x = (self.barrier.umax+self.barrier.umin)/2.
assert(np.all(self.x > self.barrier.umin))
assert(np.all(self.x < self.barrier.umax))
# Init dual
if problem.lam is not None:
self.lam = problem.lam.copy()
else:
self.lam = np.zeros(problem.b.size)
if problem.nu is not None:
self.nu = problem.nu.copy()
else:
self.nu = np.zeros(problem.f.size)
try:
if problem.pi is not None:
self.pi = problem.pi.copy()
else:
self.pi = np.zeros(self.x.size)
except AttributeError:
self.pi = np.zeros(self.x.size)
try:
if problem.mu is not None:
self.mu = problem.mu.copy()
else:
self.mu = np.zeros(self.x.size)
except AttributeError:
self.mu = np.zeros(self.x.size)
# Constants
self.sigma = 0.
self.theta = 0.
self.code = ''
self.nx = self.x.size
self.na = problem.b.size
self.nf = problem.f.size
self.ox = np.zeros(self.nx)
self.oa = np.zeros(self.na)
self.of = np.zeros(self.nf)
self.Ixx = eye(self.nx,format='coo')
self.Iff = eye(self.nf,format='coo')
self.Iaa = eye(self.na,format='coo')
# Objective scaling
fdata = self.func(self.x)
self.obj_sca = np.maximum(np.abs(fdata.phi)/100.,1.)
fdata = self.func(self.x)
# Init penalty and barrier parameters
self.sigma = kappa*norm2(fdata.GradF)/np.maximum(norm2(fdata.gphi),1.)
self.sigma = np.minimum(np.maximum(self.sigma,sigma_init_min),sigma_init_max)
self.theta = kappa*norm2(fdata.GradF)/(self.sigma*np.maximum(norm2(fdata.gphiB),1.))
self.theta = np.minimum(np.maximum(self.theta,theta_min),theta_max)
fdata = self.func(self.x)
# Init residuals
pres_prev = norminf(fdata.pres)
gLmax_prev = norminf(fdata.GradF)
# Init dual update
if pres_prev <= feastol:
self.update_multiplier_estimates()
fdata = self.func(self.x)
# Outer iterations
self.k = 0
self.useH = False
self.code = list('----')
while True:
# Solve subproblem
self.solve_subproblem(tau*gLmax_prev)
# Check done
if self.is_status_solved():
return
# Measure progress
pres = norminf(fdata.pres)
dres = norminf(fdata.dres)
gLmax = norminf(fdata.GradF)
# Penaly update
if pres <= np.maximum(gamma*pres_prev,feastol):
self.sigma *= beta_large
self.code[1] = 'p'
else:
self.sigma *= beta_small
self.code[1] = 'n'
# Dual update
self.update_multiplier_estimates()
# Barrier update
self.theta = np.maximum(self.theta*beta_small,theta_min)
# Update refs
pres_prev = pres
gLmax_prev = gLmax
# Update iters
self.k += 1
def solve_subproblem(self,delta):
# Local vars
norm2 = self.norm2
norminf = self.norminf
params = self.parameters
problem = self.problem
barrier = self.barrier
# Params
quiet = params['quiet']
maxiter = params['maxiter']
feastol = params['feastol']
optol = params['optol']
maxiter = params['maxiter']
theta_min = params['theta_min']
sigma_min = params['sigma_min']
beta_large = params['beta_large']
beta_med = params['beta_med']
beta_small = params['beta_small']
subprob_force = params['subprob_force']
subprob_maxiter = params['subprob_maxiter']
# Print header
self.print_header()
# Init eval
fdata = self.func(self.x)
# Inner iterations
i = 0
j = 0
alpha = 0.
while True:
# Compute info
pres = norminf(fdata.pres)
dres = norminf(fdata.dres)
dmax = max(map(norminf,[self.lam,self.nu,self.mu,self.pi]))
gLmax = norminf(fdata.GradF)
# Show info
if not quiet:
print('{0:^4d}'.format(self.k),end=' ')
print('{0:^9.2e}'.format(problem.phi),end=' ')
print('{0:^9.2e}'.format(pres),end=' ')
print('{0:^9.2e}'.format(dres),end=' ')
print('{0:^9.2e}'.format(gLmax),end=' ')
print('{0:^8.1e}'.format(dmax),end=' ')
print('{0:^8.1e}'.format(alpha),end=' ')
print('{0:^7.1e}'.format(self.sigma),end=' ')
print('{0:^7.1e}'.format(self.theta),end=' ')
print('{0:^7s}'.format(reduce(lambda x,y: x+y,self.code)),end=' ')
if self.info_printer:
self.info_printer(self,False)
else:
print('')
# Clear code
self.code = list('----')
# Check solved
if pres <= feastol and dres <= optol and self.theta <= theta_min:
self.set_status(self.STATUS_SOLVED)
self.set_error_msg('')
return
# Check only theta missing
if pres <= feastol and dres <= optol:
return
# Check subproblem solved
if gLmax <= delta:
return
# Check total maxiters
if self.k >= maxiter:
raise OptSolverError_MaxIters(self)
# Check penalty
if self.sigma < sigma_min:
raise OptSolverError_SmallPenalty(self)
# Check custom terminations
for t in self.terminations:
t(self)
# Search direction
p = self.compute_search_direction(self.useH)
# Max steplength
ppos = p > 1e-15
pneg = p < -1e-15
a1 = np.min(((barrier.umax-self.x)[ppos])/(p[ppos])) if ppos.sum() else np.inf
a2 = np.min(((barrier.umin-self.x)[pneg])/(p[pneg])) if pneg.sum() else np.inf
alpha_max = 0.98*min([a1,a2])
if not alpha_max:
raise OptSolverError_NumProblems(self)
try:
# Line search
alpha,fdata = self.line_search(self.x,p,fdata.F,fdata.GradF,self.func,alpha_max)
# Update x
self.x += alpha*p
except OptSolverError_LineSearch:
# Update
self.sigma *= beta_large
fdata = self.func(self.x)
self.code[3] = 'b'
if self.useH:
self.useH = False
i = 0
alpha = 0.
# Update iter count
self.k += 1
i += 1
j += 1
# Periodic force
if i >= subprob_force:
self.sigma *= beta_large
fdata = self.func(self.x)
self.code[2] = 'f'
self.useH = True
i = 0
# Periodic maxiter
if j >= subprob_maxiter:
self.sigma *= beta_med
self.update_multiplier_estimates()
fdata = self.func(self.x)
self.code[2] = 'm'
j = 0
def compute_search_direction(self,useH):
fdata = self.fdata
problem = self.problem
barrier = self.barrier
sigma = self.sigma
theta = self.theta
problem.combine_H(-sigma*self.nu+problem.f,not useH)
self.code[0] = 'h' if useH else 'g'
Hfsigma = problem.H_combined/sigma
Hphi = fdata.Hphi
HphiB = fdata.HphiB
G = coo_matrix((np.concatenate((Hphi.data,theta*HphiB.data,Hfsigma.data)),
(np.concatenate((Hphi.row,HphiB.row,Hfsigma.row)),
np.concatenate((Hphi.col,HphiB.col,Hfsigma.col)))))
if problem.A.size:
W = bmat([[G,None,None],
[problem.J,-sigma*self.Iff,None],
[problem.A,None,-sigma*self.Iaa]])
else:
W = bmat([[G,None],
[problem.J,-sigma*self.Iff]])
b = np.hstack((-fdata.GradF/sigma,
self.of,
self.oa))
if not self.linsolver1.is_analyzed():
self.linsolver1.analyze(W)
try:
return self.linsolver1.factorize_and_solve(W,b)[:self.x.size]
except Exception:
return np.zeros(self.x.size)
def func(self,x):
# Norm
norm = self.norminf
# Multipliers
lam = self.lam
nu = self.nu
# Penalty
sigma = self.sigma
theta = self.theta
# Objects
p = self.problem
fdata = self.fdata
barrier = self.barrier
# Eval
p.eval(x)
barrier.eval(x)
# Problem data
phi = p.phi/self.obj_sca
gphi = p.gphi/self.obj_sca
Hphi = p.Hphi/self.obj_sca
f = p.f
J = p.J
A = p.A
r = A*x-p.b
# Barrier data
phiB = barrier.phi
gphiB = barrier.gphi
HphiB = barrier.Hphi
# Intermediate
nuTf = np.dot(nu,f)
y = (sigma*nu-f)
JT = J.T
JTnu = JT*nu
JTy = JT*y
# Intermediate
lamTr = np.dot(lam,r)
z = (sigma*lam-r)
AT = A.T
ATlam = AT*lam
ATz = AT*z
pres = np.hstack((r,f))
dres = gphi+theta*gphiB-ATlam-JTnu
dres_den = 1.+norm(gphi)+theta*norm(gphiB)+norm(A.data)*norm(lam)+norm(J.data)*norm(nu)
fdata.ATlam = ATlam
fdata.JTnu = JTnu
fdata.r = r
fdata.f = f
fdata.F = sigma*phi + sigma*theta*phiB - sigma*(nuTf+lamTr) + 0.5*np.dot(pres,pres)
fdata.GradF = sigma*gphi + sigma*theta*gphiB - JTy - ATz
fdata.pres = pres
fdata.dres = dres/dres_den
fdata.phi = phi
fdata.gphi = gphi
fdata.Hphi = Hphi
fdata.phiB = phiB
fdata.gphiB = gphiB
fdata.HphiB = HphiB
return fdata
def print_header(self):
# Local vars
params = self.parameters
quiet = params['quiet']
if not quiet:
if self.k == 0:
print('\nSolver: augL')
print('------------')
print('{0:^4}'.format('k'), end=' ')
print('{0:^9}'.format('phi'), end=' ')
print('{0:^9}'.format('pres'), end=' ')
print('{0:^9}'.format('dres'), end=' ')
print('{0:^9}'.format('gLmax'), end=' ')
print('{0:^8}'.format('dmax'), end=' ')
print('{0:^8}'.format('alpha'), end=' ')
print('{0:^7}'.format('sigma'), end=' ')
print('{0:^7}'.format('theta'), end=' ')
print('{0:^7}'.format('code'), end=' ')
if self.info_printer:
self.info_printer(self,True)
else:
print('')
else:
print('')
def update_multiplier_estimates(self):
# Local variables
params = self.parameters
problem = self.problem
barrier = self.barrier
fdata = self.fdata
# Parameters
lam_reg = params['lam_reg']
sigma = self.sigma
theta = self.theta
eta = lam_reg
# Eval
fdata = self.func(self.x)
A = problem.A
J = problem.J
AT = A.T
JT = J.T
t = fdata.gphi+theta*fdata.gphiB-fdata.ATlam-fdata.JTnu
if problem.A.size:
W = bmat([[eta*self.Iaa,None,None],
[None,eta*self.Iff,None],
[AT,JT,-self.Ixx]],format='coo')
else:
W = bmat([[eta*self.Iff,None],
[JT,-self.Ixx]],format='coo')
b = np.hstack((A*t,
J*t,
self.ox))
if W.size:
if not self.linsolver2.is_analyzed():
self.linsolver2.analyze(W)
sol = self.linsolver2.factorize_and_solve(W,b)
self.lam += sol[:self.na]
self.nu += sol[self.na:self.na+self.nf]
self.mu = theta/(barrier.umax-self.x)
self.pi = theta/(self.x-barrier.umin)
class AugLBarrier:
"""
Class for handling bounds using barrier.
"""
def __init__(self, n, umin=None, umax=None, eps=1e-5, inf=1e8):
assert(n >= 0)
assert(inf > 0)
if umin is None or not umin.size:
umin = -inf*np.ones(n)
if umax is None or not umax.size:
umax = inf*np.ones(n)
assert(np.all(umin <= umax))
if n > 0:
umax = umax+eps
umin = umin-eps
assert(umin.size == n)
assert(umin.size == umax.size)
assert(np.all(umin < umax))
self.n = n
self.inf = inf
self.umin = umin
self.umax = umax
self.phi = 0
self.gphi = np.zeros(n)
self.Hphi_row = np.array(range(n))
self.Hphi_col = np.array(range(n))
self.Hphi_data = np.zeros(n)
self.Hphi = coo_matrix((self.Hphi_data,(self.Hphi_row,self.Hphi_col)),shape=(n,n))
def eval(self,u):
assert(u.size == self.n)
dumax = np.maximum(self.umax-u,1e-12)
dumin = np.maximum(u-self.umin,1e-12)
self.phi = -np.sum(np.log(dumax)+np.log(dumin))
self.gphi[:] = -1./dumin+1./dumax
self.Hphi_data[:] = 1./np.square(dumin)+1./np.square(dumax)
def to_interior(self,x, eps=1e-5):
return np.maximum(np.minimum(x, self.umax-eps), self.umin+eps)
|
the-stack_0_8537 | # 2020 CCC PROBLEM J1'S SOLUTION:
# declaring variables for the treat sizes.
SMALL_TREATS = int(input())
MEDIUM_TREATS = int(input())
LARGE_TREATS = int(input())
# arithmetic calculation for the determinant.
determinant = (1 * SMALL_TREATS) + (2 * MEDIUM_TREATS) + (3 * LARGE_TREATS)
# determining whether the dog is happy based on the determinant.
if determinant >= 10:
print("happy")
else:
print("sad") |
the-stack_0_8538 | import logging
from django.core.management.base import BaseCommand
from django.db import connection, connections
from django.conf import settings
from usaspending.common.helpers import timer
logger = logging.getLogger('console')
# Website columns need for update from financial_accounts_by_program_activity_object_class
financial_accounts_oc = [
('broker_submission_id', 'sub'),
('allocation_transfer_agency_id', 'tas'),
('agency_id', 'tas'),
('beginning_period_of_availability', 'tas'),
('ending_period_of_availability', 'tas'),
('availability_type_code', 'tas'),
('main_account_code', 'tas'),
('sub_account_code', 'tas'),
('object_class', 'oc'),
('program_activity_code', 'pa'),
('direct_reimbursable', 'oc'),
('ussgl498100_upward_adjust_pri_deliv_orders_oblig_unpaid_cpe', 'ds_file_table'),
('ussgl488100_upward_adjust_pri_undeliv_order_oblig_unpaid_cpe', 'ds_file_table')
]
# Website columns need for update from financial_accounts_by_awards (Adds fain, uri, and piid columns)
financial_accounts_awards = [
('fain', ' ds_file_table'),
('uri', ' ds_file_table'),
('piid', ' ds_file_table')
] + financial_accounts_oc[:]
# website -> broker mappings with specific mappings different from settings.py mappings
broker_website_cols_mapping = {
'broker_submission_id': 'db_file_table.submission_id',
"allocation_transfer_agency_id": "COALESCE(allocation_transfer_agency, '''')",
'agency_id': 'agency_identifier',
'object_class': 'object_class',
'program_activity_code': 'program_activity_code',
'beginning_period_of_availability': "COALESCE(beginning_period_of_availa, '''')",
'ending_period_of_availability': "COALESCE(ending_period_of_availabil, '''')",
'availability_type_code': "COALESCE(availability_type_code, '''')",
'direct_reimbursable': "CASE WHEN by_direct_reimbursable_fun = ''D'' then 1" +
"WHEN by_direct_reimbursable_fun = ''R'' then 2 ELSE NULL END"
}
class Command(BaseCommand):
help = "Fix File B and File C mappings due to invalid database column mappings"
@staticmethod
def get_list_of_submissions():
# Gets a list from broker of the submissions that are certified (type 2) and not updated
broker_connection = connections['data_broker'].cursor()
broker_connection.execute('SELECT submission_id from submission sub ' +
'WHERE sub.publish_status_id = 2 ORDER BY submission_id;')
return broker_connection.fetchall()
@staticmethod
def get_list_of_broker_cols(website_cols):
# Returns sql string statement to pull columns from broker
# First looks at broker_website_cols_translation that have a specific website to broker mapping
# Then looks at settings.py for the overall website website->broker mapping
return ",".join([
broker_website_cols_mapping.get(column, settings.LONG_TO_TERSE_LABELS.get(column))
for column, table in website_cols])
@staticmethod
def get_list_of_broker_cols_types(website_cols):
# Returns sql string statement to create table to compare to website type
# Needs to add a type (text or numeric) in order to match it to the website
return ",".join([
"{column} {type}".format(column=column, type='text' if column not in [
'ussgl498100_upward_adjust_pri_deliv_orders_oblig_unpaid_cpe',
'ussgl488100_upward_adjust_pri_undeliv_order_oblig_unpaid_cpe',
'broker_submission_id'] else "numeric")
for column, table in website_cols
])
@staticmethod
def get_website_row_formatted(website_cols):
# Return sql string with website columns formatted for select statement
return ",".join(['{0}.{1}'.format(table, column)
for column, table in website_cols])
@staticmethod
def get_cols_to_update(website_cols):
# Returning sql string of columns that will be updated in SET statement
# Ensures only columns that are not used as identifiers in the database are included
return ",".join(['{0} = broker.{0} * -1'.format(column) for column, table in website_cols
if table == 'ds_file_table' and column not in ['fain', 'uri', 'piid']])
@staticmethod
def get_file_table_joins(website_cols):
# Returns table joins according to identifier columns based on the file type
return " AND ".join(['broker.{0} = {1}.{0}'.format(column, table)
for column, table in website_cols
if table != 'ds_file_table' or column in ['fain', 'uri', 'piid']])
@staticmethod
def get_rows_to_update(file_type, submission_id, broker_cols, broker_cols_type, website_cols):
# Creates table with rows necessary to update
query_arguments = {'submission_id': submission_id,
'broker_cols': broker_cols,
'dblink_cols_type': broker_cols_type,
'website_cols': website_cols
}
if file_type == 'C':
query_arguments['broker_table'] = 'award_financial'
query_arguments['website_table'] = 'financial_accounts_by_awards'
query_arguments['broker_tmp_table'] = 'file_c_rows_to_update'
else:
query_arguments['broker_table'] = 'object_class_program_activity'
query_arguments['website_table'] = 'financial_accounts_by_program_activity_object_class'
query_arguments['broker_tmp_table'] = 'file_b_rows_to_update'
sql_statement = """
CREATE TEMPORARY TABLE {broker_tmp_table} AS
SELECT * from dblink(
'broker_server',
'SELECT
{broker_cols}
FROM {broker_table} db_file_table
INNER JOIN submission sub
ON db_file_table.submission_id = sub.submission_id
WHERE sub.publish_status_id = 2
AND db_file_table.submission_id = {submission_id};'
) AS (
{dblink_cols_type}
)
EXCEPT
SELECT
{website_cols}
from {website_table} ds_file_table
LEFT OUTER JOIN object_class oc
ON ds_file_table.object_class_id = oc.id
LEFT OUTER JOIN ref_program_activity pa
ON ds_file_table.program_activity_id = pa.id
LEFT OUTER JOIN treasury_appropriation_account tas
ON ds_file_table.treasury_account_id = tas.treasury_account_identifier
INNER JOIN submission_attributes sub
ON ds_file_table.submission_id = sub.submission_id
where sub.broker_submission_id = {submission_id};
""".format(**query_arguments)
return sql_statement
@staticmethod
def update_website_rows(ds_file_table, broker_tmp_table, set_statement, table_joins):
sql_statement = """
UPDATE {ds_file_table} ds_file_table
SET {set_statement}
FROM
{broker_tmp_table} broker,
object_class oc,
ref_program_activity pa,
treasury_appropriation_account tas,
submission_attributes sub
where ds_file_table.object_class_id = oc.id
AND ds_file_table.program_activity_id = pa.id
AND ds_file_table.treasury_account_id = tas.treasury_account_identifier
AND ds_file_table.submission_id = sub.submission_id
AND {table_joins}
;
""".format(ds_file_table=ds_file_table, broker_tmp_table=broker_tmp_table, table_mappings=table_joins,
set_statement=set_statement, table_joins=table_joins)
return sql_statement
def handle(self, *args, **options):
"""
Updates the column ussgl498100_upward_adjust_pri_deliv_orders_oblig_unpaid_cpe due to the incorrect
mapping in settings.py
"""
ds_cursor = connection.cursor()
logger.info('Begin updating file B and C')
broker_cols_b = self.get_list_of_broker_cols(financial_accounts_oc)
broker_cols_type_b = self.get_list_of_broker_cols_types(financial_accounts_oc)
website_cols_b = self.get_website_row_formatted(financial_accounts_oc)
website_update_text_b = self.get_cols_to_update(financial_accounts_oc)
website_cols_joins_b = self.get_file_table_joins(financial_accounts_oc)
broker_cols_c = self.get_list_of_broker_cols(financial_accounts_awards)
broker_cols_type_c = self.get_list_of_broker_cols_types(financial_accounts_awards)
website_cols_c = self.get_website_row_formatted(financial_accounts_awards)
website_update_text_c = self.get_cols_to_update(financial_accounts_awards)
website_cols_joins_c = self.get_file_table_joins(financial_accounts_awards)
with timer('getting submission ids to update', logger.info):
submissions_to_update = self.get_list_of_submissions()
for submission in submissions_to_update:
submission_id = submission[0]
# File B Updates
logger.info('loading rows data to update File B submission {}'.format(submission_id))
with timer('retrieving rows to update for File B submission {}'.format(submission_id), logger.info):
get_rows_to_update_query = self.get_rows_to_update('B', submission_id,
broker_cols_b, broker_cols_type_b,
website_cols_b)
ds_cursor.execute(get_rows_to_update_query)
with timer('updating rows for File B submission {}'.format(submission_id), logger.info):
update_rows = self.update_website_rows(
'financial_accounts_by_program_activity_object_class',
'file_b_rows_to_update', website_update_text_b, website_cols_joins_b
)
ds_cursor.execute(update_rows)
# File C updates
with timer('retrieving rows to update for File C submission {}'.format(submission_id), logger.info):
get_rows_to_update_query = self.get_rows_to_update(
'C',
submission_id,
broker_cols_c,
broker_cols_type_c,
website_cols_c)
ds_cursor.execute(get_rows_to_update_query)
with timer('updating rows for File C submission {}'.format(submission_id), logger.info):
update_rows = self.update_website_rows(
'financial_accounts_by_awards', 'file_c_rows_to_update', website_update_text_c, website_cols_joins_c
)
ds_cursor.execute(update_rows)
ds_cursor.execute("DROP TABLE file_b_rows_to_update")
ds_cursor.execute("DROP TABLE file_c_rows_to_update")
logger.info('Done updating file B and C mappings')
|
the-stack_0_8539 | """Base actions for the players to take."""
from csrv.model.actions import action
from csrv.model import appropriations
from csrv.model import cost
from csrv.model import errors
from csrv.model import events
from csrv.model import game_object
from csrv.model import parameters
from csrv.model.cards import card_info
class InstallProgram(action.Action):
DESCRIPTION = '[click]: Install a program'
COST_CLASS = cost.InstallProgramCost
REQUEST_CLASS = parameters.InstallProgramRequest
def __init__(self, game, player, card=None, cost=None):
action.Action.__init__(self, game, player, card=card, cost=cost)
self.cost.appropriations.append(appropriations.INSTALL_PROGRAMS)
if card_info.VIRUS in card.KEYWORDS:
self.cost.appropriations.append(appropriations.INSTALL_VIRUSES)
def resolve(self, response=None, ignore_clicks=False, ignore_all_costs=False):
if (not ignore_all_costs and
not self.cost.can_pay(response, ignore_clicks)):
raise errors.CostNotSatisfied(
'Not enough credits to install in that location.')
if response and response.programs_to_trash:
for program in response.programs_to_trash:
if program.location != self.game.runner.rig:
raise errors.InvalidResponse("You can't trash that")
program.trash()
if response and response.host:
if not response.host in self.card.install_host_targets():
raise errors.InvalidResponse(
'Cannot host this type of card')
if not response.host.meets_memory_limits(self.card):
raise errors.InvalidResponse(
'Host does not have enough memory free')
response.host.host_card(self.card)
action.Action.resolve(self, response,
ignore_clicks=ignore_clicks,
ignore_all_costs=ignore_all_costs)
self.player.rig.add(self.card)
@property
def description(self):
return 'Install %s' % self.card.NAME
|
the-stack_0_8542 | import json
import os
from typing import Optional
from eth_abi import encode_abi
from web3 import Web3, HTTPProvider
from web3.contract import Contract
try:
from web3.utils.abi import get_constructor_abi, merge_args_and_kwargs
from web3.utils.events import get_event_data
from web3.utils.filters import construct_event_filter_params
from web3.utils.contracts import encode_abi
from web3.middleware import geth_poa_middleware
except ImportError:
from web3._utils.abi import get_constructor_abi, merge_args_and_kwargs
from web3._utils.events import get_event_data
from web3._utils.filters import construct_event_filter_params
from web3._utils.contracts import encode_abi
from web3.middleware import geth_poa_middleware
from eth_utils import (
keccak,
is_hex_address,
is_checksum_address,
to_hex
)
class NoNodeConfigured(Exception):
pass
class NeedPrivateKey(Exception):
pass
def check_good_node_url(node_url: str):
if not node_url:
raise NoNodeConfigured("You need to give --ethereum-node-url command line option or set it up in a config file")
def get_abi():
abi_file = os.path.join(os.path.dirname(__file__), "erc20.abi.json")
with open(abi_file, "rt") as inp:
return json.load(inp)
def create_web3(url: str) -> Web3:
"""Web3 initializer."""
if isinstance(url, Web3):
# Shortcut for testing
url.middleware_onion.inject(geth_poa_middleware, layer=0)
return url
else:
w3 = Web3(HTTPProvider(url))
w3.middleware_onion.inject(geth_poa_middleware, layer=0)
return w3
def integer_hash(number: int):
return int(keccak(number).hex(), 16)
def validate_ethereum_address(address: str):
"""Clever Ethereum address validator.
Assume all lowercase addresses are not checksummed.
"""
if len(address) < 42:
raise ValueError("Not an Ethereum address: {}".format(address))
try:
if not is_hex_address(address):
raise ValueError("Not an Ethereum address: {}".format(address))
except UnicodeEncodeError:
raise ValueError("Could not decode: {}".format(address))
# Check if checksummed address if any of the letters is upper case
if any([c.isupper() for c in address]):
if not is_checksum_address(address):
raise ValueError("Not a checksummed Ethereum address: {}".format(address))
def get_constructor_arguments(contract: Contract, args: Optional[list] = None, kwargs: Optional[dict] = None):
"""Get constructor arguments for Etherscan verify.
https://etherscanio.freshdesk.com/support/solutions/articles/16000053599-contract-verification-constructor-arguments
"""
# return contract._encode_constructor_data(args=args, kwargs=kwargs)
constructor_abi = get_constructor_abi(contract.abi)
# constructor_abi can be none in case of libraries
if constructor_abi is None:
return to_hex(contract.bytecode)
if args is not None:
return contract.encodeABI(constructor_abi['name'], args)[2:] # No 0x
else:
constructor_abi = get_constructor_abi(contract.abi)
kwargs = kwargs or {}
arguments = merge_args_and_kwargs(constructor_abi, [], kwargs)
# deploy_data = add_0x_prefix(
# contract._encode_abi(constructor_abi, arguments)
# )
# TODO: Looks like recent Web3.py ABI change
deploy_data = encode_abi(contract.web3, constructor_abi, arguments)
return deploy_data
def getLogs(self,
argument_filters=None,
fromBlock=None,
toBlock="latest",
address=None,
topics=None):
"""Get events using eth_getLogs API.
This is a stateless method, as opposite to createFilter.
It can be safely called against nodes which do not provide eth_newFilter API, like Infura.
:param argument_filters:
:param fromBlock:
:param toBlock:
:param address:
:param topics:
:return:
"""
if fromBlock is None:
raise TypeError("Missing mandatory keyword argument to getLogs: fromBlock")
abi = self._get_event_abi()
argument_filters = dict()
_filters = dict(**argument_filters)
# Construct JSON-RPC raw filter presentation based on human readable Python descriptions
# Namely, convert event names to their keccak signatures
data_filter_set, event_filter_params = construct_event_filter_params(
abi,
abi_codec=self.web3.codec,
contract_address=self.address,
argument_filters=_filters,
fromBlock=fromBlock,
toBlock=toBlock,
address=address,
topics=topics,
)
# Call JSON-RPC API
logs = self.web3.eth.getLogs(event_filter_params)
# Convert raw binary data to Python proxy objects as described by ABI
for entry in logs:
yield get_event_data(self.web3.codec, abi, entry)
|
the-stack_0_8543 | #!/usr/bin/env python3
"""
Example: Write the contents of a Buffer to disk.
"""
from supercollider import Server, Synth, Buffer, HEADER_FORMAT_WAV
import math
OUTPUT_FILE = "/tmp/440.wav"
#-------------------------------------------------------------------------------
# Create connection to default server on localhost:57110
#-------------------------------------------------------------------------------
server = Server()
#-------------------------------------------------------------------------------
# Create a Buffer, generate a 440Hz sine, and write to a .wav.
#-------------------------------------------------------------------------------
length = 1024
server_status = server.get_status()
sample_rate = server_status["sample_rate_nominal"]
buf = Buffer.alloc(server, length)
buf.set([ math.sin(n * math.pi * 2.0 * 440.0 / sample_rate) for n in range(int(length)) ])
buf.write(OUTPUT_FILE, HEADER_FORMAT_WAV)
print("Written buffer to %s" % OUTPUT_FILE)
|
the-stack_0_8545 | from random import randint
"""
Найти наименьшее натуральное число, записываемое в десятичной системе счисления только с помощью цифр 0 и 1,
которое делится без остатка на заданное число К (2 ≤ К ≤ 100).
"""
def first_exercise(numbers, divider):
array = [number for number in numbers if number % divider == 0]
if len(array) != 0:
return min(array)
else:
return "Список пустой!"
numbers = [int("".join([str(randint(0, 1)) for _ in range(0, 10)])) for _ in range(100)]
divider = int(input("Введите делитель: "))
print(first_exercise(numbers, divider))
|
the-stack_0_8546 | import os
import posixpath
import string
from pathlib import PurePath
from shutil import copyfileobj, rmtree
import boto3
from flask import current_app, redirect, send_file
from flask.helpers import safe_join
from werkzeug.utils import secure_filename
from CTFd.utils import get_app_config
from CTFd.utils.encoding import hexencode
class BaseUploader(object):
def __init__(self):
raise NotImplementedError
def store(self, fileobj, filename):
raise NotImplementedError
def upload(self, file_obj, filename):
raise NotImplementedError
def download(self, filename):
raise NotImplementedError
def delete(self, filename):
raise NotImplementedError
def sync(self):
raise NotImplementedError
class FilesystemUploader(BaseUploader):
def __init__(self, base_path=None):
super(BaseUploader, self).__init__()
self.base_path = base_path or current_app.config.get("UPLOAD_FOLDER")
def store(self, fileobj, filename):
location = os.path.join(self.base_path, filename)
directory = os.path.dirname(location)
if not os.path.exists(directory):
os.makedirs(directory)
with open(location, "wb") as dst:
copyfileobj(fileobj, dst, 16384)
return filename
def upload(self, file_obj, filename):
if len(filename) == 0:
raise Exception("Empty filenames cannot be used")
filename = secure_filename(filename)
md5hash = hexencode(os.urandom(16))
file_path = posixpath.join(md5hash, filename)
return self.store(file_obj, file_path)
def download(self, filename):
return send_file(safe_join(self.base_path, filename), as_attachment=True)
def delete(self, filename):
if os.path.exists(os.path.join(self.base_path, filename)):
file_path = PurePath(filename).parts[0]
rmtree(os.path.join(self.base_path, file_path))
return True
return False
def sync(self):
pass
class S3Uploader(BaseUploader):
def __init__(self):
super(BaseUploader, self).__init__()
self.s3 = self._get_s3_connection()
self.bucket = get_app_config("AWS_S3_BUCKET")
def _get_s3_connection(self):
access_key = get_app_config("AWS_ACCESS_KEY_ID")
secret_key = get_app_config("AWS_SECRET_ACCESS_KEY")
endpoint = get_app_config("AWS_S3_ENDPOINT_URL")
client = boto3.client(
"s3",
aws_access_key_id=access_key,
aws_secret_access_key=secret_key,
endpoint_url=endpoint,
)
return client
def _clean_filename(self, c):
if c in string.ascii_letters + string.digits + "-" + "_" + ".":
return True
def store(self, fileobj, filename):
self.s3.upload_fileobj(fileobj, self.bucket, filename)
return filename
def upload(self, file_obj, filename):
filename = filter(
self._clean_filename, secure_filename(filename).replace(" ", "_")
)
filename = "".join(filename)
if len(filename) <= 0:
return False
md5hash = hexencode(os.urandom(16))
dst = md5hash + "/" + filename
self.s3.upload_fileobj(file_obj, self.bucket, dst)
return dst
def download(self, filename):
key = filename
filename = filename.split("/").pop()
url = self.s3.generate_presigned_url(
"get_object",
Params={
"Bucket": self.bucket,
"Key": key,
"ResponseContentDisposition": "attachment; filename={}".format(
filename
),
},
)
return redirect(url)
def delete(self, filename):
self.s3.delete_object(Bucket=self.bucket, Key=filename)
return True
def sync(self):
local_folder = current_app.config.get("UPLOAD_FOLDER")
# If the bucket is empty then Contents will not be in the response
bucket_list = self.s3.list_objects(Bucket=self.bucket).get("Contents", [])
for s3_key in bucket_list:
s3_object = s3_key["Key"]
# We don't want to download any directories
if s3_object.endswith("/") is False:
local_path = os.path.join(local_folder, s3_object)
directory = os.path.dirname(local_path)
if not os.path.exists(directory):
os.makedirs(directory)
self.s3.download_file(self.bucket, s3_object, local_path)
|
the-stack_0_8548 | # -*- coding:utf-8 -*-
# pylint: disable=C0103, C0413
"""
Initializing telegram bot
"""
from os import environ
from telebot import TeleBot, types
from config import DEFAULT_LANGUAGE, EN
TOKEN = environ.get("TELEGRAM_BOT_TOKEN")
APP_SITE = environ.get("APP_SITE")
DEFAULT_PARSE_MODE = "HTML"
MESSAGE_NOT_FOUND = "Sorry, but nothing was found for <b>%s</b>."
MESSAGE_SPECIFY_LOGLAN_WORD = (
"You need to specify the Loglan word you would like to find."
)
MESSAGE_SPECIFY_ENGLISH_WORD = (
"You need to specify the English word you would like to find."
)
MIN_NUMBER_OF_BUTTONS = 50
bot = TeleBot(TOKEN)
ADMIN = int(environ.get("TELEGRAM_ADMIN_ID"))
cbq = types.CallbackQuery
msg = types.Message
from bot import processor
|
the-stack_0_8550 | import os
import glob
import pandas as pd
game_files = glob.glob(os.path.join(os.getcwd(), 'games', '*.EVE'))
game_files.sort()
game_frames = []
for game_file in game_files:
game_frame = pd.read_csv(game_file, names=['type', 'multi2', 'multi3', 'multi4', 'multi5', 'multi6', 'event'])
game_frames.append(game_frame)
games = pd.concat(game_frames)
games.loc[games['multi5'] == '??', 'multi5'] = ''
identifiers = games['multi2'].str.extract(r'(.LS(\d{4})\d{5})')
identifiers = identifiers.fillna(method='ffill')
identifiers.columns = ['game_id', 'year']
games = pd.concat([games, identifiers], axis=1, sort=False)
games = games.fillna(' ')
games.loc[:, 'type'] = pd.Categorical(games.loc[:, 'type'])
print(games.head())
|
the-stack_0_8554 | import sys
import pygame
from bullet import Bullet
def check_keydown_events(event, ai_settings, screen, ship, bullets):
"""Respond to keypresses."""
if event.key == pygame.K_RIGHT:
ship.moving_right = True
elif event.key == pygame.K_LEFT:
ship.moving_left = True
elif event.key == pygame.K_SPACE:
fire_bullet(ai_settings, screen, ship, bullets)
def check_keyup_events(event, ship):
"""Respond to key releases."""
if event.key == pygame.K_RIGHT:
ship.moving_right = False
elif event.key == pygame.K_LEFT:
ship.moving_left = False
def check_events(ai_settings, screen, ship, bullets):
"""Respond to keypresses and mouse events."""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
check_keydown_events(event, ai_settings, screen, ship, bullets)
elif event.type == pygame.KEYUP:
check_keyup_events(event, ship)
def fire_bullet(ai_settings, screen, ship, bullets):
"""Fire a bullet, if limit not reached yet."""
# Create a new bullet, add to bullets group.
if len(bullets) < ai_settings.bullets_allowed:
new_bullet = Bullet(ai_settings, screen, ship)
bullets.add(new_bullet)
def update_screen(ai_settings, screen, ship, bullets):
"""Update images on the screen, and flip to the new screen."""
# Redraw the screen, each pass through the loop.
screen.fill(ai_settings.bg_color)
# Redraw all bullets, behind ship and aliens.
for bullet in bullets.sprites():
bullet.draw_bullet()
ship.blitme()
# Make the most recently drawn screen visible.
pygame.display.flip()
def update_bullets(bullets):
"""Update position of bullets, and get rid of old bullets."""
# Update bullet positions.
bullets.update()
# Get rid of bullets that have disappeared.
for bullet in bullets.copy():
if bullet.rect.bottom <= 0:
bullets.remove(bullet) |
the-stack_0_8557 | # Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import argparse
import llnl.util.tty as tty
import spack.cmd
import spack.environment as ev
import spack.repo
import spack.store
import spack.spec
import spack.binary_distribution as bindist
description = "create, download and install binary packages"
section = "packaging"
level = "long"
def setup_parser(subparser):
setup_parser.parser = subparser
subparsers = subparser.add_subparsers(help='buildcache sub-commands')
create = subparsers.add_parser('create', help=createtarball.__doc__)
create.add_argument('-r', '--rel', action='store_true',
help="make all rpaths relative" +
" before creating tarballs.")
create.add_argument('-f', '--force', action='store_true',
help="overwrite tarball if it exists.")
create.add_argument('-u', '--unsigned', action='store_true',
help="create unsigned buildcache" +
" tarballs for testing")
create.add_argument('-a', '--allow-root', action='store_true',
help="allow install root string in binary files " +
"after RPATH substitution")
create.add_argument('-k', '--key', metavar='key',
type=str, default=None,
help="Key for signing.")
create.add_argument('-d', '--directory', metavar='directory',
type=str, default='.',
help="directory in which to save the tarballs.")
create.add_argument(
'packages', nargs=argparse.REMAINDER,
help="specs of packages to create buildcache for")
create.set_defaults(func=createtarball)
install = subparsers.add_parser('install', help=installtarball.__doc__)
install.add_argument('-f', '--force', action='store_true',
help="overwrite install directory if it exists.")
install.add_argument('-m', '--multiple', action='store_true',
help="allow all matching packages ")
install.add_argument('-a', '--allow-root', action='store_true',
help="allow install root string in binary files " +
"after RPATH substitution")
install.add_argument('-u', '--unsigned', action='store_true',
help="install unsigned buildcache" +
" tarballs for testing")
install.add_argument(
'packages', nargs=argparse.REMAINDER,
help="specs of packages to install buildcache for")
install.set_defaults(func=installtarball)
listcache = subparsers.add_parser('list', help=listspecs.__doc__)
listcache.add_argument('-f', '--force', action='store_true',
help="force new download of specs")
listcache.add_argument(
'packages', nargs=argparse.REMAINDER,
help="specs of packages to search for")
listcache.set_defaults(func=listspecs)
dlkeys = subparsers.add_parser('keys', help=getkeys.__doc__)
dlkeys.add_argument(
'-i', '--install', action='store_true',
help="install Keys pulled from mirror")
dlkeys.add_argument(
'-t', '--trust', action='store_true',
help="trust all downloaded keys")
dlkeys.add_argument('-f', '--force', action='store_true',
help="force new download of keys")
dlkeys.set_defaults(func=getkeys)
def find_matching_specs(
pkgs, allow_multiple_matches=False, force=False, env=None):
"""Returns a list of specs matching the not necessarily
concretized specs given from cli
Args:
specs: list of specs to be matched against installed packages
allow_multiple_matches : if True multiple matches are admitted
Return:
list of specs
"""
hashes = env.all_hashes() if env else None
# List of specs that match expressions given via command line
specs_from_cli = []
has_errors = False
specs = spack.cmd.parse_specs(pkgs)
for spec in specs:
matching = spack.store.db.query(spec, hashes=hashes)
# For each spec provided, make sure it refers to only one package.
# Fail and ask user to be unambiguous if it doesn't
if not allow_multiple_matches and len(matching) > 1:
tty.error('%s matches multiple installed packages:' % spec)
for match in matching:
tty.msg('"%s"' % match.format())
has_errors = True
# No installed package matches the query
if len(matching) == 0 and spec is not any:
tty.error('{0} does not match any installed packages.'.format(
spec))
has_errors = True
specs_from_cli.extend(matching)
if has_errors:
tty.die('use one of the matching specs above')
return specs_from_cli
def match_downloaded_specs(pkgs, allow_multiple_matches=False, force=False):
"""Returns a list of specs matching the not necessarily
concretized specs given from cli
Args:
specs: list of specs to be matched against buildcaches on mirror
allow_multiple_matches : if True multiple matches are admitted
Return:
list of specs
"""
# List of specs that match expressions given via command line
specs_from_cli = []
has_errors = False
specs = bindist.get_specs(force)
for pkg in pkgs:
matches = []
tty.msg("buildcache spec(s) matching %s \n" % pkg)
for spec in sorted(specs):
if pkg.startswith('/'):
pkghash = pkg.replace('/', '')
if spec.dag_hash().startswith(pkghash):
matches.append(spec)
else:
if spec.satisfies(pkg):
matches.append(spec)
# For each pkg provided, make sure it refers to only one package.
# Fail and ask user to be unambiguous if it doesn't
if not allow_multiple_matches and len(matches) > 1:
tty.error('%s matches multiple downloaded packages:' % pkg)
for match in matches:
tty.msg('"%s"' % match.format())
has_errors = True
# No downloaded package matches the query
if len(matches) == 0:
tty.error('%s does not match any downloaded packages.' % pkg)
has_errors = True
specs_from_cli.extend(matches)
if has_errors:
tty.die('use one of the matching specs above')
return specs_from_cli
def createtarball(args):
"""create a binary package from an existing install"""
if not args.packages:
tty.die("build cache file creation requires at least one" +
" installed package argument")
pkgs = set(args.packages)
specs = set()
outdir = '.'
if args.directory:
outdir = args.directory
signkey = None
if args.key:
signkey = args.key
# restrict matching to current environment if one is active
env = ev.get_env(args, 'buildcache create')
matches = find_matching_specs(pkgs, False, False, env=env)
for match in matches:
if match.external or match.virtual:
tty.msg('skipping external or virtual spec %s' %
match.format())
else:
tty.msg('adding matching spec %s' % match.format())
specs.add(match)
tty.msg('recursing dependencies')
for d, node in match.traverse(order='post',
depth=True,
deptype=('link', 'run')):
if node.external or node.virtual:
tty.msg('skipping external or virtual dependency %s' %
node.format())
else:
tty.msg('adding dependency %s' % node.format())
specs.add(node)
tty.msg('writing tarballs to %s/build_cache' % outdir)
for spec in specs:
tty.msg('creating binary cache file for package %s ' % spec.format())
bindist.build_tarball(spec, outdir, args.force, args.rel,
args.unsigned, args.allow_root, signkey)
def installtarball(args):
"""install from a binary package"""
if not args.packages:
tty.die("build cache file installation requires" +
" at least one package spec argument")
pkgs = set(args.packages)
matches = match_downloaded_specs(pkgs, args.multiple, args.force)
for match in matches:
install_tarball(match, args)
def install_tarball(spec, args):
s = spack.spec.Spec(spec)
if s.external or s.virtual:
tty.warn("Skipping external or virtual package %s" % spec.format())
return
for d in s.dependencies(deptype=('link', 'run')):
tty.msg("Installing buildcache for dependency spec %s" % d)
install_tarball(d, args)
package = spack.repo.get(spec)
if s.concrete and package.installed and not args.force:
tty.warn("Package for spec %s already installed." % spec.format())
else:
tarball = bindist.download_tarball(spec)
if tarball:
tty.msg('Installing buildcache for spec %s' % spec.format())
bindist.extract_tarball(spec, tarball, args.allow_root,
args.unsigned, args.force)
spack.hooks.post_install(spec)
spack.store.store.reindex()
else:
tty.die('Download of binary cache file for spec %s failed.' %
spec.format())
def listspecs(args):
"""list binary packages available from mirrors"""
specs = bindist.get_specs(args.force)
if args.packages:
pkgs = set(args.packages)
for pkg in pkgs:
tty.msg("buildcache spec(s) matching " +
"%s and commands to install them" % pkgs)
for spec in sorted(specs):
if spec.satisfies(pkg):
tty.msg('Enter\nspack buildcache install /%s\n' %
spec.dag_hash(7) +
' to install "%s"' %
spec.format())
else:
tty.msg("buildcache specs and commands to install them")
for spec in sorted(specs):
tty.msg('Enter\nspack buildcache install /%s\n' %
spec.dag_hash(7) +
' to install "%s"' %
spec.format())
def getkeys(args):
"""get public keys available on mirrors"""
bindist.get_keys(args.install, args.trust, args.force)
def buildcache(parser, args):
if args.func:
args.func(args)
|
the-stack_0_8558 | # -*- coding: utf-8 -*-
"""QGIS Unit tests for QgsLogger.
.. note:: 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 2 of the License, or
(at your option) any later version.
"""
__author__ = 'Tim Sutton'
__date__ = '20/08/2012'
__copyright__ = 'Copyright 2012, The QGIS Project'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '176c06ceefb5f555205e72b20c962740cc0ec183'
import qgis # NOQA
import tempfile
import os
(myFileHandle, myFilename) = tempfile.mkstemp()
os.environ['QGIS_DEBUG'] = '2'
os.environ['QGIS_LOG_FILE'] = myFilename
from qgis.core import QgsLogger
from qgis.testing import unittest
# Convenience instances in case you may need them
# not used in this test
# from qgis.testing import start_app
# start_app()
class TestQgsLogger(unittest.TestCase):
def testLogger(self):
try:
myFile = os.fdopen(myFileHandle, "w")
myFile.write("QGIS Logger Unit Test\n")
myFile.close()
myLogger = QgsLogger()
myLogger.debug('This is a debug')
myLogger.warning('This is a warning')
myLogger.critical('This is critical')
# myLogger.fatal('Aaaargh...fatal'); #kills QGIS not testable
myFile = open(myFilename, 'rt')
myText = myFile.readlines()
myFile.close()
myExpectedText = ['QGIS Logger Unit Test\n',
'This is a debug\n',
'This is a warning\n',
'This is critical\n']
myMessage = ('Expected:\n---\n%s\n---\nGot:\n---\n%s\n---\n' %
(myExpectedText, myText))
self.assertEqual(myText, myExpectedText, myMessage)
finally:
pass
os.remove(myFilename)
if __name__ == '__main__':
unittest.main()
|
the-stack_0_8561 | # -*- coding: utf-8 -*-
"""
Created on Fri Sep 13 17:22:08 2019
@author: Chenghai Li
"""
import math
import time
import torch
import torch.nn as nn
import numpy as np
from torchdiffeq import odeint_adjoint as odeint
import matplotlib.pyplot as plt
from scipy import interpolate
device = torch.device('cuda:0')
file = open('3.txt','r')
x3 = []
y3 = []
for row in file.readlines():
row = row.split()
row[0] = float(row[0])
row[1] = float(row[1])
x3.append(row[0])
y3.append(row[1])
file.close()
E = interpolate.interp1d(x3, y3, kind="cubic")
file = open('pr.txt','r')
p = []
r = []
for row in file.readlines():
row = row.split()
row[0] = float(row[0])
row[1] = float(row[1])
p.append(row[0])
r.append(row[1])
file.close()
pr_pre = interpolate.interp1d(p, r, kind="cubic")
def pr(p):
if p>0.1001:
return pr_pre(p)
else:
return [0.8043390]
file = open('2_1.txt','r')
x2_1 = []
y2_1 = []
for row in file.readlines():
row = row.split()
row[0] = float(row[0])
row[1] = float(row[1])
x2_1.append(row[0])
y2_1.append(row[1])
file.close()
l2_1 = interpolate.interp1d(x2_1, y2_1, kind="cubic")
file = open('2_2.txt','r')
x2_2 = []
y2_2 = []
for row in file.readlines():
row = row.split()
row[0] = float(row[0])
row[1] = float(row[1])
x2_2.append(row[0])
y2_2.append(row[1])
file.close()
l2_2 = interpolate.interp1d(x2_2, y2_2, kind="cubic")
def l(x):
x = (x -12.5) % 100
if x < 0.45:
return torch.tensor(l2_1(x), dtype = torch.double)
if 0.45 <= x <= 2:
return torch.tensor([2], dtype = torch.double)
if 2 < x < 2.45:
return torch.tensor(l2_2(x), dtype = torch.double)
if 2.45 <= x <= 100:
return torch.tensor([0], dtype = torch.double)
A = 0.7*0.7*math.pi
v = 500*5*5*math.pi
omiga = math.pi/111
def v0(t):
return torch.tensor([-(-2.413 * math.sin( omiga * t + math.pi/2 ) + 4.826) * math.pi * 2.5 * 2.5 + 162.1374326208532], dtype = torch.double)
def v0t(t):
return torch.tensor([omiga * 2.413 * math.cos ( omiga * t + math.pi/2 ) * math.pi * 2.5 * 2.5], dtype = torch.double)
class func(nn.Module):
def forward(self, t, w):
p0, p1= w
tr = t % 100
if p0 >= p1 and v0t(t) < 0:
Q0 = 0.85 * A * math.sqrt(2 * ( p0 - p1 ) / torch.tensor(pr(p0), dtype = torch.double) )
else:
Q0 = torch.tensor([0], dtype = torch.double)
if p0 < 0.5 and v0t(t) > 0:
r0t = torch.tensor([0], dtype = torch.double)
p0t = torch.tensor([0], dtype = torch.double)
else:
r0t = (-Q0 * torch.tensor(pr(p0), dtype = torch.double) * v0(t) - v0(t) * torch.tensor(pr(p0), dtype = torch.double) * v0t(t)) / (v0(t) ** 2)
p0t = torch.tensor(E(p0), dtype = torch.double) / torch.tensor(pr(p0), dtype = torch.double) * r0t
A1 = math.pi * l(tr) * math.sin( math.pi / 20 ) * (4 * 1.25 + l(tr) * math.sin( math.pi / 20 ) * math.cos( math.pi / 20 ) )
A2 = math.pi * 0.7 * 0.7
Q1 = 0.85 * min(A1, A2) * math.sqrt(2 * p1 / torch.tensor(pr(p1), dtype = torch.double))
r1t = (Q0 * torch.tensor(pr(p0), dtype = torch.double) - Q1 * torch.tensor(pr(p1), dtype = torch.double)) / v
p1t = torch.tensor(E(p1), dtype = torch.double) / torch.tensor(pr(p1), dtype = torch.double) * r1t
return torch.tensor([p0t, p1t],dtype=torch.double)
time_range = 20
step_length = 0.01
time_start=time.time()
t = torch.tensor( np.arange(0, time_range, step_length), dtype=torch.double)
y0 = torch.tensor([0.5, 100], dtype=torch.double)
track1 = odeint(func(), y0, t, method='rk4')
time_end=time.time()
print('totally cost',time_end-time_start)
'''
show = []
for i in range(len(track1)):
show.append(track1[i][0])
plt.plot(show)
'''
|
the-stack_0_8562 | from django.urls import path
from .views import post_comment_create_and_list_view, like_unlike_post, PostDeleteView, PostUpdateView
app_name = 'posts'
urlpatterns = [
path('', post_comment_create_and_list_view, name='main-post-view'),
path('liked/', like_unlike_post, name='like-post-view'),
path('<pk>/delete/', PostDeleteView.as_view(), name='post-delete'),
path('<pk>/update/', PostUpdateView.as_view(), name='post-update'),
]
|
the-stack_0_8565 | #!/bin/env python
#===============================================================================
# NAME: SerialHVisitor.py
#
# DESCRIPTION: A visitor responsible for the generation of header file
# for each serializable class.
#
# AUTHOR: reder
# EMAIL: [email protected]
# DATE CREATED : June 4, 2007
#
# Copyright 2013, California Institute of Technology.
# ALL RIGHTS RESERVED. U.S. Government Sponsorship acknowledged.
#===============================================================================
#
# Python standard modules
#
import logging
import os
import sys
import time
import datetime
from optparse import OptionParser
#
# Python extention modules and custom interfaces
#
#from Cheetah import Template
#from fprime_ac.utils import version
from fprime_ac.utils import ConfigManager
#from fprime_ac.utils import DiffAndRename
from fprime_ac.generators.visitors import AbstractVisitor
from fprime_ac.generators import formatters
#
# Import precompiled templates here
#
from fprime_ac.generators.templates.serialize import startSerialH
from fprime_ac.generators.templates.serialize import includes1SerialH
from fprime_ac.generators.templates.serialize import includes2SerialH
from fprime_ac.generators.templates.serialize import namespaceSerialH
from fprime_ac.generators.templates.serialize import publicSerialH
from fprime_ac.generators.templates.serialize import protectedSerialH
from fprime_ac.generators.templates.serialize import privateSerialH
from fprime_ac.generators.templates.serialize import finishSerialH
#
# Universal globals used within module go here.
# (DO NOT USE MANY!)
#
# Global logger init. below.
PRINT = logging.getLogger('output')
DEBUG = logging.getLogger('debug')
typelist = ['U8','I8','U16','I16','U32','I32','U64','I64','F32','F64',"bool"]
#
# Module class or classes go here.
class SerialHVisitor(AbstractVisitor.AbstractVisitor):
"""
A visitor class responsible for generation of component header
classes in C++.
"""
__instance = None
__config = None
__fp = None
__form = None
__form_comment = None
def __init__(self):
"""
Constructor.
"""
self.__config = ConfigManager.ConfigManager.getInstance()
self.__form = formatters.Formatters()
self.__form_comment = formatters.CommentFormatters()
DEBUG.info("SerialHVisitor: Instanced.")
self.bodytext = ""
self.prototypetext = ""
def _get_args_string(self, obj):
"""
Return a string of (type, name) args, comma seperated
for use in templates that generate prototypes.
"""
arg_str = ""
for (name,mtype,size,format,comment) in obj.get_members():
typename = mtype
if type(mtype) == type(tuple()):
typename = mtype[0][1]
arg_str += "%s %s, "%(mtype[0][1],name)
elif mtype == "string":
arg_str += "const %s::%sString& %s, " % (obj.get_name(),name, name)
elif mtype not in typelist and size is None:
arg_str += "const %s& %s, " %(mtype,name)
elif size != None:
arg_str += "const %s* %s, " % (mtype, name)
arg_str += "NATIVE_INT_TYPE %sSize, " % (name)
else:
arg_str += "%s %s" % (mtype, name)
arg_str += ", "
arg_str = arg_str.strip(', ')
return arg_str
def _get_conv_mem_list(self, obj):
"""
Return a list of port argument tuples
"""
arg_list = list()
for (name,mtype,size,format,comment) in obj.get_members():
typeinfo = None
if type(mtype) == type(tuple()):
mtype = mtype[0][1]
typeinfo = "enum"
elif mtype == "string":
mtype = "%s::%sString" %(obj.get_name(),name)
typeinfo = "string"
elif mtype not in typelist:
typeinfo = "extern"
arg_list.append((name,mtype,size,format,comment,typeinfo))
return arg_list
def _get_enum_string_list(self, enum_list):
"""
"""
enum_tuple = enum_list[0]
enum_list = enum_list[1]
enum_str_list = []
for e in enum_list:
# No value, No comment
if (e[1] == None) and (e[2] == None):
s = "%s," % (e[0])
# No value, With comment
elif (e[1] == None) and (e[2] != None):
s = "%s, // %s" % (e[0],e[2])
# With value, No comment
elif (e[1] != None) and (e[2] == None):
s = "%s = %s," % (e[0],e[1])
# With value and comment
elif (e[1] != None) and (e[2] != None):
s = "%s = %s, // %s" % (e)
else:
pass
enum_str_list.append(s)
return (enum_tuple, enum_str_list)
def _writeTmpl(self, c, visit_str):
"""
Wrapper to write tmpl to files desc.
"""
DEBUG.debug('SerialHVisitor:%s' % visit_str)
DEBUG.debug('===================================')
DEBUG.debug(c)
self.__fp.writelines(c.__str__())
DEBUG.debug('===================================')
def initFilesVisit(self, obj):
"""
Defined to generate files for generated code products.
@parms obj: the instance of the concrete element to operation on.
"""
# Build filename here...
if self.__config.get("serialize","XMLDefaultFileName") == "True":
namespace = "".join(obj.get_namespace().split('::'))
filename = namespace + obj.get_name() + self.__config.get("serialize","SerializableH")
PRINT.info("Generating code filename: %s, using XML namespace and name attributes..." % filename)
else:
xml_file = obj.get_xml_filename()
x = xml_file.split(".")
s = self.__config.get("serialize","SerializableXML").split(".")
l = len(s[0])
#
if (x[0][-l:] == s[0]) & (x[1] == s[1]):
filename = x[0].split(s[0])[0] + self.__config.get("serialize","SerializableH")
PRINT.info("Generating code filename: %s, using default XML filename prefix..." % filename)
else:
msg = "XML file naming format not allowed (must be XXXSerializableAi.xml), Filename: %s" % xml_file
PRINT.info(msg)
sys.exit(-1)
# Open file for writting here...
DEBUG.info('Open file: %s' % filename)
self.__fp = open(filename,'w')
if self.__fp == None:
raise Exception("Could not open %s file.") % filename
DEBUG.info('Completed')
def startSourceFilesVisit(self, obj):
"""
Defined to generate starting static code within files.
"""
c = startSerialH.startSerialH()
c.name = obj.get_name()
if obj.get_namespace() == None:
c.namespace_list = None
else:
c.namespace_list = obj.get_namespace().split('::')
d = datetime.datetime.now()
c.date = d.strftime("%A, %d %B %Y")
c.user = os.environ['USER']
self._writeTmpl(c, "startSourceFilesVisit")
def includes1Visit(self, obj):
"""
Defined to generate includes within a file.
Usually used for the base classes but also for Serial types
@parms args: the instance of the concrete element to operation on.
"""
c = includes1SerialH.includes1SerialH()
self._writeTmpl(c, "includes1Visit")
def includes2Visit(self, obj):
"""
Defined to generate internal includes within a file.
Usually used for data type includes and system includes.
@parms args: the instance of the concrete element to operation on.
"""
c = includes2SerialH.includes2SerialH()
c.xml_includes_list = obj.get_xml_includes()
if False in [x[-6:] == 'Ai.xml' for x in c.xml_includes_list]:
PRINT.info("ERROR: Only Ai.xml files can be given within <import_serializable_type> tag!!!")
sys.exit(-1)
c.xml_includes_list = [x.replace('Ai.xml','Ac.hpp') for x in c.xml_includes_list]
c.c_includes_list = obj.get_c_includes()
if False in [x[-3:] == 'hpp' or x[-1:] == 'h' for x in c.c_includes_list]:
PRINT.info("ERROR: Only .hpp or .h files can be given within <include_header> tag!!!")
sys.exit(-1)
#
self._writeTmpl(c, "includes2Visit")
def namespaceVisit(self, obj):
"""
Defined to generate namespace code within a file.
Also any pre-condition code is generated.
@parms args: the instance of the concrete element to operation on.
"""
c = namespaceSerialH.namespaceSerialH()
if obj.get_namespace() == None:
c.namespace_list = None
else:
c.namespace_list = obj.get_namespace().split('::')
c.enum_type_list = []
t = [x[1] for x in obj.get_members()]
enum_list = [x for x in t if type(x) == type(tuple())]
for e in enum_list:
c.enum_type_list.append(self._get_enum_string_list(e))
c.mem_list = obj.get_members()
c.name = obj.get_name()
self._writeTmpl(c, "namespaceVisit")
def publicVisit(self, obj):
"""
Defined to generate public stuff within a class.
@parms args: the instance of the concrete element to operation on.
"""
c = publicSerialH.publicSerialH()
c.name = obj.get_name()
c.args_proto = self._get_args_string(obj)
c.members = self._get_conv_mem_list(obj)
self._writeTmpl(c, "publicVisit")
def protectedVisit(self, obj):
"""
Defined to generate protected stuff within a class.
@parms args: the instance of the concrete element to operation on.
"""
c = protectedSerialH.protectedSerialH()
c.uuid = obj.get_typeid()
c.name = obj.get_name()
c.members = self._get_conv_mem_list(obj)
self._writeTmpl(c, "protectedVisit")
def privateVisit(self, obj):
"""
Defined to generate private stuff within a class.
@parms args: the instance of the concrete element to operation on.
"""
c = privateSerialH.privateSerialH()
self._writeTmpl(c, "privateVisit")
def finishSourceFilesVisit(self, obj):
"""
Defined to generate ending static code within files.
"""
c = finishSerialH.finishSerialH()
c.name = obj.get_name()
if obj.get_namespace() == None:
c.namespace_list = None
else:
c.namespace_list = obj.get_namespace().split('::')
self._writeTmpl(c, "finishSourceFilesVisit")
self.__fp.close()
if __name__ == '__main__':
pass
|
the-stack_0_8567 | import PyPDF2
# This code will add the watermark file on each of the files from super_pdf
template = PyPDF2.PdfFileReader(open('super_pdf', 'rb'))
watermark = PyPDF2.PdfFileReader(open('wtr.pdf', 'rb'))
output = PyPDF2.PdfFileWriter()
for i in range(template.getNumPages()):
page = template.getPage(i)
page.mergePage(watermark.getPage(0))
output.addPage(page)
with open('watermarked_output.pdf', 'wb') as file:
output.write(file) |
the-stack_0_8569 | import os
import subprocess
from platform import system
from time import sleep
try:
from psutil import NoSuchProcess, Process
except ImportError:
""" Don't make psutil a strict requirement, but use if available. """
Process = None
def kill_pid(pid, use_psutil=True):
if use_psutil and Process:
_psutil_kill_pid(pid)
else:
_stock_kill_pid(pid)
def _psutil_kill_pid(pid):
"""
http://stackoverflow.com/questions/1230669/subprocess-deleting-child-processes-in-windows
"""
try:
parent = Process(pid)
for child in parent.get_children(recursive=True):
child.kill()
parent.kill()
except NoSuchProcess:
return
def _stock_kill_pid(pid):
is_windows = system() == 'Windows'
if is_windows:
__kill_windows(pid)
else:
__kill_posix(pid)
def __kill_windows(pid):
try:
subprocess.check_call(['taskkill', '/F', '/T', '/PID', pid])
except subprocess.CalledProcessError:
pass
def __kill_posix(pid):
def __check_pid():
try:
os.kill(pid, 0)
return True
except OSError:
return False
if __check_pid():
for sig in [15, 9]:
try:
os.killpg(pid, sig)
except OSError:
return
sleep(1)
if not __check_pid():
return
|
the-stack_0_8572 | # Demonstrates the IPTC Media Topics document classification capability of the (Cloud based) expert.ai Natural Language API
from expertai.nlapi.cloud.client import ExpertAiClient
client = ExpertAiClient()
text = "Michael Jordan was one of the best basketball players of all time. Scoring was Jordan's stand-out skill, but he still holds a defensive NBA record, with eight steals in a half."
taxonomy = 'behavioral-traits'
language= 'en'
output = client.classification(body={"document": {"text": text}}, params={'taxonomy': taxonomy, 'language': language})
print("Tab separated list of categories:")
for category in output.categories:
print(category.id_, category.hierarchy, sep="\t")
|
the-stack_0_8573 | import logging
import sys
# Make sure a NullHandler is available
# This was added in Python 2.7/3.2
try:
from logging import NullHandler
except ImportError:
class NullHandler(logging.Handler):
def emit(self, record):
pass
# Make sure that dictConfig is available
# This was added in Python 2.7/3.2
try:
from logging.config import dictConfig
except ImportError:
from snaptastic.utils.dictconfig import dictConfig
if sys.version_info < (2, 5):
class LoggerCompat(object):
def __init__(self, logger):
self._logger = logger
def __getattr__(self, name):
val = getattr(self._logger, name)
if callable(val):
def _wrapper(*args, **kwargs):
# Python 2.4 logging module doesn't support 'extra' parameter to
# methods of Logger
kwargs.pop('extra', None)
return val(*args, **kwargs)
return _wrapper
else:
return val
def getLogger(name=None):
return LoggerCompat(logging.getLogger(name=name))
else:
getLogger = logging.getLogger
# Ensure the creation of the Django logger
# with a null handler. This ensures we don't get any
# 'No handlers could be found for logger "django"' messages
logger = getLogger('django')
if not logger.handlers:
logger.addHandler(NullHandler())
|
the-stack_0_8575 | # -*- coding: utf-8 -*-
#
# records.py
# csvdiff
#
import six
import csv
from . import error
class InvalidKeyError(Exception):
pass
def load(file_or_stream, sep=','):
istream = (open(file_or_stream)
if not hasattr(file_or_stream, 'read')
else file_or_stream)
# unicode delimiters are not ok in Python 2
if six.PY2 and isinstance(sep, six.text_type):
sep = sep.encode('utf8')
return SafeDictReader(istream, sep=sep)
class SafeDictReader:
"""
A CSV reader that streams records but gives nice errors if lines fail to parse.
"""
def __init__(self, istream, sep=None):
self.reader = csv.DictReader(istream, delimiter=sep)
def __iter__(self):
for lineno, r in enumerate(self.reader, 2):
if any(k is None for k in r):
error.abort('CSV parse error on line {}'.format(lineno))
yield r
@property
def fieldnames(self):
return self.reader._fieldnames
def index(record_seq, index_columns):
try:
obj = {
tuple(r[i] for i in index_columns): r
for r in record_seq
}
return obj
except KeyError as k:
raise InvalidKeyError('invalid column name {k} as key'.format(k=k))
def filter_ignored(sequence, ignore_columns):
for key in sequence:
for i in ignore_columns:
sequence[key].pop(i)
return sequence
def save(record_seq, fieldnames, ostream):
writer = csv.DictWriter(ostream, fieldnames)
writer.writeheader()
for r in record_seq:
writer.writerow(r)
def sort(recs):
return sorted(recs, key=_record_key)
def _record_key(r):
return sorted(r.items())
|
the-stack_0_8576 | #!/usr/bin/env python
from __future__ import print_function
import gripql
import argparse
import pandas
import math
def load_matrix(args):
conn = gripql.Connection(args.server)
O = conn.graph(args.db)
matrix = pandas.read_csv(args.input, sep="\t", index_col=0)
for name, row in matrix.iterrows():
data = {}
for k, v in row.iteritems():
if not isinstance(v, float) or not math.isnan(v):
data[k] = v
O.addVertex(name, "Sample", data)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("input")
parser.add_argument("--server", default="http://localhost:8201")
parser.add_argument("--db", required=True)
args = parser.parse_args()
load_matrix(args)
|
the-stack_0_8577 | # This is a dict where each entry contains an label for a morphological feature,
# or the label for the UPOS tag if the key is 'upos'
pos_properties = {'ADJ': ['Degree', 'Number', 'Gender', 'Case'],
'ADP': ['Number', 'Gender', 'Case'],
'ADV': ['Degree', 'Abbr'],
'AUX': ['Mood',
'Aspect',
'Tense',
'Number',
'Person',
'VerbForm',
'Voice'],
'CCONJ': [],
'DET': ['Number', 'Gender', 'PronType', 'Definite', 'Case'],
'NOUN': ['Number', 'Gender', 'Abbr', 'Case'],
'NUM': ['NumType', 'Number', 'Gender', 'Case'],
'PART': [],
'PRON': ['Number', 'Gender', 'Person', 'Poss', 'PronType', 'Case'],
'PROPN': ['Number', 'Gender', 'Case'],
'PUNCT': [],
'SCONJ': [],
'SYM': [],
'VERB': ['Mood',
'Aspect',
'Tense',
'Number',
'Gender',
'Person',
'VerbForm',
'Voice',
'Case'],
'X': ['Foreign'],
'_': []}
# The labels for the named entity output of the ner model.
# A string label can be obtained by an output index
pos_labels = {'Abbr': ['_', 'Yes'],
'Aspect': ['Perf', '_', 'Imp'],
'Case': ['Dat', '_', 'Acc', 'Gen', 'Nom', 'Voc'],
'Definite': ['Ind', 'Def', '_'],
'Degree': ['Cmp', 'Sup', '_'],
'Foreign': ['_', 'Yes'],
'Gender': ['Fem', 'Masc', '_', 'Neut'],
'Mood': ['Ind', '_', 'Imp'],
'NumType': ['Mult', 'Card', '_', 'Ord', 'Sets'],
'Number': ['Plur', '_', 'Sing'],
'Person': ['3', '1', '_', '2'],
'Poss': ['_', 'Yes'],
'PronType': ['Ind', 'Art', '_', 'Rel', 'Dem', 'Prs', 'Ind,Rel', 'Int'],
'Tense': ['Pres', 'Past', '_'],
'VerbForm': ['Part', 'Conv', '_', 'Inf', 'Fin'],
'Voice': ['Pass', 'Act', '_'],
'upos': ['X',
'PROPN',
'PRON',
'ADJ',
'AUX',
'PART',
'ADV',
'_',
'DET',
'SYM',
'NUM',
'CCONJ',
'PUNCT',
'NOUN',
'SCONJ',
'ADP',
'VERB']}
|
the-stack_0_8580 | """AI."""
from mgz import Version
from mgz.util import Find
from construct import (Array, Byte, If, Int16ul, Int32sl, Int32ul, Padding,
PascalString, Struct, this, IfThenElse)
# pylint: disable=invalid-name
script = "script"/Struct(
Padding(4),
"seq"/Int32sl,
"max_rules"/Int16ul,
"num_rules"/Int16ul,
Padding(4),
Array(this.num_rules, "rules"/Struct(
Padding(12),
"num_facts"/Byte,
"num_facts_actions"/Byte,
Padding(2),
Array(16, "data"/Struct(
"type"/Int32ul,
"id"/Int16ul,
Padding(2),
Array(4, "params"/Int32ul)
))
))
)
ai = "ai"/Struct(
"has_ai"/Int32ul, # if true, parse AI
"yep"/If(
this.has_ai == 1,
IfThenElse(
lambda ctx: ctx._.version == Version.DE,
Find(b'\00' * 4096, None), # The ai structure in DE seems to have changed, for now we simply skip it
"ais"/Struct(
"max_strings"/Int16ul,
"num_strings"/Int16ul,
Padding(4),
Array(this.num_strings, "strings"/PascalString(lengthfield="name_length"/Int32ul,
encoding='latin1')),
Padding(6),
Array(8, script),
Padding(104),
Array(80, "timers"/Int32sl),
Array(256, "shared_goals"/Int32sl),
Padding(4096),
)
)
)
)
|
the-stack_0_8581 | # Copyright (c) 2020 Graphcore Ltd. All rights reserved.
from contextlib import contextmanager
import copy
import fcntl
import hashlib
import os
from typing import Dict, Any
import torch
# Do not import any poptorch.* here: it will break the poptorch module
from ._logging import logger
from . import poptorch_core
# A flag to tell the user if the current target is IPU. This is to allow
# divergent IPU/CPU codepaths within one model.
_is_ipu_context = False
def createPoptorchError(msg):
type = "poptorch_py_error"
error = poptorch_core.Error(f"'{type}': {msg}")
error.type = type
error.message = msg
error.location = ""
return error
def isRunningOnIpu() -> bool:
""" This function returns `True` when executing on IPU and `False` when
executing the model outside IPU scope. This allows for separate
codepaths to be marked in the model simply by using:
>>> if poptorch.isRunningOnIpu():
>>> # IPU path
>>> else:
>>> # CPU path
Note this will only apply to code during execution. During model
creation it will always return `False`.
:returns: True if running on IPU, otherwise False.
"""
global _is_ipu_context
return _is_ipu_context
def setIpuContext(val: bool):
global _is_ipu_context
_is_ipu_context = val
def internal_cast(tensor, dtype):
if dtype in [torch.float, torch.float32]:
return torch.ops.poptorch.internal_cast(tensor, "FLOAT")
if dtype in [torch.half, torch.float16]:
return torch.ops.poptorch.internal_cast(tensor, "FLOAT16")
raise ValueError(
'Invalid poptorch.cast target type. Expecting torch.float or torch.half'
)
def applyOptimizer(optimizer):
num_groups = len(optimizer.param_groups)
for index in range(0, num_groups):
torch.ops.poptorch.optimizer_group(
index, optimizer.param_groups[index]["params"])
# To understand which variable groups the user wants to apply the
# optimizer to we need to mark them via a wrapper. We do this because
# when we reference the variables in the context of the operation we
# get the corresponding IR value for "free" as part of the trace.
# Otherwise we would need a system to map the variable in the optimizer
# to the variable in the model to the variable in the IR.
class OptimizerWrapper(torch.nn.Module):
def __init__(self, model, optimizer):
super().__init__()
self.model = model
self.optimizer = optimizer
def forward(self, *args, **kwargs):
out = self.model(*args, **kwargs)
applyOptimizer(self.optimizer)
return out
@contextmanager
def distributedCacheLock(model, opts):
"""In a distributed environment we only want the model to be compiled once.
If there is only one process or if the cache is not enabled:
no need for a lock, early return.
Otherwise:
The first process to reach the lock takes it and compiles the model.
The model will be added to the PopART cache.
After the first process releases the lock the other ones will grab it
one at the time and compile the model too (Except that they will
now all hit the cache).
The last process to grab / release the lock will delete the file.
(Each process append a character to the file, so the position in
the file when acquiring the lock indicates how many processes have
already successfully compiled the model).
"""
filename = None
if opts.Distributed.numProcesses > 1:
cache = opts._popart.options.get("cachePath", "") # pylint: disable=protected-access
if not cache:
logger.warning(
"Use poptorch.Options.enableExecutableCaching() to avoid "
"compiling the model once per process")
else:
os.makedirs(cache, exist_ok=True)
assert os.access(cache, os.W_OK), (f"Cache folder {cache}"
" is not writable")
filename = os.path.join(
cache, "%s.lock" %
hashlib.md5(repr(model).encode("utf-8")).hexdigest())
# Not distributed mode or the cache is not enabled: do nothing.
if not filename:
yield False
return
delete_file = False
try:
with open(filename, "a+") as f:
try:
fcntl.flock(f, fcntl.LOCK_EX)
# Add a character to the file
f.write("0")
logger.debug(
"Executable cache file locked by process %s (pos %d/%d)",
opts.Distributed.processId, f.tell(),
opts.Distributed.numProcesses)
delete_file = f.tell() == opts.Distributed.numProcesses
# Only the first process should compile
yield f.tell() == 1
finally:
logger.debug("Process %s released the cache lock",
opts.Distributed.processId)
fcntl.flock(f, fcntl.LOCK_UN)
finally:
if delete_file:
os.remove(filename)
# The pickle handlers are called in two cases: when an object is copied
# (i.e copy.copy(obj)) or when an object is pickled / serialised.
# In both cases the object is first dumped using pickleUnwrapModel and then
# in the copy case _pickleRestoreWrapperIfPossible() is called immediately after
# to create the new object.
#
# The _wrapper_registry keeps track of the mapping between user model, parameter,
# buffer types and their corresponding wrapper.
# When an object is copied we want to preserve the Wrapper type: the PopTorch
# wrapper doesn't contain any attribute so it's just a question of updating
# the __class__attribute.
#
# When an object is loaded from file: the wrapper type doesn't exist anymore
# therefore we keep the object unwrapped. (It will be wrapped again when passed
# to poptorch.trainingModel anyway)
_wrapper_registry: Dict[int, Any] = {}
def _pickleRestoreWrapperIfPossible(obj):
wrapperType = _wrapper_registry.get(id(obj))
if wrapperType:
obj.__class__ = wrapperType
return obj
def pickleUnwrapObject(obj):
global _wrapper_registry
wrapperType = obj.__class__
obj.__class__ = obj.__class__.__bases__[0]
other = copy.copy(obj)
_wrapper_registry[id(other)] = wrapperType
obj.__class__ = wrapperType
return _pickleRestoreWrapperIfPossible, (other, )
|
the-stack_0_8582 | #excersise when we create 2 inherited classes from main Turtle. Each has defined function to turn in predefined direction.
#after we create 20 turtles and list them
#we check the turtles in list and assign pen colors
#let all turtles draw square, each with assigned color and turning in predefined direction
from turtle import Turtle
from random import randrange as rr
class Turtle1(Turtle): #creating inherited class from Turtle and defining function to turn it in predefined direction.
def otoc(self, uhol):
self.lt(uhol)
class Turtle2(Turtle): #creating inherited class from Turtle and defining function to turn it in predefined direction
def otoc(self, uhol):
self.rt(uhol)
zoz = [] #list of created turtles
for i in range(20): #creating 20 turtles, if o=0 Turtle1 is created, if o=1 Turtle2 is created
o = rr(0, 2)
if o == 0:
t1 = Turtle1()
t1.seth(0)
t1.pu()
t1.setpos(-200 + i * 20, 0)
t1.pd()
zoz.append(t1) #adding turtle into list
else:
t2 = Turtle2()
t2.seth(0)
t2.pu()
t2.setpos(-200 + i * 20, 0)
t2.pd()
zoz.append(t2) #adding turtle into list
for t in zoz: #checking the list of turtles one by one. Changing pen color based on turtle instance
if isinstance(t, Turtle1):
t.pencolor('red')
elif isinstance(t, Turtle2):
t.pencolor('blue')
for i in range(4): #moving turtles one after another to draw square
for t in zoz:
t.fd(20)
t.otoc(90)
|
the-stack_0_8583 | # Copyright 2019 Xanadu Quantum Technologies Inc.
# 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 writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Circuit class specification for the general Gaussian Boson Sampling class of circuits."""
from strawberryfields.program_utils import CircuitError, Command, group_operations
import strawberryfields.ops as ops
from .gaussian import GaussianSpecs
class GBSSpecs(GaussianSpecs):
"""Circuit specifications for the general GBS class of circuits."""
short_name = 'gbs'
primitives = {
# meta operations
"All",
"_New_modes",
"_Delete",
# state preparations
"Vacuum",
"Coherent",
"Squeezed",
"DisplacedSqueezed",
"Thermal",
"Gaussian",
# measurements
"MeasureHomodyne",
"MeasureHeterodyne",
"MeasureFock",
"MeasureThreshold",
# channels
"LossChannel",
"ThermalLossChannel",
# single mode gates
"Dgate",
"Xgate",
"Zgate",
"Sgate",
"Rgate",
"Fouriergate",
"BSgate"
}
def compile(self, seq, registers):
"""Try to arrange a quantum circuit into a form suitable for Gaussian boson sampling.
This method checks whether the circuit can be implemented as a Gaussian boson sampling
problem, i.e., if it is equivalent to a circuit A+B, where the sequence A only contains
Gaussian operations, and B only contains Fock measurements.
If the answer is yes, the circuit is arranged into the A+B order, and all the Fock
measurements are combined into a single :class:`MeasureFock` operation.
Args:
seq (Sequence[Command]): quantum circuit to modify
registers (Sequence[RegRefs]): quantum registers
Returns:
List[Command]: modified circuit
Raises:
CircuitError: the circuit does not correspond to GBS
"""
A, B, C = group_operations(seq, lambda x: isinstance(x, ops.MeasureFock))
# C should be empty
if C:
raise CircuitError('Operations following the Fock measurements.')
# A should only contain Gaussian operations
# (but this is already guaranteed by group_operations() and our primitive set)
# without Fock measurements GBS is pointless
if not B:
raise CircuitError('GBS circuits must contain Fock measurements.')
# there should be only Fock measurements in B
measured = set()
for cmd in B:
if not isinstance(cmd.op, ops.MeasureFock):
raise CircuitError('The Fock measurements are not consecutive.')
# combine the Fock measurements
temp = set(cmd.reg)
if measured & temp:
raise CircuitError('Measuring the same mode more than once.')
measured |= temp
# replace B with a single Fock measurement
B = [Command(ops.MeasureFock(), sorted(list(measured), key=lambda x: x.ind))]
return super().compile(A + B, registers)
|
the-stack_0_8584 | #In 1
from __future__ import print_function
from __future__ import division
import pandas as pd
import numpy as np
# from matplotlib import pyplot as plt
# import seaborn as sns
# from sklearn.model_selection import train_test_split
import statsmodels.api as sm
# just for the sake of this blog post!
from warnings import filterwarnings
filterwarnings('ignore')
#In 2
# load the provided data
train_features = pd.read_csv('data/dengue_features_train.csv',
index_col=[0,1,2])
train_labels = pd.read_csv('data/dengue_labels_train.csv',
index_col=[0,1,2])
# Separate data for Iquitos
iq_train_features = train_features.loc['iq']
iq_train_labels = train_labels.loc['iq']
iq_train_features.drop('week_start_date', axis=1, inplace=True)
#In 7
# Null check
iq_train_features.fillna(method='ffill', inplace=True)
#In 13
iq_train_features['total_cases'] = iq_train_labels.total_cases
#In 14
# compute the correlations
iq_correlations = iq_train_features.corr()
#In 19
def preprocess_data(data_path, labels_path=None):
# load data and set index to city, year, weekofyear
df = pd.read_csv(data_path, index_col=[0, 1, 2])
# select features we want
features = ['reanalysis_specific_humidity_g_per_kg',
'reanalysis_dew_point_temp_k',
'reanalysis_min_air_temp_k']
df = df[features]
# fill missing values
df.fillna(method='ffill', inplace=True)
# add labels to dataframe
if labels_path:
labels = pd.read_csv(labels_path, index_col=[0, 1, 2])
df = df.join(labels)
# separate san juan and iquitos
iq = df.loc['iq']
return iq
#In 20
iq_train = preprocess_data('data/dengue_features_train.csv',
labels_path="data/dengue_labels_train.csv")
iq_train_subtrain = iq_train
#iq_train_subtrain = iq_train.head(400)
iq_train_subtest = iq_train.tail(iq_train.shape[0] - 400)
#In 24
from statsmodels.tools import eval_measures
import statsmodels.formula.api as smf
def get_best_model(train, test):
# Step 1: specify the form of the model
model_formula = "total_cases ~ 1 + " \
"reanalysis_specific_humidity_g_per_kg + " \
"reanalysis_dew_point_temp_k + " \
"reanalysis_min_air_temp_k"
grid = 10 ** np.arange(-8, -3, dtype=np.float64)
best_alpha = []
best_score = 1000
# Step 2: Find the best hyper parameter, alpha
for alpha in grid:
model = smf.glm(formula=model_formula,
data=train,
family=sm.families.NegativeBinomial(alpha=alpha))
results = model.fit()
predictions = results.predict(test).astype(int)
score = eval_measures.meanabs(predictions, test.total_cases)
if score < best_score:
best_alpha = alpha
best_score = score
# Step 3: refit on entire dataset
full_dataset = pd.concat([train, test])
model = smf.glm(formula=model_formula,
data=full_dataset,
family=sm.families.NegativeBinomial(alpha=best_alpha))
fitted_model = model.fit()
return fitted_model
iq_best_model = get_best_model(iq_train_subtrain, iq_train_subtest)
iq_test = preprocess_data('data/dengue_features_test.csv')
iq_predictions = iq_best_model.predict(iq_test).astype(int)
submission = pd.read_csv("data/submission_format.csv",
index_col=[0, 1, 2])
submission.total_cases = np.concatenate([iq_predictions])
submission.to_csv("data/benchmark.csv")
|
the-stack_0_8585 | """Xbox Media Source Implementation."""
from __future__ import annotations
from dataclasses import dataclass
from pydantic.error_wrappers import ValidationError # pylint: disable=no-name-in-module
from xbox.webapi.api.client import XboxLiveClient
from xbox.webapi.api.provider.catalog.models import FieldsTemplate, Image
from xbox.webapi.api.provider.gameclips.models import GameclipsResponse
from xbox.webapi.api.provider.screenshots.models import ScreenshotResponse
from xbox.webapi.api.provider.smartglass.models import InstalledPackage
from homeassistant.components.media_player.const import (
MEDIA_CLASS_DIRECTORY,
MEDIA_CLASS_GAME,
MEDIA_CLASS_IMAGE,
MEDIA_CLASS_VIDEO,
)
from homeassistant.components.media_source.const import MEDIA_MIME_TYPES
from homeassistant.components.media_source.models import (
BrowseMediaSource,
MediaSource,
MediaSourceItem,
PlayMedia,
)
from homeassistant.core import callback
from homeassistant.helpers.typing import HomeAssistantType
from homeassistant.util import dt as dt_util
from .browse_media import _find_media_image
from .const import DOMAIN
MIME_TYPE_MAP = {
"gameclips": "video/mp4",
"screenshots": "image/png",
}
MEDIA_CLASS_MAP = {
"gameclips": MEDIA_CLASS_VIDEO,
"screenshots": MEDIA_CLASS_IMAGE,
}
async def async_get_media_source(hass: HomeAssistantType):
"""Set up Xbox media source."""
entry = hass.config_entries.async_entries(DOMAIN)[0]
client = hass.data[DOMAIN][entry.entry_id]["client"]
return XboxSource(hass, client)
@callback
def async_parse_identifier(
item: MediaSourceItem,
) -> tuple[str, str, str]:
"""Parse identifier."""
identifier = item.identifier or ""
start = ["", "", ""]
items = identifier.lstrip("/").split("~~", 2)
return tuple(items + start[len(items) :])
@dataclass
class XboxMediaItem:
"""Represents gameclip/screenshot media."""
caption: str
thumbnail: str
uri: str
media_class: str
class XboxSource(MediaSource):
"""Provide Xbox screenshots and gameclips as media sources."""
name: str = "Xbox Game Media"
def __init__(self, hass: HomeAssistantType, client: XboxLiveClient):
"""Initialize Xbox source."""
super().__init__(DOMAIN)
self.hass: HomeAssistantType = hass
self.client: XboxLiveClient = client
async def async_resolve_media(self, item: MediaSourceItem) -> PlayMedia:
"""Resolve media to a url."""
_, category, url = async_parse_identifier(item)
kind = category.split("#", 1)[1]
return PlayMedia(url, MIME_TYPE_MAP[kind])
async def async_browse_media(
self, item: MediaSourceItem, media_types: tuple[str] = MEDIA_MIME_TYPES
) -> BrowseMediaSource:
"""Return media."""
title, category, _ = async_parse_identifier(item)
if not title:
return await self._build_game_library()
if not category:
return _build_categories(title)
return await self._build_media_items(title, category)
async def _build_game_library(self):
"""Display installed games across all consoles."""
apps = await self.client.smartglass.get_installed_apps()
games = {
game.one_store_product_id: game
for game in apps.result
if game.is_game and game.title_id
}
app_details = await self.client.catalog.get_products(
games.keys(),
FieldsTemplate.BROWSE,
)
images = {
prod.product_id: prod.localized_properties[0].images
for prod in app_details.products
}
return BrowseMediaSource(
domain=DOMAIN,
identifier="",
media_class=MEDIA_CLASS_DIRECTORY,
media_content_type="",
title="Xbox Game Media",
can_play=False,
can_expand=True,
children=[_build_game_item(game, images) for game in games.values()],
children_media_class=MEDIA_CLASS_GAME,
)
async def _build_media_items(self, title, category):
"""Fetch requested gameclip/screenshot media."""
title_id, _, thumbnail = title.split("#", 2)
owner, kind = category.split("#", 1)
items: list[XboxMediaItem] = []
try:
if kind == "gameclips":
if owner == "my":
response: GameclipsResponse = (
await self.client.gameclips.get_recent_clips_by_xuid(
self.client.xuid, title_id
)
)
elif owner == "community":
response: GameclipsResponse = await self.client.gameclips.get_recent_community_clips_by_title_id(
title_id
)
else:
return None
items = [
XboxMediaItem(
item.user_caption
or dt_util.as_local(
dt_util.parse_datetime(item.date_recorded)
).strftime("%b. %d, %Y %I:%M %p"),
item.thumbnails[0].uri,
item.game_clip_uris[0].uri,
MEDIA_CLASS_VIDEO,
)
for item in response.game_clips
]
elif kind == "screenshots":
if owner == "my":
response: ScreenshotResponse = (
await self.client.screenshots.get_recent_screenshots_by_xuid(
self.client.xuid, title_id
)
)
elif owner == "community":
response: ScreenshotResponse = await self.client.screenshots.get_recent_community_screenshots_by_title_id(
title_id
)
else:
return None
items = [
XboxMediaItem(
item.user_caption
or dt_util.as_local(item.date_taken).strftime(
"%b. %d, %Y %I:%M%p"
),
item.thumbnails[0].uri,
item.screenshot_uris[0].uri,
MEDIA_CLASS_IMAGE,
)
for item in response.screenshots
]
except ValidationError:
# Unexpected API response
pass
return BrowseMediaSource(
domain=DOMAIN,
identifier=f"{title}~~{category}",
media_class=MEDIA_CLASS_DIRECTORY,
media_content_type="",
title=f"{owner.title()} {kind.title()}",
can_play=False,
can_expand=True,
children=[_build_media_item(title, category, item) for item in items],
children_media_class=MEDIA_CLASS_MAP[kind],
thumbnail=thumbnail,
)
def _build_game_item(item: InstalledPackage, images: list[Image]):
"""Build individual game."""
thumbnail = ""
image = _find_media_image(images.get(item.one_store_product_id, []))
if image is not None:
thumbnail = image.uri
if thumbnail[0] == "/":
thumbnail = f"https:{thumbnail}"
return BrowseMediaSource(
domain=DOMAIN,
identifier=f"{item.title_id}#{item.name}#{thumbnail}",
media_class=MEDIA_CLASS_GAME,
media_content_type="",
title=item.name,
can_play=False,
can_expand=True,
children_media_class=MEDIA_CLASS_DIRECTORY,
thumbnail=thumbnail,
)
def _build_categories(title):
"""Build base categories for Xbox media."""
_, name, thumbnail = title.split("#", 2)
base = BrowseMediaSource(
domain=DOMAIN,
identifier=f"{title}",
media_class=MEDIA_CLASS_GAME,
media_content_type="",
title=name,
can_play=False,
can_expand=True,
children=[],
children_media_class=MEDIA_CLASS_DIRECTORY,
thumbnail=thumbnail,
)
owners = ["my", "community"]
kinds = ["gameclips", "screenshots"]
for owner in owners:
for kind in kinds:
base.children.append(
BrowseMediaSource(
domain=DOMAIN,
identifier=f"{title}~~{owner}#{kind}",
media_class=MEDIA_CLASS_DIRECTORY,
media_content_type="",
title=f"{owner.title()} {kind.title()}",
can_play=False,
can_expand=True,
children_media_class=MEDIA_CLASS_MAP[kind],
)
)
return base
def _build_media_item(title: str, category: str, item: XboxMediaItem):
"""Build individual media item."""
kind = category.split("#", 1)[1]
return BrowseMediaSource(
domain=DOMAIN,
identifier=f"{title}~~{category}~~{item.uri}",
media_class=item.media_class,
media_content_type=MIME_TYPE_MAP[kind],
title=item.caption,
can_play=True,
can_expand=False,
thumbnail=item.thumbnail,
)
|
the-stack_0_8587 | #Reads files
#input = open('words.txt','r')
input = open('http://woz.cs.missouriwestern.edu/data/docs/moby.txt')
for line in input:
line = line.strip()
print("The line is",line)
input.close()
print("Done") |
the-stack_0_8588 | from commands import tankdrive
import ctre
from wpilib import SmartDashboard as Dash
from wpilib.command import Subsystem
from constants import Constants
from utils import singleton, units, lazytalonsrx
import math
class Drive(Subsystem, metaclass=singleton.Singleton):
"""The Drive subsystem controls the drive motors
and encoders."""
def __init__(self):
super().__init__()
def init(self):
"""Initialize the drive motors. This is not in the constructor to make the calling explicit in the robotInit to the robot simulator."""
self.bl_motor = lazytalonsrx.LazyTalonSRX(Constants.BL_MOTOR_ID)
self.br_motor = lazytalonsrx.LazyTalonSRX(Constants.BR_MOTOR_ID)
self.fl_motor = lazytalonsrx.LazyTalonSRX(Constants.FL_MOTOR_ID)
self.fr_motor = lazytalonsrx.LazyTalonSRX(Constants.FR_MOTOR_ID)
self.motors = [self.bl_motor, self.br_motor,
self.fl_motor, self.fr_motor]
self.bl_motor.initialize(
inverted=False, encoder=True, phase=True, name="Drive Back Left")
self.br_motor.initialize(
inverted=True, encoder=True, phase=True, name="Drive Back Right")
self.fl_motor.initialize(
inverted=False, encoder=True, phase=True, name="Drive Front Left")
self.fr_motor.initialize(
inverted=True, encoder=True, phase=True, name="Drive Front Right")
self.initPIDF()
def initPIDF(self):
"""Initialize the drive motor pidf gains."""
self.bl_motor.setPIDF(0, Constants.BL_VELOCITY_KP, Constants.BL_VELOCITY_KI,
Constants.BL_VELOCITY_KD, Constants.BL_VELOCITY_KF)
self.br_motor.setPIDF(0, Constants.BR_VELOCITY_KP, Constants.BR_VELOCITY_KI,
Constants.BR_VELOCITY_KD, Constants.BR_VELOCITY_KF)
self.fl_motor.setPIDF(0, Constants.FL_VELOCITY_KP, Constants.FL_VELOCITY_KI,
Constants.FL_VELOCITY_KD, Constants.FL_VELOCITY_KF)
self.fr_motor.setPIDF(0, Constants.FR_VELOCITY_KP, Constants.FR_VELOCITY_KI,
Constants.FR_VELOCITY_KD, Constants.FR_VELOCITY_KF)
def zeroSensors(self):
"""Set the encoder positions to 0."""
for motor in self.motors:
motor.zero()
def outputToDashboard(self):
self.bl_motor.outputToDashboard()
self.br_motor.outputToDashboard()
self.fl_motor.outputToDashboard()
self.fr_motor.outputToDashboard()
def setPercentOutput(self, bl_signal, br_signal, fl_signal, fr_signal):
"""Set the percent output of the 4 motors."""
bl_signal = math.copysign(abs(bl_signal)**Constants.BL_EXP, bl_signal)
br_signal = math.copysign(abs(br_signal)**Constants.BR_EXP, br_signal)
fl_signal = math.copysign(abs(fl_signal)**Constants.FL_EXP, fl_signal)
fr_signal = math.copysign(abs(fr_signal)**Constants.FR_EXP, fr_signal)
self.bl_motor.setPercentOutput(
bl_signal, max_signal=Constants.MAX_DRIVE_OUTPUT)
self.br_motor.setPercentOutput(
br_signal, max_signal=Constants.MAX_DRIVE_OUTPUT)
self.fl_motor.setPercentOutput(
fl_signal, max_signal=Constants.MAX_DRIVE_OUTPUT)
self.fr_motor.setPercentOutput(
fr_signal, max_signal=Constants.MAX_DRIVE_OUTPUT)
def setDirectionOutput(self, x_signal, y_signal, rotation):
"""Set percent output of the 4 motors given an x, y, and rotation inputs."""
if Constants.MAX_TURN_SPEED < abs(rotation):
rotation = math.copysign(Constants.MAX_TURN_SPEED, rotation)
bl_signal = x_signal - y_signal + rotation
br_signal = x_signal + y_signal - rotation
fl_signal = x_signal + y_signal + rotation
fr_signal = x_signal - y_signal - rotation
self.setPercentOutput(bl_signal, br_signal, fl_signal, fr_signal)
def setDirectionVelocity(self, x_signal, y_signal, rotation):
"""Set percent output of the 4 motors given an x, y, and rotation inputs."""
bl_signal = x_signal - y_signal + rotation
br_signal = x_signal + y_signal - rotation
fl_signal = x_signal + y_signal + rotation
fr_signal = x_signal - y_signal - rotation
self.setVelocityOutput(bl_signal, br_signal, fl_signal, fr_signal)
def setVelocityOutput(self, bl_velocity, br_velocity, fl_velocity, fr_velocity):
self.bl_motor.setVelocitySetpoint(bl_velocity)
self.br_motor.setVelocitySetpoint(br_velocity)
self.fl_motor.setVelocitySetpoint(fl_velocity)
self.fr_motor.setVelocitySetpoint(fr_velocity)
def initDefaultCommand(self):
return self.setDefaultCommand(tankdrive.TankDrive())
def periodic(self):
self.outputToDashboard()
def reset(self):
self.zeroSensors()
self.initPIDF()
|
the-stack_0_8591 | import numpy as np
import scipy.signal
from typing import Dict, Optional
from ray.rllib.evaluation.episode import MultiAgentEpisode
from ray.rllib.policy.policy import Policy
from ray.rllib.policy.sample_batch import SampleBatch
from ray.rllib.utils.annotations import DeveloperAPI
from ray.rllib.utils.typing import AgentID
class Postprocessing:
"""Constant definitions for postprocessing."""
ADVANTAGES = "advantages"
VALUE_TARGETS = "value_targets"
def adjust_nstep(n_step: int, gamma: float, batch: SampleBatch) -> None:
"""Rewrites `batch` to encode n-step rewards, dones, and next-obs.
Observations and actions remain unaffected. At the end of the trajectory,
n is truncated to fit in the traj length.
Args:
n_step (int): The number of steps to look ahead and adjust.
gamma (float): The discount factor.
batch (SampleBatch): The SampleBatch to adjust (in place).
Examples:
n-step=3
Trajectory=o0 r0 d0, o1 r1 d1, o2 r2 d2, o3 r3 d3, o4 r4 d4=True o5
gamma=0.9
Returned trajectory:
0: o0 [r0 + 0.9*r1 + 0.9^2*r2 + 0.9^3*r3] d3 o0'=o3
1: o1 [r1 + 0.9*r2 + 0.9^2*r3 + 0.9^3*r4] d4 o1'=o4
2: o2 [r2 + 0.9*r3 + 0.9^2*r4] d4 o1'=o5
3: o3 [r3 + 0.9*r4] d4 o3'=o5
4: o4 r4 d4 o4'=o5
"""
assert not any(batch[SampleBatch.DONES][:-1]), \
"Unexpected done in middle of trajectory!"
len_ = len(batch)
# Shift NEXT_OBS and DONES.
batch[SampleBatch.NEXT_OBS] = np.concatenate(
[
batch[SampleBatch.OBS][n_step:],
np.stack([batch[SampleBatch.NEXT_OBS][-1]] * min(n_step, len_))
],
axis=0)
batch[SampleBatch.DONES] = np.concatenate(
[
batch[SampleBatch.DONES][n_step - 1:],
np.tile(batch[SampleBatch.DONES][-1], min(n_step - 1, len_))
],
axis=0)
# Change rewards in place.
for i in range(len_):
for j in range(1, n_step):
if i + j < len_:
batch[SampleBatch.REWARDS][i] += \
gamma**j * batch[SampleBatch.REWARDS][i + j]
@DeveloperAPI
def compute_advantages(rollout: SampleBatch,
last_r: float,
gamma: float = 0.9,
lambda_: float = 1.0,
use_gae: bool = True,
use_critic: bool = True):
"""
Given a rollout, compute its value targets and the advantages.
Args:
rollout (SampleBatch): SampleBatch of a single trajectory.
last_r (float): Value estimation for last observation.
gamma (float): Discount factor.
lambda_ (float): Parameter for GAE.
use_gae (bool): Using Generalized Advantage Estimation.
use_critic (bool): Whether to use critic (value estimates). Setting
this to False will use 0 as baseline.
Returns:
SampleBatch (SampleBatch): Object with experience from rollout and
processed rewards.
"""
assert SampleBatch.VF_PREDS in rollout or not use_critic, \
"use_critic=True but values not found"
assert use_critic or not use_gae, \
"Can't use gae without using a value function"
if use_gae:
vpred_t = np.concatenate(
[rollout[SampleBatch.VF_PREDS],
np.array([last_r])])
delta_t = (
rollout[SampleBatch.REWARDS] + gamma * vpred_t[1:] - vpred_t[:-1])
# This formula for the advantage comes from:
# "Generalized Advantage Estimation": https://arxiv.org/abs/1506.02438
rollout[Postprocessing.ADVANTAGES] = discount_cumsum(
delta_t, gamma * lambda_)
rollout[Postprocessing.VALUE_TARGETS] = (
rollout[Postprocessing.ADVANTAGES] +
rollout[SampleBatch.VF_PREDS]).astype(np.float32)
else:
rewards_plus_v = np.concatenate(
[rollout[SampleBatch.REWARDS],
np.array([last_r])])
discounted_returns = discount_cumsum(rewards_plus_v,
gamma)[:-1].astype(np.float32)
if use_critic:
rollout[Postprocessing.
ADVANTAGES] = discounted_returns - rollout[SampleBatch.
VF_PREDS]
rollout[Postprocessing.VALUE_TARGETS] = discounted_returns
else:
rollout[Postprocessing.ADVANTAGES] = discounted_returns
rollout[Postprocessing.VALUE_TARGETS] = np.zeros_like(
rollout[Postprocessing.ADVANTAGES])
rollout[Postprocessing.ADVANTAGES] = rollout[
Postprocessing.ADVANTAGES].astype(np.float32)
return rollout
def compute_gae_for_sample_batch(
policy: Policy,
sample_batch: SampleBatch,
other_agent_batches: Optional[Dict[AgentID, SampleBatch]] = None,
episode: Optional[MultiAgentEpisode] = None) -> SampleBatch:
"""Adds GAE (generalized advantage estimations) to a trajectory.
The trajectory contains only data from one episode and from one agent.
- If `config.batch_mode=truncate_episodes` (default), sample_batch may
contain a truncated (at-the-end) episode, in case the
`config.rollout_fragment_length` was reached by the sampler.
- If `config.batch_mode=complete_episodes`, sample_batch will contain
exactly one episode (no matter how long).
New columns can be added to sample_batch and existing ones may be altered.
Args:
policy (Policy): The Policy used to generate the trajectory
(`sample_batch`)
sample_batch (SampleBatch): The SampleBatch to postprocess.
other_agent_batches (Optional[Dict[PolicyID, SampleBatch]]): Optional
dict of AgentIDs mapping to other agents' trajectory data (from the
same episode). NOTE: The other agents use the same policy.
episode (Optional[MultiAgentEpisode]): Optional multi-agent episode
object in which the agents operated.
Returns:
SampleBatch: The postprocessed, modified SampleBatch (or a new one).
"""
# Trajectory is actually complete -> last r=0.0.
if sample_batch[SampleBatch.DONES][-1]:
last_r = 0.0
# Trajectory has been truncated -> last r=VF estimate of last obs.
else:
# Input dict is provided to us automatically via the Model's
# requirements. It's a single-timestep (last one in trajectory)
# input_dict.
# Create an input dict according to the Model's requirements.
input_dict = sample_batch.get_single_step_input_dict(
policy.model.view_requirements, index="last")
last_r = policy._value(**input_dict)
# Adds the policy logits, VF preds, and advantages to the batch,
# using GAE ("generalized advantage estimation") or not.
batch = compute_advantages(
sample_batch,
last_r,
policy.config["gamma"],
policy.config["lambda"],
use_gae=policy.config["use_gae"],
use_critic=policy.config.get("use_critic", True))
return batch
def discount_cumsum(x: np.ndarray, gamma: float) -> np.ndarray:
"""Calculates the discounted cumulative sum over a reward sequence `x`.
y[t] - discount*y[t+1] = x[t]
reversed(y)[t] - discount*reversed(y)[t-1] = reversed(x)[t]
Args:
gamma (float): The discount factor gamma.
Returns:
np.ndarray: The sequence containing the discounted cumulative sums
for each individual reward in `x` till the end of the trajectory.
Examples:
>>> x = np.array([0.0, 1.0, 2.0, 3.0])
>>> gamma = 0.9
>>> discount_cumsum(x, gamma)
... array([0.0 + 0.9*1.0 + 0.9^2*2.0 + 0.9^3*3.0,
... 1.0 + 0.9*2.0 + 0.9^2*3.0,
... 2.0 + 0.9*3.0,
... 3.0])
"""
return scipy.signal.lfilter([1], [1, float(-gamma)], x[::-1], axis=0)[::-1]
|
the-stack_0_8594 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from .resource_py3 import Resource
class VirtualWAN(Resource):
"""VirtualWAN Resource.
Variables are only populated by the server, and will be ignored when
sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: Resource tags.
:type tags: dict[str, str]
:param disable_vpn_encryption: Vpn encryption to be disabled or not.
:type disable_vpn_encryption: bool
:ivar virtual_hubs: List of VirtualHubs in the VirtualWAN.
:vartype virtual_hubs:
list[~azure.mgmt.network.v2019_02_01.models.SubResource]
:ivar vpn_sites: List of VpnSites in the VirtualWAN.
:vartype vpn_sites:
list[~azure.mgmt.network.v2019_02_01.models.SubResource]
:param security_provider_name: The Security Provider name.
:type security_provider_name: str
:param allow_branch_to_branch_traffic: True if branch to branch traffic is
allowed.
:type allow_branch_to_branch_traffic: bool
:param allow_vnet_to_vnet_traffic: True if Vnet to Vnet traffic is
allowed.
:type allow_vnet_to_vnet_traffic: bool
:param office365_local_breakout_category: The office local breakout
category. Possible values include: 'Optimize', 'OptimizeAndAllow', 'All',
'None'
:type office365_local_breakout_category: str or
~azure.mgmt.network.v2019_02_01.models.OfficeTrafficCategory
:param p2_svpn_server_configurations: List of all
P2SVpnServerConfigurations associated with the virtual wan.
:type p2_svpn_server_configurations:
list[~azure.mgmt.network.v2019_02_01.models.P2SVpnServerConfiguration]
:param provisioning_state: The provisioning state of the resource.
Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed'
:type provisioning_state: str or
~azure.mgmt.network.v2019_02_01.models.ProvisioningState
:ivar etag: Gets a unique read-only string that changes whenever the
resource is updated.
:vartype etag: str
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'virtual_hubs': {'readonly': True},
'vpn_sites': {'readonly': True},
'etag': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'disable_vpn_encryption': {'key': 'properties.disableVpnEncryption', 'type': 'bool'},
'virtual_hubs': {'key': 'properties.virtualHubs', 'type': '[SubResource]'},
'vpn_sites': {'key': 'properties.vpnSites', 'type': '[SubResource]'},
'security_provider_name': {'key': 'properties.securityProviderName', 'type': 'str'},
'allow_branch_to_branch_traffic': {'key': 'properties.allowBranchToBranchTraffic', 'type': 'bool'},
'allow_vnet_to_vnet_traffic': {'key': 'properties.allowVnetToVnetTraffic', 'type': 'bool'},
'office365_local_breakout_category': {'key': 'properties.office365LocalBreakoutCategory', 'type': 'str'},
'p2_svpn_server_configurations': {'key': 'properties.p2SVpnServerConfigurations', 'type': '[P2SVpnServerConfiguration]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
}
def __init__(self, *, id: str=None, location: str=None, tags=None, disable_vpn_encryption: bool=None, security_provider_name: str=None, allow_branch_to_branch_traffic: bool=None, allow_vnet_to_vnet_traffic: bool=None, office365_local_breakout_category=None, p2_svpn_server_configurations=None, provisioning_state=None, **kwargs) -> None:
super(VirtualWAN, self).__init__(id=id, location=location, tags=tags, **kwargs)
self.disable_vpn_encryption = disable_vpn_encryption
self.virtual_hubs = None
self.vpn_sites = None
self.security_provider_name = security_provider_name
self.allow_branch_to_branch_traffic = allow_branch_to_branch_traffic
self.allow_vnet_to_vnet_traffic = allow_vnet_to_vnet_traffic
self.office365_local_breakout_category = office365_local_breakout_category
self.p2_svpn_server_configurations = p2_svpn_server_configurations
self.provisioning_state = provisioning_state
self.etag = None
|
the-stack_0_8595 | from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
import os
from flask_cors import CORS
# Init app
app = Flask(__name__)
#config headers
CORS(app)
basedir = os.path.abspath(os.path.dirname(__file__))
# Database
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'db.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# Init db
db = SQLAlchemy(app)
# Init ma
ma = Marshmallow(app)
# Post Class/Model
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100))
post = db.Column(db.String(300))
def __init__(self, name, post):
self.name = name
self.post = post
# Post Schema
class PostSchema(ma.Schema):
class Meta:
fields = ('id', 'name', 'post')
# Init schema
post_schema = PostSchema()
posts_schema = PostSchema(many=True)
# Create a Post
@app.route('/post', methods=['POST'])
def add_post():
name = request.json['name']
post = request.json['post']
new_post = Post(name, post)
db.session.add(new_post)
db.session.commit()
return post_schema.jsonify(new_post)
# Get All Posts
@app.route('/post', methods=['GET'])
def get_posts():
all_posts = Post.query.all()
result = posts_schema.dump(all_posts)
return jsonify(result)
# Get Single Post
@app.route('/post/<id>', methods=['GET'])
def get_post(id):
post = Post.query.get(id)
return post_schema.jsonify(post)
# Update a Post
@app.route('/post/<id>', methods=['PUT'])
def update_post(id):
my_post = Post.query.get(id)
name = request.json['name']
post = request.json['post']
my_post.name = name
my_post.post = post
db.session.commit()
return post_schema.jsonify(my_post)
# Delete Post
@app.route('/post/<id>', methods=['DELETE'])
def delete_post(id):
post = Post.query.get(id)
db.session.delete(post)
db.session.commit()
return post_schema.jsonify(post)
# Run Server
if __name__ == '__main__':
app.run(debug=True) |
the-stack_0_8597 | import sys
import pygame
from pygame.locals import *
from constants import *
from event import HandleEvent
from utils.vector import Vector3
from utils.camera import Camera
from utils.light import Light
from utils.mesh.base import Mesh
from utils.mesh.meshes import *
from utils.mesh.spheres import *
from utils.mesh.point import *
from utils.matrix import *
from utils.tools import *
from utils.world import Scene
from random import randint
pygame.init()
flags = DOUBLEBUF
screen = pygame.display.set_mode(Size, flags, 16)
clock = pygame.time.Clock()
fps = 240
#mouse setup
pygame.mouse.get_rel()
pygame.mouse.set_visible(True)
a = pygame.event.set_grab(False)
# create scene and the world
res = 3
scene = Scene()
for x in range(res):
for y in range(res):
for z in range(res):
cube = Mesh()
s = 5
r = randint(10, 255)
g = randint(10, 255)
b = randint(10, 255)
cube.triangles = CubeTriangles((r, g, b),Vector3(x * s, y * s, z * s), s)
cube.position = Vector3(x * s, y * s, z * s)
cube.transform = Matrix.scaling(0.1)
scene.world.append(cube)
#camera setup
camera = Camera(Vector3(0, 0, 0), 0.1, 1000.0, 75.0)
camera.speed = 0.5
camera.rotationSpeed = 0.8
#light setup
light = Light(Vector3(0.9, 0.9, -1))
hue = 0
angle = 0
moveLight = True
run = True
while run:
screen.fill(BackgroundColor)
clock.tick(fps)
dt = clock.tick(fps)/100
frameRate = clock.get_fps()
pygame.display.set_caption(str(frameRate) + " fps")
run = HandleEvent(camera, dt)
hue = 0
camera.HandleInput(dt)
if moveLight == True and light != None:
mx, my = pygame.mouse.get_pos()
_x = translateValue( mx, 0, Width, -1, 1)
_y = translateValue( my, 0, Height, -1, 1)
light = Light(Vector3(-_x, -_y, -1))
scene.update(
dt = dt,
camera=camera,
light=light,
screen=screen,
showAxis=True,
fill=True,
wireframe=True,
vertices=True,
depth=True,
clippingDebug=False,
showNormals=False,
radius=2,
verticeColor=False,
wireframeColor=(255, 255, 255),
ChangingColor=hue)
pygame.display.flip()
angle += 0.01
pygame.quit()
sys.exit()
|
the-stack_0_8598 | from torchvision.datasets import CIFAR10
from torchvision.datasets import CIFAR100
from torch.utils.data import DataLoader
from torchvision.transforms import Compose, Pad, RandomCrop, RandomHorizontalFlip
from torchvision.transforms import ToTensor, Normalize
CIFAR10_CLASS = [
"airplane", "automobile", "bird", "cat", "deer",
"dog", "frog", "horse", "ship", "truck"
]
class WrappedCIFAR10(CIFAR10):
def __init__(self, root, train=True, download=False, *args, **kwargs):
self.categories = CIFAR10_CLASS
if train:
transforms = Compose([
Pad(padding=4),
RandomCrop(size=32),
RandomHorizontalFlip(p=0.5),
ToTensor(),
Normalize(mean=(0.485, 0.456, 0.406),
std=(0.229, 0.224, 0.225))
])
else:
transforms = Compose([
RandomHorizontalFlip(p=0.5),
ToTensor(),
Normalize(mean=(0.485, 0.456, 0.406),
std=(0.229, 0.224, 0.225))
])
super(WrappedCIFAR10, self).__init__(
root=root, train=train, transform=transforms,
download=download, *args, **kwargs)
class WrappedCIFAR100(CIFAR100):
def __init__(self, root, train=True, download=False, *args, **kwargs):
if train:
transforms = Compose([
Pad(padding=4),
RandomCrop(size=32),
RandomHorizontalFlip(p=0.5),
ToTensor(),
Normalize(mean=(0.485, 0.456, 0.406),
std=(0.229, 0.224, 0.225))
])
else:
transforms = Compose([
RandomHorizontalFlip(p=0.5),
ToTensor(),
Normalize(mean=(0.485, 0.456, 0.406),
std=(0.229, 0.224, 0.225))
])
super(WrappedCIFAR100, self).__init__(
root=root, train=train, transform=transforms,
download=download, *args, **kwargs)
if __name__ == '__main__':
# You need to change the argument according to your own settings.
ROOT = "path/to/data"
def download_CIFAR10():
print("Downloading CIFAR10......")
CIFAR = WrappedCIFAR10(root=ROOT, download=True)
def test_CIFAR10():
CIFAR = WrappedCIFAR10(root=ROOT, train=True)
CIFAR_dataloader = DataLoader(CIFAR, batch_size=4, shuffle=True, num_workers=4)
for i in CIFAR_dataloader:
print(i[0].shape, i[1])
def test_CIFAR10_using_network():
from torch.utils import data
from models.resnet import ResNetMini
from loss import fetch_loss
from optimizer import fetch_optimizer
batch_size = 4
epoch = 1
train_data = WrappedCIFAR10(root=ROOT, train=True)
train_loader = data.DataLoader(
train_data, batch_size=batch_size,
shuffle=True, num_workers=4)
network = ResNetMini().cuda()
loss_func = fetch_loss()
optim = fetch_optimizer()(network.parameters(), lr=0.001, momentum=0.9)
for e in range(epoch):
for iter, data in enumerate(train_loader):
I, Y = data
I, Y = I.cuda(), Y.cuda()
Y_pre = network(I)
loss = loss_func(Y_pre, Y)
optim.zero_grad()
loss.backward()
optim.step()
if iter % 100 == 0:
print("iter: ", iter, " , loss: ", loss.item())
# download_CIFAR10()
# test_CIFAR10()
# test_CIFAR10_using_network()
|
the-stack_0_8600 | import sys
from typing import List
def reverse_args(av: List[str]) -> None:
if len(av) == 1:
return
without_program_name = av[1:len(av)]
joined = ' '.join(without_program_name)
reversed = joined[::-1]
swap_Aa_aA = reversed.swapcase()
print(swap_Aa_aA)
return
if __name__ == "__main__":
reverse_args(sys.argv) |
the-stack_0_8601 | """
example showing how to plot data from a DEM file and an ESRI shape file using
gdal (http://pypi.python.org/pypi/GDAL).
"""
from osgeo import gdal, ogr
from mpl_toolkits.basemap import Basemap, cm
import numpy as np
import matplotlib.pyplot as plt
from numpy import ma
# read 2.5 minute U.S. DEM file using gdal.
# (http://www.prism.oregonstate.edu/docs/meta/dem_25m.htm)
gd = gdal.Open('us_25m.dem')
array = gd.ReadAsArray()
# get lat/lon coordinates from DEM file.
coords = gd.GetGeoTransform()
nlons = array.shape[1]; nlats = array.shape[0]
delon = coords[1]
delat = coords[5]
lons = coords[0] + delon*np.arange(nlons)
lats = coords[3] + delat*np.arange(nlats)[::-1] # reverse lats
# setup figure.
fig = plt.figure(figsize=(11,6))
# setup basemap instance.
m = Basemap(llcrnrlon=-119,llcrnrlat=22,urcrnrlon=-64,urcrnrlat=49,
projection='lcc',lat_1=33,lat_2=45,lon_0=-95)
# create masked array, reversing data in latitude direction
# (so that data is oriented in increasing latitude, as transform_scalar requires).
topoin = ma.masked_values(array[::-1,:],-999.)
# transform DEM data to a 4 km native projection grid
nx = int((m.xmax-m.xmin)/4000.)+1; ny = int((m.ymax-m.ymin)/4000.)+1
topodat = m.transform_scalar(topoin,lons,lats,nx,ny,masked=True)
# plot DEM image on map.
im = m.imshow(topodat,cmap=cm.GMT_haxby_r)
# draw meridians and parallels.
m.drawparallels(np.arange(20,71,10),labels=[1,0,0,0])
m.drawmeridians(np.arange(-120,-40,10),labels=[0,0,0,1])
# plot state boundaries from shapefile using ogr.
g = ogr.Open ("st99_d00.shp")
L = g.GetLayer(0) # data is in 1st layer.
for feat in L: # iterate over features in layer
geo = feat.GetGeometryRef()
# iterate over geometries.
for count in range(geo.GetGeometryCount()):
geom = geo.GetGeometryRef(count)
if not geom.GetGeometryCount(): # just one geometry.
# get lon,lat points
lons = [geom.GetX(i) for i in range(geom.GetPointCount())]
lats = [geom.GetY(i) for i in range(geom.GetPointCount())]
# convert to map projection coords.
x, y = m(lons,lats)
# plot on map.
m.plot(x,y,'k')
else: # iterate over nested geometries.
for cnt in range( geom.GetGeometryCount()):
g = geom.GetGeometryRef( cnt )
lons = [g.GetX(i) for i in range(g.GetPointCount())]
lats = [g.GetY(i) for i in range(g.GetPointCount())]
x, y = m(lons,lats)
m.plot(x,y,'k')
# draw colorbar.
m.colorbar(im)
plt.title(gd.GetDescription()+' with state boundaries from '+g.GetName(),y=1.05)
plt.show()
|
the-stack_0_8607 | # Copyright 2015 VMware, Inc.
# 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 required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import mock
from neutron.tests import base
from vmware_nsx.plugins.nsx_v.vshield import vcns_driver
from vmware_nsx.services.lbaas.nsx_v import lbaas_common as lb_common
EDGE_ID = 'edge-x'
POOL_ID = 'b3dfb476-6fdf-4ddd-b6bd-e86ae78dc30b'
def firewall_section_maker(if_ip_list, vip_ip_list):
return (
'<section id="1132" name="LBaaS FW Rules"><rule><name>' + POOL_ID +
'</name><action>allow</action><sources excluded="false"><source>'
'<type>Ipv4Address</type><value>' + ','.join(if_ip_list) +
'</value></source></sources><destinations excluded="false">'
'<destination><type>Ipv4Address</type><value>' +
','.join(vip_ip_list) + '</value></destination></destinations></rule>'
'</section>')
def if_maker(ip_list):
intf = {
'index': 1, 'name': 'internal1', 'addressGroups': {
'addressGroups': [
{'subnetPrefixLength': '24',
'secondaryAddresses': {
'ipAddress': ip_list,
'type': 'secondary_addresses'},
'primaryAddress': '10.0.0.1',
'subnetMask': '255.255.255.0'}]},
'portgroupName': 'pg1234', 'label': 'vNic_1',
'type': 'internal', 'portgroupId': 'virtualwire-31'}
return intf
def if_list_maker(ip_list):
if_list = {
'vnics': [
{'index': 0, 'name': 'external', 'addressGroups': {
'addressGroups': [
{'subnetMask': '255.255.255.0',
'primaryAddress': '172.24.4.2',
'subnetPrefixLength': '24'}]},
'portgroupName': 'VM Network', 'label': 'vNic_0',
'type': 'uplink', 'portgroupId': 'network-13'},
{'index': 1, 'name': 'internal1', 'addressGroups': {
'addressGroups': [
{'subnetPrefixLength': '24',
'secondaryAddresses': {
'ipAddress': ip_list,
'type': 'secondary_addresses'},
'primaryAddress': '10.0.0.1',
'subnetMask': '255.255.255.0'}]},
'portgroupName': 'pg1234',
'label': 'vNic_1', 'type': 'internal',
'portgroupId': 'virtualwire-31'},
{'index': 2, 'name': 'vnic2',
'addressGroups': {'addressGroups': []},
'label': 'vNic_2', 'type': 'internal'},
{'index': 3, 'name': 'vnic3',
'addressGroups': {'addressGroups': []},
'label': 'vNic_3', 'type': 'internal'}]}
return if_list
class TestLbaasCommon(base.BaseTestCase):
def setUp(self):
super(TestLbaasCommon, self).setUp()
callbacks = mock.Mock()
callbacks.plugin = mock.Mock()
self.edge_driver = vcns_driver.VcnsDriver(callbacks)
self.edge_driver._lb_driver_prop = mock.Mock()
def _mock_edge_driver_vcns(self, attr):
return mock.patch.object(self.edge_driver.vcns, attr)
def test_add_vip_as_secondary_ip(self):
update_if = if_maker(['10.0.0.6', '10.0.0.8'])
with self._mock_edge_driver_vcns('get_interfaces') as mock_get_if,\
self._mock_edge_driver_vcns(
'update_interface') as mock_update_if:
mock_get_if.return_value = (None, if_list_maker(['10.0.0.6']))
lb_common.add_vip_as_secondary_ip(
self.edge_driver.vcns, EDGE_ID, '10.0.0.8')
mock_update_if.assert_called_with(EDGE_ID, update_if)
def test_del_vip_as_secondary_ip(self):
update_if = if_maker(['10.0.0.6'])
with self._mock_edge_driver_vcns('get_interfaces') as mock_get_if,\
self._mock_edge_driver_vcns(
'update_interface') as mock_update_if:
mock_get_if.return_value = (None, if_list_maker(['10.0.0.6',
'10.0.0.8']))
lb_common.del_vip_as_secondary_ip(
self.edge_driver.vcns, EDGE_ID, '10.0.0.8')
mock_update_if.assert_called_with(EDGE_ID, update_if)
def test_get_edge_ip_addresses(self):
get_if_list = if_list_maker(['10.0.0.6'])
with mock.patch.object(self.edge_driver.vcns, 'get_interfaces',
return_value=(None, get_if_list)):
ip_list = lb_common.get_edge_ip_addresses(self.edge_driver.vcns,
EDGE_ID)
self.assertEqual(['172.24.4.2', '10.0.0.1'], ip_list)
|
the-stack_0_8608 | #!/usr/bin/env python3
# Copyright 2019 Intel Corporation
#
# 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 writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
import json
import logging
import os
import sys
import time
import random
import hashlib
import avalon_enclave_manager.sgx_work_order_request as work_order_request
import avalon_enclave_manager.avalon_enclave_helper as enclave_helper
import avalon_crypto_utils.signature as signature
import avalon_crypto_utils.crypto_utility as crypto_utils
from database import connector
from error_code.error_status import ReceiptCreateStatus, WorkOrderStatus
from avalon_sdk.worker.worker_details import WorkerStatus, WorkerType
from avalon_sdk.work_order_receipt.work_order_receipt \
import WorkOrderReceiptRequest
logger = logging.getLogger(__name__)
# representation of the enclave data
enclave_data = None
# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
class EnclaveManager:
"""
Wrapper for managing Worker data
"""
def __init__(self, config, signup_data, measurements):
self.config = config
self.enclave_data = signup_data
self.sealed_data = signup_data.sealed_data
self.verifying_key = signup_data.verifying_key
self.encryption_key = signup_data.encryption_key
# TODO: EncryptionKeyNonce and EncryptionKeySignature are hardcoded
# to dummy values.
# Need to come up with a scheme to generate both for every unique
# encryption key.
self.encryption_key_nonce = ""
self.encryption_key_signature = ""
self.enclave_id = signup_data.enclave_id
self.extended_measurements = measurements
# ProofDataType is one of TEE prefixed type
# TODO: Read ProofDataType from config file
self.proof_data_type = config.get("WorkerConfig")["ProofDataType"]
self.proof_data = signup_data.proof_data
# Key pair for work order receipt signing
# This is temporary approach
self.private_key = crypto_utils.generate_signing_keys()
self.public_key = self.private_key.GetPublicKey().Serialize()
def manager_on_boot(self, kv_helper):
"""
Executes Boot flow of enclave manager
"""
logger.info("Executing boot time procedure")
# Cleanup "workers" table
workers_list = kv_helper.lookup("workers")
if len(workers_list) == 0:
logger.info("No worker entries available in workers table; " +
"skipping cleanup")
else:
logger.info("Clearing entries in workers table")
for worker in workers_list:
kv_helper.remove("workers", worker)
worker_info = create_json_worker(self, self.config)
logger.info("Adding enclave workers to workers table")
worker_id = crypto_utils.strip_begin_end_public_key(self.enclave_id) \
.encode("UTF-8")
# Calculate sha256 of worker id to get 32 bytes. The TC spec proxy
# model contracts expect byte32. Then take a hexdigest for hex str.
worker_id = hashlib.sha256(worker_id).hexdigest()
kv_helper.set("workers", worker_id, worker_info)
# Cleanup wo-processing" table
processing_list = kv_helper.lookup("wo-processing")
if len(processing_list) == 0:
logger.info("No workorder entries found in " +
"wo-processing table, skipping Cleanup")
return
for wo in processing_list:
logger.info("Validating workorders in wo-processing table")
wo_json_resp = kv_helper.get("wo-responses", wo)
wo_processed = kv_helper.get("wo-processed", wo)
if wo_json_resp is not None:
try:
wo_resp = json.loads(wo_json_resp)
except ValueError as e:
logger.error(
"Invalid JSON format found for the response for " +
"workorder %s - %s", wo, e)
if wo_processed is None:
kv_helper.set("wo-processed", wo,
WorkOrderStatus.FAILED.name)
kv_helper.remove("wo-processing", wo)
continue
if "Response" in wo_resp and \
wo_resp["Response"]["Status"] == \
WorkOrderStatus.FAILED:
if wo_processed is None:
kv_helper.set("wo-processed", wo,
WorkOrderStatus.FAILED.name)
logger.error("Work order processing failed; " +
"removing it from wo-processing table")
kv_helper.remove("wo-processing", wo)
continue
wo_receipt = kv_helper.get("wo-receipts", wo)
if wo_receipt:
# update receipt
logger.info("Updating receipt in boot flow")
self.__update_receipt(kv_helper, wo, wo_json_resp)
logger.info("Receipt updated for workorder %s during boot",
wo)
if wo_processed is None:
kv_helper.set("wo-processed", wo,
WorkOrderStatus.SUCCESS.name)
else:
logger.info("No response found for the workorder %s; " +
"hence placing the workorder request " +
"back in wo-scheduled", wo)
kv_helper.set("wo-scheduled", wo,
WorkOrderStatus.SCHEDULED.name)
logger.info(
"Finally deleting workorder %s from wo-processing table", wo)
kv_helper.remove("wo-processing", wo)
# End of for-loop
# -----------------------------------------------------------------
def process_work_orders(self, kv_helper):
"""
Executes Run time flow of enclave manager
"""
logger.info("Processing work orders")
try:
# Get all workorders requests from KV storage lookup and process
list_of_workorders = kv_helper.lookup("wo-scheduled")
if not list_of_workorders:
logger.info("Received empty list of work orders from " +
"wo-scheduled table")
return
except Exception as e:
logger.error("Problem while getting keys from wo-scheduled table")
return
for wo_id in list_of_workorders:
try:
kv_helper.set("wo-processing", wo_id,
WorkOrderStatus.PROCESSING.name)
# Get JSON workorder request corresponding to wo_id
wo_json_req = kv_helper.get("wo-requests", wo_id)
if wo_json_req is None:
logger.error("Received empty work order corresponding " +
"to id %s from wo-requests table", wo_id)
kv_helper.remove("wo-processing", wo_id)
return
except Exception as e:
logger.error("Problem while reading the work order %s"
"from wo-requests table", wo_id)
kv_helper.remove("wo-processing", wo_id)
return
logger.info("Create workorder entry %s in wo-processing table",
wo_id)
kv_helper.set("wo-processing", wo_id,
WorkOrderStatus.PROCESSING.name)
logger.info("Delete workorder entry %s from wo-scheduled table",
wo_id)
kv_helper.remove("wo-scheduled", wo_id)
logger.info("Validating JSON workorder request %s", wo_id)
validation_status = validate_request(wo_json_req)
if not validation_status:
logger.error(
"JSON validation for Workorder %s failed; " +
"handling Failure scenarios", wo_id)
wo_response["Response"]["Status"] = WorkOrderStatus.FAILED
wo_response["Response"]["Message"] = \
"Workorder JSON request is invalid"
kv_helper.set("wo-responses", wo_id, json.dumps(wo_response))
kv_helper.set("wo-processed", wo_id,
WorkOrderStatus.FAILED.name)
kv_helper.remove("wo-processing", wo_id)
return
# Execute work order request
logger.info("Execute workorder with id %s", wo_id)
wo_json_resp = execute_work_order(self.enclave_data, wo_json_req)
wo_resp = json.loads(wo_json_resp)
logger.info("Update workorder receipt for workorder %s", wo_id)
receipt = self.__update_receipt(kv_helper, wo_id, wo_resp)
if "Response" in wo_resp and \
wo_resp["Response"]["Status"] == WorkOrderStatus.FAILED:
logger.error("error in Response")
kv_helper.set("wo-processed", wo_id,
WorkOrderStatus.FAILED.name)
kv_helper.set("wo-responses", wo_id, wo_json_resp)
kv_helper.remove("wo-processing", wo_id)
return
logger.info("Mark workorder status for workorder id %s " +
"as Completed in wo-processed", wo_id)
kv_helper.set("wo-processed", wo_id, WorkOrderStatus.SUCCESS.name)
logger.info("Create entry in wo-responses table for workorder %s",
wo_id)
kv_helper.set("wo-responses", wo_id, wo_json_resp)
logger.info("Delete workorder entry %s from wo-processing table",
wo_id)
kv_helper.remove("wo-processing", wo_id)
# end of for loop
# -----------------------------------------------------------------
def __update_receipt(self, kv_helper, wo_id, wo_json_resp):
"""
Update the existing work order receipt with the status as in wo_json_
Parameters:
- kv_helper is lmdb instance to access database
- wo_id is work order id of request for which receipt is to be
created.
- wo_json_resp is json rpc response of the work order execution.
status of the work order receipt and updater signature update in
the receipt.
"""
receipt_entry = kv_helper.get("wo-receipts", wo_id)
if receipt_entry:
update_type = None
if "error" in wo_json_resp and \
wo_json_resp["error"]["code"] != \
WorkOrderStatus.PENDING.value:
update_type = ReceiptCreateStatus.FAILED.value
else:
update_type = ReceiptCreateStatus.PROCESSED.value
receipt_obj = WorkOrderReceiptRequest()
wo_receipt = receipt_obj.update_receipt(
wo_id,
update_type,
wo_json_resp,
self.private_key
)
updated_receipt = None
# load previous updates to receipt
updates_to_receipt = kv_helper.get("wo-receipt-updates", wo_id)
# If it is first update to receipt
if updates_to_receipt is None:
updated_receipt = []
else:
updated_receipt = json.loads(updates_to_receipt)
# Get the last update to receipt
last_receipt = updated_receipt[len(updated_receipt) - 1]
# If receipt updateType is completed,
# then no further update allowed
if last_receipt["updateType"] == \
ReceiptCreateStatus.COMPLETED.value:
logger.info(
"Receipt for the workorder id %s is completed " +
"and no further updates are allowed",
wo_id)
return
updated_receipt.append(wo_receipt)
# Since receipts_json is jrpc request updating only params object.
kv_helper.set("wo-receipt-updates", wo_id, json.dumps(
updated_receipt))
logger.info("Receipt for the workorder id %s is updated to %s",
wo_id, wo_receipt)
else:
logger.info("Work order receipt is not created, " +
"so skipping the update")
# -----------------------------------------------------------------
def create_enclave_signup_data():
"""
Create enclave signup data
"""
try:
enclave_signup_data = \
enclave_helper.EnclaveHelper.create_enclave_signup_data()
except Exception as e:
logger.error("failed to create enclave signup data; %s", str(e))
sys.exit(-1)
return enclave_signup_data
# -----------------------------------------------------------------
def execute_work_order(enclave_data, input_json_str, indent=4):
"""
Submits workorder request to Worker enclave and retrieves the response
"""
try:
wo_request = work_order_request.SgxWorkOrderRequest(
enclave_data,
input_json_str)
wo_response = wo_request.execute()
try:
json_response = json.dumps(wo_response, indent=indent)
except Exception as err:
logger.error("ERROR: Failed to serialize JSON; %s", str(err))
wo_response["Response"]["Status"] = WorkOrderStatus.FAILED
wo_response["Response"]["Message"] = "Failed to serialize JSON"
json_response = json.dumps(wo_response)
except Exception as e:
logger.error("failed to execute work order; %s", str(e))
wo_response["Response"]["Status"] = WorkOrderStatus.FAILED
wo_response["Response"]["Message"] = str(e)
json_response = json.dumps(wo_response)
return json_response
# -----------------------------------------------------------------
def validate_request(wo_request):
"""
Validate JSON workorder request
"""
try:
json.loads(wo_request)
except ValueError as e:
logger.error("Invalid JSON format found for workorder - %s", e)
return False
return True
# -----------------------------------------------------------------
def create_json_worker(enclave_data, config):
"""
Create JSON worker object which gets saved in KvStorage
"""
worker_type_data = dict()
worker_type_data["verificationKey"] = enclave_data.verifying_key
worker_type_data["extendedMeasurements"] = \
enclave_data.extended_measurements
worker_type_data["proofDataType"] = enclave_data.proof_data_type
worker_type_data["proofData"] = enclave_data.proof_data
worker_type_data["encryptionKey"] = enclave_data.encryption_key
worker_type_data["encryptionKeySignature"] = \
enclave_data.encryption_key_signature
worker_info = dict()
worker_info["workerType"] = WorkerType.TEE_SGX.value
worker_info["organizationId"] = \
config.get("WorkerConfig")["OrganizationId"]
worker_info["applicationTypeId"] = \
config.get("WorkerConfig")["ApplicationTypeId"]
details_info = dict()
details_info["workOrderSyncUri"] = \
config.get("WorkerConfig")["WorkOrderSyncUri"]
details_info["workOrderAsyncUri"] = \
config.get("WorkerConfig")["WorkOrderAsyncUri"]
details_info["workOrderPullUri"] = \
config.get("WorkerConfig")["WorkOrderPullUri"]
details_info["workOrderNotifyUri"] = \
config.get("WorkerConfig")["WorkOrderNotifyUri"]
details_info["receiptInvocationUri"] = \
config.get("WorkerConfig")["ReceiptInvocationUri"]
details_info["workOrderInvocationAddress"] = config.get(
"WorkerConfig")["WorkOrderInvocationAddress"]
details_info["receiptInvocationAddress"] = config.get(
"WorkerConfig")["ReceiptInvocationAddress"]
details_info["fromAddress"] = config.get("WorkerConfig")["FromAddress"]
details_info["hashingAlgorithm"] = \
config.get("WorkerConfig")["HashingAlgorithm"]
details_info["signingAlgorithm"] = \
config.get("WorkerConfig")["SigningAlgorithm"]
details_info["keyEncryptionAlgorithm"] = \
config.get("WorkerConfig")["KeyEncryptionAlgorithm"]
details_info["dataEncryptionAlgorithm"] = \
config.get("WorkerConfig")["DataEncryptionAlgorithm"]
details_info["workOrderPayloadFormats"] = \
config.get("WorkerConfig")["workOrderPayloadFormats"]
details_info["workerTypeData"] = worker_type_data
worker_info["details"] = details_info
worker_info["status"] = WorkerStatus.ACTIVE.value
# JSON serialize worker_info
json_worker_info = json.dumps(worker_info)
logger.info("JSON serialized worker info is %s", json_worker_info)
return json_worker_info
# -----------------------------------------------------------------
def start_enclave_manager(config):
"""
Instantiate KvStorage, Execute boot flow and run time flow
"""
global enclave_data
if config.get("KvStorage") is None:
logger.error("Kv Storage path is missing")
sys.exit(-1)
try:
logger.debug("initialize the enclave")
# Extended measurements is a list of enclave basename and
# enclave measurement
extended_measurements = \
enclave_helper.initialize_enclave(config.get("EnclaveModule"))
except Exception as e:
logger.exception("failed to initialize enclave; %s", str(e))
sys.exit(-1)
logger.info("creating a new enclave")
enclave_signup_data = create_enclave_signup_data()
logger.info("initialize enclave_manager")
enclave_manager = EnclaveManager(
config, enclave_signup_data, extended_measurements)
logger.info("Enclave manager started")
try:
kv_helper = connector.open(config['KvStorage']['remote_url'])
except Exception as err:
logger.error("Failed to open KV storage interface; " +
"exiting SGX Enclave manager: {err}")
sys.exit(-1)
try:
logger.info("--------------- Starting Boot time flow ----------------")
enclave_manager.manager_on_boot(kv_helper)
logger.info("--------------- Boot time flow Complete ----------------")
except Exception as err:
logger.error("Failed to execute boot time flow; " +
"exiting SGX Enclave manager: {err}")
exit(1)
try:
sleep_interval = int(config["EnclaveManager"]["sleep_interval"])
except Exception as err:
logger.error("Failed to get sleep interval from config file. " +
"Setting sleep interval to 10 seconds: %s", str(err))
sleep_interval = 10
try:
while True:
# Poll KV storage for new work-order requests and process
enclave_manager.process_work_orders(kv_helper)
logger.info("Enclave manager sleeping for %d secs", sleep_interval)
time.sleep(sleep_interval)
except Exception as inst:
logger.error("Error while processing work-order; " +
"shutting down enclave manager")
logger.error("Exception: {} args {} details {}".format(type(inst),
inst.args, inst))
exit(1)
TCFHOME = os.environ.get("TCF_HOME", "../../../../")
# -----------------------------------------------------------------
# -----------------------------------------------------------------
def parse_command_line(config, args):
"""
Parse command line arguments
"""
# global consensus_file_name
parser = argparse.ArgumentParser()
parser.add_argument(
"--logfile",
help="Name of the log file, __screen__ for standard output", type=str)
parser.add_argument("--loglevel", help="Logging leve", type=str)
parser.add_argument(
"--lmdb_url",
help="DB url to connect to lmdb", type=str)
options = parser.parse_args(args)
if config.get("Logging") is None:
config["Logging"] = {
"LogFile": "__screen__",
"LogLevel": "INFO"
}
if options.logfile:
config["Logging"]["LogFile"] = options.logfile
if options.loglevel:
config["Logging"]["LogLevel"] = options.loglevel.upper()
if options.lmdb_url:
config["KvStorage"]["remote_url"] = options.lmdb_url
# -----------------------------------------------------------------
def main(args=None):
import config.config as pconfig
import utility.logger as plogger
# parse out the configuration file first
conffiles = ["tcs_config.toml"]
confpaths = [".", TCFHOME + "/" + "config"]
parser = argparse.ArgumentParser()
parser.add_argument("--config", help="configuration file", nargs="+")
parser.add_argument("--config-dir", help="configuration folder", nargs="+")
(options, remainder) = parser.parse_known_args(args)
if options.config:
conffiles = options.config
if options.config_dir:
confpaths = options.config_dir
try:
config = pconfig.parse_configuration_files(conffiles, confpaths)
json.dumps(config, indent=4)
except pconfig.ConfigurationException as e:
logger.error(str(e))
sys.exit(-1)
plogger.setup_loggers(config.get("Logging", {}))
sys.stdout = plogger.stream_to_logger(
logging.getLogger("STDOUT"), logging.DEBUG)
sys.stderr = plogger.stream_to_logger(
logging.getLogger("STDERR"), logging.WARN)
parse_command_line(config, remainder)
logger.info("Starting Enclave manager")
start_enclave_manager(config)
main()
|
the-stack_0_8611 | from functools import reduce
from sys import *
import numpy as np
import random as r
import socket
import struct
import subprocess as sp
import threading
from threading import Thread
import ast
import time
import datetime as dt
import os
import psutil
from netifaces import interfaces, ifaddresses, AF_INET
import paho.mqtt.client as mqtt
import smtplib
import config
import paramiko
import argparse
import pickle
import logging
current_path = os.path.dirname(os.path.abspath(__file__))
os.chdir(current_path)
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s:%(levelname)s:%(name)s:%(message)s')
_tasks = {'t1': {'wcet': 3, 'period': 20, 'deadline': 15},
't2': {'wcet': 1, 'period': 5, 'deadline': 4},
't3': {'wcet': 2, 'period': 10, 'deadline': 8},
't4': {'wcet': 1, 'period': 10, 'deadline': 9},
't5': {'wcet': 3, 'period': 15, 'deadline': 12}
}
# mat = {'p0': ['cpu', 'mem', 'storage']}
_need = {
't1': [7, 4, 3],
't2': [1, 2, 2],
't3': [6, 0, 0],
't4': [0, 1, 1],
't5': [4, 3, 1]
}
allocation = {
't1': [0, 1, 0],
't2': [2, 0, 0],
't3': [3, 0, 2],
't4': [2, 1, 1],
't5': [0, 0, 2]
}
_cpu = [] # cpu plot list
prev_t = 0 # variable for cpu util
_off_mec = 0 # used to keep a count of tasks offloaded from local mec to another mec
_off_cloud = 0 # used to keep a count of tasks offloaded to cloud
_loc = 0 # used to keep a count of tasks executed locally
_inward_mec = 0 # used to keep a count of tasks offloaded from another mec to local mec
deadlock = [1] # keeps count of how many deadlock is resolved
memory = []
mec_waiting_time = {} # {ip : [moving (waiting time + rtt)]}
mec_rtt = {} # {ip: [RTT]}
offload_register = {} # {task: host_ip} to keep track of tasks sent to mec for offload
reoffload_list = [[], {}] # [[task_list],{wait_time}] => records that’s re-offloaded to mec to execute.
discovering = 0 # if discovering == 0 update host
test = []
_time = []
_pos = 0
received_task_queue = [] # [[(task_list,wait_time), host_ip], ....]
thread_record = []
_port_ = 64000
cloud_register = {} # ={client_id:client_ip} keeps address of task offloaded to cloud
cloud_port = 63000
received_time = []
task_record = {} # keeps record of task reoffloaded
task_id = 0 # id for each task reoffloaded
shared_resource_lock = threading.Lock()
t_track = 1
def ping(host):
cmd = [f'ping -c 1 {host}']
output = str(sp.check_output(cmd, shell=True), 'utf-8').split('\n')
try:
value = float(output[-2].split('=')[-1].split('/')[0])
except ValueError:
value = None
return value
def discovering_group():
global sock1
multicast_group = '224.3.29.71'
server_address = ('', 10000)
# Create the socket
sock1 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Bind to the server address
sock1.bind(server_address)
# Tell the operating system to add the socket to the multicast group
# on all interfaces.
group = socket.inet_aton(multicast_group)
mreq = struct.pack('4sL', group, socket.INADDR_ANY)
sock1.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
def offloading_group():
global sock2
multicast_group = '224.5.5.55'
server_address = ('', 20000)
# Create the socket
sock2 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Bind to the server address
sock2.bind(server_address)
# Tell the operating system to add the socket to the multicast group
# on all interfaces.
group = socket.inet_aton(multicast_group)
mreq = struct.pack('4sL', group, socket.INADDR_ANY)
sock2.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
def ip_address():
try:
# cmd = ['ifconfig eth1 | grep inet | cut -d ":" -f 2 | cut -d " " -f 1']
cmd = ['ifconfig ens4 | grep inet | head -n 1 | cut -d "t" -f 2 | cut -d " " -f 2']
address = str(sp.check_output(cmd, shell=True), 'utf-8')[0:-1]
if len(address.strip().split('.')) == 4:
return address.strip()
else:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
return s.getsockname()[0]
except Exception as e:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
return s.getsockname()[0]
def _memory():
global memory
memory.append(round(my_algo.memory_percent(), 4))
def m_cpu():
global prev_t
# get cpu
next_t = psutil.cpu_percent(percpu=False)
delta = abs(prev_t - next_t)
prev_t = next_t
_cpu.append(round(delta, 4))
def get_mec_rtts():
for i in mec_rtt:
mec_rtt[i].append(get_rtt(i))
def generate_results():
_memory()
m_cpu()
get_mec_rtts()
def host_ip_set():
global ip_set
ip_set = set()
for ifaceName in interfaces():
addresses = [i['addr'] for i in ifaddresses(ifaceName).setdefault(AF_INET, [{'addr': 'No IP addr'}])]
ip_set.add(', '.join(addresses))
def get_time():
_time_ = []
d = str(dt.datetime.utcnow()).split()
_time_ += d[0].split('-')
g = d[1].split('.')
_time_ += g[0].split(':')
_time_.append(g[1])
return _time_
def get_rtt(host):
rtt = ping(host)
if rtt:
return round(rtt, 4)
else:
return get_rtt(host)
def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
def _lcm(a, b):
return int(a * b / gcd(a, b))
def lcm(_list):
return reduce(_lcm, _list)
def gosh_dist(_range):
return ((23 ** r.randrange(1, 1331)) % r.randrange(1, 1777)) % _range
def on_connect(connect_client, userdata, flags, rc):
# logger.info("Connected with Code :" +str(rc))
# Subscribe Topic from here
connect_client.subscribe(node_id)
# Callback Function on Receiving the Subscribed Topic/Message
def on_message(message_client, userdata, msg):
global run
data = str(msg.payload, 'utf-8')
if data[0] == 'c': # receive from cloud
received_task = data[2:]
# send_client({received_task: get_time()}, cloud_register[received_task.split('.')[2]])
if received_task in task_record:
del task_record[received_task]
received_task = '.'.join(received_task.split('.')[:-1])
_client.publish(topic=received_task.split('.')[2], payload=str({received_task: get_time() + ['cloud']}), )
cooperate['cloud'] += 1
count_task_sent(received_task)
elif data[0] == 't': # receive from client
received_task = ast.literal_eval(data[2:])
received_task_queue.append(received_task)
received_time.append(time.time())
elif data.strip() == 'stop': # stop {hostname: ip}
logger.info('sending stop alert')
run = 0
def connect_to_broker(stop):
global _client
username = 'mec'
password = 'password'
broker_port_no = 1883
_client = mqtt.Client()
_client.on_connect = on_connect
_client.on_message = on_message
_client.username_pw_set(username, password)
_client.connect(broker_ip, broker_port_no, 60)
_client.loop_start()
while True:
if stop():
_client.loop_stop()
_client.disconnect()
logger.info('broker loop terminated')
break
def task_time_map(seq, process):
exe_seq = []
capacity_sum = 0
for job in process:
capacity_sum += process[job]['wcet']
while capacity_sum > 0:
for job in seq:
if process[job]['wcet'] > 0:
exe_seq.append(job)
process[job]['wcet'] -= 1
capacity_sum -= 1
return exe_seq
def load_tasks():
period_list = [tasks[i]['period'] for i in tasks]
lcm_period = lcm(period_list)
# insert idle task
s_task = {**tasks, 'idle': {'wcet': lcm_period, 'period': lcm_period + 1}}
return lcm_period, s_task
total_received_task = 0
def scheduler(_lcm_, s_tasks): # RMS algorithm
global total_received_task
queue = list(s_tasks.keys()) # initialize task queue
schedule = []
rms = []
curr = '' # current task
prev = '' # previous task
tmp = {}
for task in s_tasks.keys():
tmp[task] = {} # temporary data for each task
tmp[task]['deadline'] = s_tasks[task]['period']
tmp[task]['executed'] = 0
# start scheduling...
# proceed by one timestamp to handle preemption
for _time_ in range(_lcm_):
# insert new tasks into the queue
for t in tmp.keys():
if _time_ == tmp[t]['deadline']:
if s_tasks[t]['wcet'] > tmp[t]['executed']:
# logger.info('Scheduling Failed at %d' % time)
exit(1)
else:
tmp[t]['deadline'] += s_tasks[t]['period']
tmp[t]['executed'] = 0
queue.append(t)
# select next task to be scheduled
_min_ = _lcm_ * 2
for task in queue:
if tmp[task]['deadline'] < _min_:
_min_ = tmp[task]['deadline']
curr = task
tmp[curr]['executed'] += 1
# logger.info(time, queue, curr)
# dequeue the execution-completed task
if tmp[curr]['executed'] == s_tasks[curr]['wcet']:
for i in range(len(queue)):
if curr == queue[i]:
del queue[i]
break
# record to the schedule trace
if prev != curr:
if prev in queue and prev != 'idle': # previous task is preempted..
s = schedule.pop()
schedule.append([s[0], s[1], '*'])
rms.append(s[1])
schedule.append([_time_, curr])
if curr != 'idle':
rms.append(curr)
prev = curr
process = {task: {'wcet': tasks[task]['wcet']} for task in tasks}
rms = task_time_map(seq=rms, process=process)
total_received_task += len(rms)
return rms
# generate execution sequence with wait_die
def wait_die(processes, avail, n_need, allocat):
global deadlock
offload = []
# To store execution sequence
exec_seq = []
# Make a copy of available resources
work = [0] * len(processes)
# While all processes are not finished
# or system is not in safe state.
while 'w' or 0 in work:
if 0 in work:
ind = work.index(0)
i = processes[ind]
elif 'w' in work:
# logger.info('wk: ', work)
ind = work.index('w')
i = processes[ind]
else:
break
# logger.info('comparing| process: ', i, n_need[i], 'work: ', avail)
if not (False in list(np.greater_equal(avail, n_need[i]))):
exec_seq.append(i)
avail = np.add(avail, allocat[i])
work[ind] = 1
# logger.info('added: ', exec_seq)
else:
a = list(set(processes) - set(exec_seq) - set(offload))
n = {}
for j in a:
n[j] = sum(allocat[j])
_max = max(n, key=n.get)
# logger.info('work: ', work, 'need: ', n_need[_max])
if processes.index(_max) > processes.index(i): # if true, i is older
# if process is already waiting then offload process
if work[ind] == 'w':
offload.append(i)
avail = np.array(avail) + np.array(allocat[i])
work[processes.index(i)] = 1
# logger.info('offload reentry: ', i, offload)
else:
# wait put process to waiting
work[processes.index(i)] = 'w'
# logger.info('waiting: ', i)
else:
# abort i
offload.append(i)
avail = np.array(avail) + np.array(allocat[i])
work[processes.index(i)] = 1
# logger.info('offload: ', i)
if len(offload) > 0:
logger.info(f'offloading tasks: {offload}')
cooperative_mec(offload)
deadlock[0] += 1
logger.info(f'Execution seq: {exec_seq}')
return exec_seq
def get_exec_seq(pro):
# Number of processes
p = len(pro)
processes = ['{}_{}'.format(pro[i], i) for i in range(p)]
# Available instances of resources
avail = [6, 5, 5]
n_need = {i: _need[i[:2]] for i in processes}
# logger.info('need', n_need)
# Resources allocated to processes
allot = {i: allocation[i[:2]] for i in processes}
# return execution sequence
return wait_die(processes, avail, n_need, allot)
def calc_wait_time(list_seq):
pre = 0
time_dic = {}
for i in list_seq:
j = i.split('_')[0]
time_dic[i] = round(t_time[j][0] + pre, 3)
pre += t_time[j][0]
# waiting time = total waiting time ÷ 2 average waiting time might be too tight
w_send = round(time_dic[list(time_dic.keys())[-1]] / 2, 3)
send_message('wt {} {}'.format(ip_address(), str(w_send))) # Broadcasting waiting time to cooperative MECs
return time_dic
def compare_local_mec(list_seq):
time_compare_dict = {i: t_time[i.split('_')[0]][1] > list_seq[i] for i in list_seq}
logger.info(f'local vs MEC comparison: {time_compare_dict}')
execute_mec = []
execute_locally = []
for i in time_compare_dict:
if time_compare_dict[i]:
execute_locally.append(i)
else:
execute_mec.append(i)
return execute_mec, execute_locally
def calculate_mov_avg(ma1, a1):
if ma1 in mec_waiting_time:
_count = len(mec_waiting_time[ma1])
avg1 = mec_waiting_time[ma1][-1]
else:
_count = 0
avg1 = 0
_count += 1
avg1 = ((_count - 1) * avg1 + a1) / _count
# ma1.append(avg1) #cumulative average formula
# μ_n=((n-1) μ_(n-1) + x_n)/n
return round(avg1, 4)
def send_message(mg):
_multicast_group = ('224.3.29.71', 10000)
try:
# Send data to the multicast group
if mg == 'hello':
smg = mg + ' ' + str([get_hostname(), ip_address()])
sock1.sendto(str.encode(smg), _multicast_group)
logger.info('\nHello message sent')
else:
sock1.sendto(str.encode(mg), _multicast_group)
except Exception as e:
logger.info(str(e))
def get_hostname():
cmd = ['cat /etc/hostname']
hostname = str(sp.check_output(cmd, shell=True), 'utf-8')[0:-1]
return hostname
def receive_message(stop): # used for multi-cast message exchange among MEC
global hosts
while True:
if stop():
logger.info('Stopped: receive_message()')
break
else:
data, address = sock1.recvfrom(1024)
_d = data.decode()
if _d[:5] == 'hello':
_data = ast.literal_eval(_d[6:])
hosts[_data[0]] = _data[1]
if _data[1] != host_ip:
mec_rtt[_data[1]] = []
elif (_d[:6] == 'update') and (discovering == 0):
hosts = ast.literal_eval(_d[7:])
# logger.info('received: ', hosts)
for i in hosts:
if i != host_ip:
mec_rtt[i] = []
elif _d[:2] == 'wt':
split_data = _d.split()
if split_data[1] != host_ip:
w_time = calculate_mov_avg(split_data[1], float(split_data[2]) + get_rtt(
address[0])) # calcuate moving average of mec wait time => w_time = wait time + rtt
if split_data[1] in mec_waiting_time:
mec_waiting_time[split_data[1]].append(w_time)
else:
mec_waiting_time[split_data[1]] = [w_time]
def mec_comparison():
# returns min average waiting for all mecs
if len(mec_waiting_time) == 0:
return 0
min_mec = {i: mec_waiting_time[i][-1] for i in mec_waiting_time}
min_wt = min(min_mec, key=min_mec.get)
return min_wt
def cooperative_mec(mec_list):
global _off_cloud
global _off_mec
global task_id, task_record
for i in mec_list:
_host = mec_comparison()
if _host == 0:
# send_cloud([i.split('_')[0], t_time[i.split('_')[0]][0]]) # [task_id,exec_time]
_send_task = f"{i.split('_')[0]}.{task_id}"
_client.publish(cloud_ip, str([_send_task, t_time[i.split('_')[0]][0]]), )
task_record[_send_task] = 'cloud'
task_id += 1
_off_cloud += 1
# cloud_register[i.split('_')[0].split('.')[2]] = send_back_host
logger.info('\n=========SENDING {} TO CLOUD==========='.format(i))
else:
j = i.split('_')[0]
_max = np.array([6, 5, 5])
send = 'false'
if not (False in list(np.greater_equal(_max, _need[j[:2]]))):
send = 'true'
# CHECK IF THE MINIMUM MEC WAIT TIME IS LESS THAN LATENCY
if mec_waiting_time[_host][-1] < t_time[j][1] and send == 'true':
_send_task = f"{j}.{task_id}"
send_offloaded_task_mec('{} {} {}'.format('ex', mec_id(_host), [_send_task, t_time[j][0]]))
task_record[_send_task] = 'mec'
task_id += 1
_off_mec += 1
# SENDS TASK TO MEC FOR EXECUTION
w_send = mec_waiting_time[_host][-1] + 0.001
mec_waiting_time[_host].append(w_send) # adds a new average waiting time
logger.info('\n======SENDING {} TO MEC {}========='.format(i, _host))
elif send == 'true' and (get_rtt(_host) < get_rtt(cloud_ip)):
_send_task = f"{j}.{task_id}"
send_offloaded_task_mec('{} {} {}'.format('ex', mec_id(_host), [_send_task, t_time[j][0]]))
task_record[_send_task] = 'mec'
task_id += 1
_off_mec += 1
# SENDS TASK TO MEC FOR EXECUTION
w_send = mec_waiting_time[_host][-1] + 0.001
mec_waiting_time[_host].append(w_send) # adds a new average waiting time
logger.info('\n======SENDING {} TO MEC {}========='.format(i, _host))
else:
_send_task = f"{j}.{task_id}"
_client.publish(cloud_ip, str([_send_task, t_time[j][0]]), )
task_record[_send_task] = 'cloud'
task_id += 1
_off_cloud += 1
# send_cloud([j, t_time[j][0]]) # # [task_id,exec_time]
# cloud_register[j.split('.')[2]] = send_back_host
logger.info('\n=========SENDING {} TO CLOUD==========='.format(i))
outward_mec = 0
offload_check = [0, 0]
def execute_re_offloaded_task(offloaded_task):
global outward_mec, offload_check
exec_list = get_exec_seq(offloaded_task[0])
outward_mec += len(exec_list)
for i in offloaded_task[0]: # i = 't1.1.2.3*1_3'
j = i.split('_')[0]
time.sleep(offloaded_task[1][j] / 2)
# logger.info('j task: ', j)
send_offloaded_task_mec('{} {}'.format(j.split('.')[1], i.split('*')[0]))
clients_record = {}
def count_task_sent(task):
global clients_record
c_id = task.split('.')[2]
if c_id in clients_record:
clients_record[c_id] += 1
else:
clients_record[c_id] = 1
def execute(local):
logger.info(f'\nExecuting :{local}')
for i in local:
j = i.split('_')[0]
_t = t_time[j][0] / 2
time.sleep(_t)
logger.info('#{}'.format(local.index(i) + 1) + f' Executed: {i}')
_client.publish(j.split('.')[2], str({j: get_time() + ['local']}), )
count_task_sent(j)
logger.info('============== EXECUTION DONE ===============')
cooperate = {'mec': 0, 'cloud': 0}
def receive_offloaded_task_mec(stop): # run as a thread
global _inward_mec
global t_track
while True:
if stop():
logger.info('Stopped: receive_offloaded_task_mec()')
break
else:
data, address = sock2.recvfrom(1024)
if len(data.decode()) > 0:
da = data.decode().split(' ')
if (address[0] not in ip_set) and (da[0] == node_id): # send back to client
# send_client({da[1]: get_time()}, offload_register[da[1]]) # send back to client
if da[1] in task_record:
del task_record[da[1]]
task_new = '.'.join(da[1].split('.')[:-1])
_client.publish(da[1].split('.')[2], str({task_new: get_time() + ['mec']}), )
count_task_sent(da[1])
cooperate['mec'] += 1
else:
logger.info('*' * 30 + f'\n{da[1]} Not in Task Record\n' + '*' * 30)
elif (address[0] not in ip_set) and (da[0] == 'ex') and (da[1] == node_id):
_received = ast.literal_eval(da[2] + da[3])
shared_resource_lock.acquire()
task = _received[0] + '*{}'.format(t_track)
reoffload_list[0].append(task)
reoffload_list[1][task] = _received[1]
shared_resource_lock.release()
t_track += 1
_inward_mec += 1
def call_execute_re_offload(stop):
global reoffload_list, outward_mec
global offload_check
while True:
if stop():
logger.info('Stopped: call_execute_re_offload()')
break
else:
if len(reoffload_list[0]) == 1:
t = reoffload_list[0][-1]
time.sleep(reoffload_list[1][t] / 2)
shared_resource_lock.acquire()
reoffload_list[0].remove(t)
del reoffload_list[1][t]
shared_resource_lock.release()
send_offloaded_task_mec('{} {}'.format(t.split('.')[1], t.split('*')[0]))
outward_mec += 1
offload_check[0] += 1
elif len(reoffload_list[0]) > 1:
o = reoffload_list.copy()
offload_check[1] += len(o)
execute_re_offloaded_task(o)
for i in o[0]:
shared_resource_lock.acquire()
reoffload_list[0].remove(i)
del reoffload_list[1][i]
shared_resource_lock.release()
def send_email(msg, send_path):
try:
server = smtplib.SMTP_SSL('smtp.gmail.com')
server.ehlo()
server.login(config.email_address, config.password)
subject = 'Deadlock results rms+wait-die {} {}'.format(get_hostname(), send_path)
# msg = 'Attendance done for {}'.format(_timer)
_message = 'Subject: {}\n\n{}\n\n SENT BY RIHANNA \n\n'.format(subject, msg)
server.sendmail(config.email_address, config.send_email, _message)
server.quit()
logger.info("Email sent!")
except Exception as e:
logger.info(str(e))
def send_offloaded_task_mec(msg):
_multicast_group = ('224.5.5.55', 20000)
try:
sock2.sendto(str.encode(msg), _multicast_group)
except Exception as e:
logger.info(str(e))
def mec_id(client_ip):
_id = client_ip.split('.')[-1]
if len(_id) == 1:
return '00' + _id
elif len(_id) == 2:
return '0' + _id
else:
return _id
def send_result(host_, data):
try:
c = paramiko.SSHClient()
un = 'mec'
pw = 'password'
port = 22
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(host_, port, un, pw)
for i in data:
cmd = ('echo "{}" >> /home/mec/result/data.py'.format(i)) # task share : host ip task
stdin, stdout, stderr = c.exec_command(cmd)
except Exception as e:
logger.info(str(e))
def save_and_send(send_path):
_id_ = get_hostname()[-1]
result = f"\nwt{_id_}_10_{mec_no} = {mec_waiting_time} " \
f"\nrtt{_id_}_10_{mec_no} = {mec_rtt} \ncpu{_id_}_10_{mec_no} = {_cpu} " \
f"\noff_mec{_id_}_10_{mec_no} = {_off_mec} " \
f"\noff_cloud{_id_}_10_{mec_no} = {_off_cloud} " \
f"\ninward_mec{_id_}_10_{mec_no} = {_inward_mec}" \
f"\nloc{_id_}_10_{mec_no} = {_loc} " \
f"\ndeadlock{_id_}_10_{mec_no} = {deadlock} \nmemory{_id_}_10_{mec_no} = {memory}" \
f"\ntask_received{_id_}_10_{mec_no} = {total_received_task} \nsent_t{_id_}_10_{mec_no} = {clients_record}" \
f"\ncooperate{_id_}_10_{mec_no} = {cooperate} \ntask_record{_id_}_10_{mec_no} = {task_record}" \
f"\noutward_mec{_id_}_10_{mec_no} = {outward_mec}" \
f"\noffload_check{_id_}_10_{mec_no} = {offload_check}"
list_result = [
f"\nwt{_id_}_10_{mec_no} = {mec_waiting_time} ",
f"\nrtt{_id_}_10_{mec_no} = {mec_rtt} \ncpu{_id_}_10_{mec_no} = {_cpu} ",
f"\noff_mec{_id_}_10_{mec_no} = {_off_mec} \noff_cloud{_id_}_10_{mec_no} = {_off_cloud} ",
f"\ninward_mec{_id_}_10_{mec_no} = {_inward_mec}",
f"\nloc{_id_}_10_{mec_no} = {_loc} ",
f"\ndeadlock{_id_}_10_{mec_no} = {deadlock} \nmemory{_id_}_10_{mec_no} = {memory}",
f"\ntask_received{_id_}_10_{mec_no} = {total_received_task} \nsent_t{_id_}_10_{mec_no} = {clients_record}",
f"\ncooperate{_id_}_10_{mec_no} = {cooperate} \ntask_record{_id_}_10_{mec_no} = {task_record} "
f"\noutward_mec{_id_}_10_{mec_no} = {outward_mec}",
f"\noffload_check{_id_}_10_{mec_no} = {offload_check}"
]
file_ = open(f'{_id_}_10_{mec_no}datap.py', 'w')
for i in list_result:
file_.write(i)
file_.close()
cmd = f'mv {_id_}_10_{mec_no}datap.py {send_path}'
os.system(cmd)
send_email(result, send_path)
if len(task_record) > 0:
for _task_ in task_record:
task_new = '.'.join(_task_.split('.')[:-1])
_client.publish(task_new.split('.')[2], str({task_new: get_time() + [task_record[_task_]]}), )
run = 1 # tell agents child when to stop
def start_loop():
global _loc
global tasks
global t_time
global node_id
global run
logger.info('\n============* WELCOME TO THE DEADLOCK EMULATION PROGRAM *=============\n')
node_id = mec_id(ip_address())
# logger.info('node id: ', node_id)
func_to_thread = [receive_message, receive_offloaded_task_mec, call_execute_re_offload, connect_to_broker]
threads_ = []
stop = False
for i in func_to_thread:
threads_.append(Thread(target=i, args=(lambda: stop,)))
threads_[-1].daemon = True
threads_[-1].start()
logger.info('algorithm is starting....')
logger.info('========= Waiting for tasks ==========')
while run == 1:
try:
if len(received_task_queue) > 0:
info = received_task_queue.pop(0)
tasks, t_time = info
logger.info(f'EDF List of Processes: {tasks}\n')
logger.info('\n========= Running Deadlock Algorithm ===========')
lcm_result, task_load = load_tasks()
list_seq = get_exec_seq(scheduler(lcm_result, task_load))
if len(list_seq) > 0: # do only when there is a task in safe sequence
wait_list = calc_wait_time(list_seq)
logger.info(f'\nWaiting Time List: {wait_list}')
compare_result = compare_local_mec(wait_list)
logger.info(f'\nExecute Locally: {compare_result[1]}')
_loc += len(compare_result[1]) # total number of tasks to be executed locally
logger.info(f'\nExecute in MEC: {compare_result[0]}')
logger.info('\nSending to cooperative platform')
if len(compare_result[0]) > 0:
cooperative_mec(compare_result[0])
execute(compare_result[1])
generate_results()
_time_ = dt.datetime.now()
else:
send_message(str('wt {} 0.0'.format(ip_address())))
time.sleep(.5)
except KeyboardInterrupt:
logger.info('\nProgramme Terminated')
stop = False
cmd = 'kill -9 {}'.format(os.getpid())
os.system(cmd)
break
logger.info('algo stopped!')
def run_me(hosts_, mec_no_, cloud_ip_, send_path, broker_ip_): # call this from agent
global discovering
global hosts
global mec_no
global host_ip
global cloud_ip
global my_algo
global broker_ip
logger.info(f'mec ip: {ip_address()}')
my_algo = psutil.Process()
discovering_group()
offloading_group()
host_ip_set()
hosts = hosts_
mec_no = mec_no_
cloud_ip = cloud_ip_
broker_ip = broker_ip_
host_ip = ip_address()
logger.info(f'MEC Details: {hosts}')
discovering = 1
time.sleep(2)
for host in hosts:
if hosts[host] != host_ip:
mec_rtt[hosts[host]] = []
start_loop()
logger.info('saving data')
save_and_send(send_path)
logger.info('send alert to control')
time.sleep(r.uniform(1, 10))
_client.publish('control/control', pickle.dumps(['stop', ip_address()]))
logger.info('Terminating process')
cmd = 'kill -9 {}'.format(os.getpid())
os.system(cmd)
def main():
# (hosts_, mec_no_, cloud_ip_, send_path, broker_ip_) , (--hosts, --mec_no_, --cloud_ip, --s_path, --b_ip)
parser = argparse.ArgumentParser()
parser.add_argument('--hosts', type=str, help="{hostname: 'ip address', ...} of all mec")
parser.add_argument('--mec_no', type=int, default=1.0, help='Number of MEC nodes')
parser.add_argument('--cloud_ip', type=str, help="cloud ip address")
parser.add_argument('--s_path', type=str, default='/home/mec/result/python', help='Path to send result to')
parser.add_argument('--b_ip', type=str, help='Broker ip address')
args = parser.parse_args()
# h_hosts = ast.literal_eval(args.hosts)
l_host, l_len = args.hosts.split('_'), len(args.hosts.split('_'))
h_hosts = dict(zip(l_host[:l_len//2], l_host[l_len//2:]))
f_name = os.path.basename(__file__).split('/')[-1].split('.')[0]
tim = dt.datetime.now().strftime("%a_%H%M")
name = f'logs/{f_name}_{tim}_{args.mec_no}'
file_handler = logging.FileHandler(name)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
logger.info('Process Started')
run_me(hosts_=h_hosts, mec_no_=args.mec_no, cloud_ip_=args.cloud_ip, send_path=args.s_path, broker_ip_=args.b_ip)
if __name__ == '__main__':
main() |
the-stack_0_8613 | # -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys
sys.path.insert(0, os.path.abspath(os.pardir))
import graphviz
# -- Project information -----------------------------------------------------
project = 'graphviz'
copyright = '2013-2020, Sebastian Bank'
author = 'Sebastian Bank'
# The short X.Y version
version = '0.14.2.dev0'
# The full version, including alpha/beta/rc tags
release = version
# -- General configuration ---------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.autosummary',
'sphinx.ext.intersphinx',
'sphinx.ext.napoleon',
'sphinx.ext.viewcode',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The master toctree document.
master_doc = 'index'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path .
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
if not on_rtd:
import sphinx_rtd_theme
html_theme = 'sphinx_rtd_theme'
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Custom sidebar templates, must be a dictionary that maps document names
# to template names.
#
# The default sidebars (for documents that don't match any pattern) are
# defined by theme itself. Builtin themes are using these templates by
# default: ``['localtoc.html', 'relations.html', 'sourcelink.html',
# 'searchbox.html']``.
#
# html_sidebars = {}
# -- Options for HTMLHelp output ---------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'graphvizdoc'
# -- Options for LaTeX output ------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'graphviz.tex', 'graphviz Documentation',
'Sebastian Bank', 'manual'),
]
# -- Options for manual page output ------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'graphviz', 'graphviz Documentation',
[author], 1)
]
# -- Options for Texinfo output ----------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'graphviz', 'graphviz Documentation',
author, 'graphviz', 'One line description of project.',
'Miscellaneous'),
]
# -- Extension configuration -------------------------------------------------
# -- Options for intersphinx extension ---------------------------------------
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {
'py': ('https://docs.python.org/2', None),
'py3': ('https://docs.python.org/3', None),
}
# monkey patch, see https://github.com/sphinx-doc/sphinx/issues/2044
from sphinx.ext.autodoc import ClassLevelDocumenter, InstanceAttributeDocumenter
def add_directive_header(self, sig):
ClassLevelDocumenter.add_directive_header(self, sig)
InstanceAttributeDocumenter.add_directive_header = add_directive_header
|
the-stack_0_8614 | # *********************************************************************************
# REopt, Copyright (c) 2019-2020, Alliance for Sustainable Energy, LLC.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice, this list
# of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright notice, this
# list of conditions and the following disclaimer in the documentation and/or other
# materials provided with the distribution.
#
# Neither the name of the copyright holder nor the names of its contributors may be
# used to endorse or promote products derived from this software without specific
# prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
# OF THE POSSIBILITY OF SUCH DAMAGE.
# *********************************************************************************
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('reo', '0039_loadprofilemodel_gen_energy_at_start_of_outage_kwh'),
]
operations = [
migrations.RenameField(
model_name='loadprofilemodel',
old_name='gen_energy_at_start_of_outage_kwh',
new_name='fuel_avail_before_outage_pct',
),
]
|
the-stack_0_8615 | # Copyright (C) 2021, Mindee.
# This program is licensed under the Apache License version 2.
# See LICENSE or go to <https://www.apache.org/licenses/LICENSE-2.0.txt> for full license details.
import json
import os
from typing import Any, Callable, List, Optional, Tuple
import numpy as np
from doctr.utils.geometry import fit_rbbox
from .datasets import AbstractDataset
__all__ = ["DetectionDataset"]
class DetectionDataset(AbstractDataset):
"""Implements a text detection dataset
Example::
>>> from doctr.datasets import DetectionDataset
>>> train_set = DetectionDataset(img_folder="/path/to/images", label_path="/path/to/labels.json")
>>> img, target = train_set[0]
Args:
img_folder: folder with all the images of the dataset
label_path: path to the annotations of each image
sample_transforms: composable transformations that will be applied to each image
rotated_bbox: whether polygons should be considered as rotated bounding box (instead of straight ones)
"""
def __init__(
self,
img_folder: str,
label_path: str,
sample_transforms: Optional[Callable[[Any], Any]] = None,
rotated_bbox: bool = False,
) -> None:
super().__init__(img_folder)
self.sample_transforms = sample_transforms
# File existence check
if not os.path.exists(label_path):
raise FileNotFoundError(f"unable to locate {label_path}")
with open(label_path, 'rb') as f:
labels = json.load(f)
self.data: List[Tuple[str, np.ndarray]] = []
for img_name, label in labels.items():
# File existence check
if not os.path.exists(os.path.join(self.root, img_name)):
raise FileNotFoundError(f"unable to locate {os.path.join(self.root, img_name)}")
polygons = np.asarray(label['polygons'])
if rotated_bbox:
# Switch to rotated rects
boxes = np.asarray([list(fit_rbbox(poly)) for poly in polygons])
else:
# Switch to xmin, ymin, xmax, ymax
boxes = np.concatenate((polygons.min(axis=1), polygons.max(axis=1)), axis=1)
self.data.append((img_name, np.asarray(boxes, dtype=np.float32)))
def __getitem__(
self,
index: int
) -> Tuple[Any, np.ndarray]:
img, boxes = self._read_sample(index)
h, w = self._get_img_shape(img)
if self.sample_transforms is not None:
img = self.sample_transforms(img)
# Boxes
boxes = boxes.copy()
boxes[..., [0, 2]] /= w
boxes[..., [1, 3]] /= h
boxes = boxes.clip(0, 1)
return img, boxes
|
the-stack_0_8616 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Dummy router supporting IGD."""
# Instructions:
# - Change `SOURCE``. When using IPv6, be sure to set the scope_id, the last value in the tuple.
# - Run this module.
# - Run upnp-client (change IP to your own IP):
# upnp-client call-action 'http://0.0.0.0:8000/device.xml' \
# WANCIC/GetTotalPacketsReceived
import asyncio
import logging
import time
import xml.etree.ElementTree as ET
from typing import Dict, Mapping, Sequence, Type
from async_upnp_client.client import UpnpRequester, UpnpStateVariable
from async_upnp_client.const import (
STATE_VARIABLE_TYPE_MAPPING,
DeviceInfo,
ServiceInfo,
StateVariableTypeInfo,
)
from .server import UpnpServerDevice, UpnpServerService, callable_action, run_server
logging.basicConfig(level=logging.DEBUG)
LOGGER = logging.getLogger("dummy_router")
LOGGER_SSDP_TRAFFIC = logging.getLogger("async_upnp_client.traffic")
LOGGER_SSDP_TRAFFIC.setLevel(logging.WARNING)
SOURCE = ("172.24.83.184", 0) # Your IP here!
# SOURCE = ("fe80::215:5dff:fe3e:6d23", 0, 0, 6) # Your IP here!
HTTP_PORT = 8000
class WANIPConnectionService(UpnpServerService):
"""WANIPConnection service."""
SERVICE_DEFINITION = ServiceInfo(
service_id="urn:upnp-org:serviceId:WANIPConnection1",
service_type="urn:schemas-upnp-org:service:WANIPConnection:1",
control_url="/upnp/control/WANIPConnection1",
event_sub_url="/upnp/event/WANIPConnection1",
scpd_url="/WANIPConnection_1.xml",
xml=ET.Element("server_service"),
)
STATE_VARIABLE_DEFINITIONS = {
"ExternalIPAddress": StateVariableTypeInfo(
data_type="string",
data_type_mapping=STATE_VARIABLE_TYPE_MAPPING["string"],
default_value="1.2.3.4",
allowed_value_range={},
allowed_values=None,
xml=ET.Element("server_stateVariable"),
),
"ConnectionStatus": StateVariableTypeInfo(
data_type="string",
data_type_mapping=STATE_VARIABLE_TYPE_MAPPING["string"],
default_value="Unconfigured",
allowed_value_range={},
allowed_values=[
"Unconfigured",
"Authenticating",
"Connecting",
"Connected",
"PendingDisconnect",
"Disconnecting",
"Disconnected",
],
xml=ET.Element("server_stateVariable"),
),
"LastConnectionError": StateVariableTypeInfo(
data_type="string",
data_type_mapping=STATE_VARIABLE_TYPE_MAPPING["string"],
default_value="ERROR_NONE",
allowed_value_range={},
allowed_values=[
"ERROR_NONE",
],
xml=ET.Element("server_stateVariable"),
),
"Uptime": StateVariableTypeInfo(
data_type="ui4",
data_type_mapping=STATE_VARIABLE_TYPE_MAPPING["ui4"],
default_value="0",
allowed_value_range={},
allowed_values=None,
xml=ET.Element("server_stateVariable"),
),
}
@callable_action(
name="GetStatusInfo",
in_args={},
out_args={
"NewConnectionStatus": "ConnectionStatus",
"NewLastConnectionError": "LastConnectionError",
"NewUptime": "Uptime",
},
)
async def get_status_info(self) -> Dict[str, UpnpStateVariable]:
"""Get status info."""
# from async_upnp_client.exceptions import UpnpActionError, UpnpActionErrorCode
# raise UpnpActionError(
# error_code=UpnpActionErrorCode.INVALID_ACTION, error_desc="Invalid action"
# )
return {
"NewConnectionStatus": self.state_variable("ConnectionStatus"),
"NewLastConnectionError": self.state_variable("LastConnectionError"),
"NewUptime": self.state_variable("Uptime"),
}
@callable_action(
name="GetExternalIPAddress",
in_args={},
out_args={
"NewExternalIPAddress": "ExternalIPAddress",
},
)
async def get_external_ip_address(self) -> Dict[str, UpnpStateVariable]:
"""Get external IP address."""
# from async_upnp_client.exceptions import UpnpActionError, UpnpActionErrorCode
# raise UpnpActionError(
# error_code=UpnpActionErrorCode.INVALID_ACTION, error_desc="Invalid action"
# )
return {
"NewExternalIPAddress": self.state_variable("ExternalIPAddress"),
}
class WanConnectionDevice(UpnpServerDevice):
"""WAN Connection device."""
DEVICE_DEFINITION = DeviceInfo(
device_type="urn:schemas-upnp-org:device:WANConnectionDevice:1",
friendly_name="Dummy Router WAN Connection Device",
manufacturer="Steven",
model_name="DummyRouter v1",
udn="uuid:51e00c19-c8f3-4b28-9ef1-7f562f204c82",
model_description="Dummy Router IGD",
model_number="v0.0.1",
serial_number="0000001",
url="/device.xml",
icons=[],
xml=ET.Element("server_device"),
)
EMBEDDED_DEVICES: Sequence[Type[UpnpServerDevice]] = []
SERVICES = [WANIPConnectionService]
def __init__(self, requester: UpnpRequester, base_uri: str) -> None:
"""Initialize."""
super().__init__(
requester=requester,
base_uri=base_uri,
)
class WANCommonInterfaceConfigService(UpnpServerService):
"""WANCommonInterfaceConfig service."""
SERVICE_DEFINITION = ServiceInfo(
service_id="urn:upnp-org:serviceId:WANCommonInterfaceConfig1",
service_type="urn:schemas-upnp-org:service:WANCommonInterfaceConfig:1",
control_url="/upnp/control/WANCommonInterfaceConfig1",
event_sub_url="/upnp/event/WANCommonInterfaceConfig1",
scpd_url="/WANCommonInterfaceConfig_1.xml",
xml=ET.Element("server_service"),
)
STATE_VARIABLE_DEFINITIONS = {
"TotalBytesReceived": StateVariableTypeInfo(
data_type="ui4",
data_type_mapping=STATE_VARIABLE_TYPE_MAPPING["ui4"],
default_value="0",
allowed_value_range={},
allowed_values=None,
xml=ET.Element("server_stateVariable"),
),
"TotalBytesSent": StateVariableTypeInfo(
data_type="ui4",
data_type_mapping=STATE_VARIABLE_TYPE_MAPPING["ui4"],
default_value="0",
allowed_value_range={},
allowed_values=None,
xml=ET.Element("server_stateVariable"),
),
"TotalPacketsReceived": StateVariableTypeInfo(
data_type="ui4",
data_type_mapping=STATE_VARIABLE_TYPE_MAPPING["ui4"],
default_value="0",
allowed_value_range={},
allowed_values=None,
xml=ET.Element("server_stateVariable"),
),
"TotalPacketsSent": StateVariableTypeInfo(
data_type="ui4",
data_type_mapping=STATE_VARIABLE_TYPE_MAPPING["ui4"],
default_value="0",
allowed_value_range={},
allowed_values=None,
xml=ET.Element("server_stateVariable"),
),
}
MAX_COUNTER = 2**32
def _update_bytes(self, state_var_name: str) -> None:
"""Update bytes state variable."""
new_bytes = int(time.time() * 1000) % self.MAX_COUNTER
self.state_variable(state_var_name).value = new_bytes
def _update_packets(self, state_var_name: str) -> None:
"""Update state variable values."""
new_packets = int(time.time()) % self.MAX_COUNTER
self.state_variable(state_var_name).value = new_packets
self.state_variable(state_var_name).value = new_packets
@callable_action(
name="GetTotalBytesReceived",
in_args={},
out_args={
"NewTotalBytesReceived": "TotalBytesReceived",
},
)
async def get_total_bytes_received(self) -> Dict[str, UpnpStateVariable]:
"""Get total bytes received."""
self._update_bytes("TotalBytesReceived")
return {
"NewTotalBytesReceived": self.state_variable("TotalBytesReceived"),
}
@callable_action(
name="GetTotalBytesSent",
in_args={},
out_args={
"NewTotalBytesSent": "TotalBytesSent",
},
)
async def get_total_bytes_sent(self) -> Dict[str, UpnpStateVariable]:
"""Get total bytes sent."""
self._update_bytes("TotalBytesSent")
return {
"NewTotalBytesSent": self.state_variable("TotalBytesSent"),
}
@callable_action(
name="GetTotalPacketsReceived",
in_args={},
out_args={
"NewTotalPacketsReceived": "TotalPacketsReceived",
},
)
async def get_total_packets_received(self) -> Dict[str, UpnpStateVariable]:
"""Get total packets received."""
self._update_packets("TotalPacketsReceived")
return {
"NewTotalPacketsReceived": self.state_variable("TotalPacketsReceived"),
}
@callable_action(
name="GetTotalPacketsSent",
in_args={},
out_args={
"NewTotalPacketsSent": "TotalPacketsSent",
},
)
async def get_total_packets_sent(self) -> Dict[str, UpnpStateVariable]:
"""Get total packets sent."""
self._update_packets("TotalPacketsSent")
return {
"NewTotalPacketsSent": self.state_variable("TotalPacketsSent"),
}
class WanDevice(UpnpServerDevice):
"""WAN device."""
DEVICE_DEFINITION = DeviceInfo(
device_type="urn:schemas-upnp-org:device:WANDevice:1",
friendly_name="Dummy Router WAN Device",
manufacturer="Steven",
model_name="DummyRouter v1",
udn="uuid:51e00c19-c8f3-4b28-9ef1-7f562f204c81",
model_description="Dummy Router IGD",
model_number="v0.0.1",
serial_number="0000001",
url="/device.xml",
icons=[],
xml=ET.Element("server_device"),
)
EMBEDDED_DEVICES = [WanConnectionDevice]
SERVICES = [WANCommonInterfaceConfigService]
def __init__(self, requester: UpnpRequester, base_uri: str) -> None:
"""Initialize."""
super().__init__(
requester=requester,
base_uri=base_uri,
)
class Layer3ForwardingService(UpnpServerService):
"""Layer3Forwarding service."""
SERVICE_DEFINITION = ServiceInfo(
service_id="urn:upnp-org:serviceId:Layer3Forwarding1",
service_type="urn:schemas-upnp-org:service:Layer3Forwarding:1",
control_url="/upnp/control/Layer3Forwarding1",
event_sub_url="/upnp/event/Layer3Forwarding1",
scpd_url="/Layer3Forwarding_1.xml",
xml=ET.Element("server_service"),
)
STATE_VARIABLE_DEFINITIONS: Mapping[str, StateVariableTypeInfo] = {}
class IgdDevice(UpnpServerDevice):
"""IGD device."""
DEVICE_DEFINITION = DeviceInfo(
device_type="urn:schemas-upnp-org:device:InternetGatewayDevice:1",
friendly_name="Dummy Router",
manufacturer="Steven",
model_name="DummyRouter v1",
udn="uuid:51e00c19-c8f3-4b28-9ef1-7f562f204c80",
model_description="Dummy Router IGD",
model_number="v0.0.1",
serial_number="0000001",
url="/device.xml",
icons=[],
xml=ET.Element("server_device"),
)
EMBEDDED_DEVICES = [WanDevice]
SERVICES = [Layer3ForwardingService]
def __init__(self, requester: UpnpRequester, base_uri: str) -> None:
"""Initialize."""
super().__init__(
requester=requester,
base_uri=base_uri,
)
async def async_main() -> None:
"""Main."""
await run_server(SOURCE, HTTP_PORT, IgdDevice)
if __name__ == "__main__":
asyncio.run(async_main())
|
the-stack_0_8620 | from dagster_graphql.client.util import parse_raw_log_lines
from dagster_k8s.utils import (
get_pod_names_in_job,
retrieve_pod_logs,
wait_for_job,
wait_for_job_success,
)
from dagster import check
def wait_for_job_ready(job_name, namespace):
'''Wait for a dagster-k8s job to be ready
'''
check.str_param(job_name, 'job_name')
check.str_param(namespace, 'namespace')
wait_for_job(job_name=job_name, namespace=namespace)
def wait_for_job_and_get_logs(job_name, namespace):
'''Wait for a dagster-k8s job to complete, ensure it launched only one pod,
and then grab the logs from the pod it launched.
'''
check.str_param(job_name, 'job_name')
check.str_param(namespace, 'namespace')
wait_for_job_success(job_name, namespace=namespace)
pod_names = get_pod_names_in_job(job_name, namespace)
assert len(pod_names) == 1
pod_name = pod_names[0]
raw_logs = retrieve_pod_logs(pod_name, namespace=namespace)
return parse_raw_log_lines(raw_logs.split('\n'))
|
the-stack_0_8622 | # -*- coding: utf-8 -*-
#
# michael a.g. aïvázis
# orthologue
# (c) 1998-2022 all rights reserved
#
from .SI import meter
from .SI import kilo, centi, milli, micro, nano
#
# definitions of common length units
# data taken from Appendix F of Halliday, Resnick, Walker, "Fundamentals of Physics",
# fourth edition, John Willey and Sons, 1993
nanometer = nano * meter
micrometer = micro * meter
millimeter = milli * meter
centimeter = centi * meter
kilometer = kilo * meter
# aliases
m = meter
nm = nanometer
um = micrometer
micron = micrometer
mm = millimeter
cm = centimeter
km = kilometer
# British units
inch = 2.540 * centimeter
foot = 12 * inch
yard = 3 * foot
mile = 5280 * foot
mil = 1e-3 * inch
fathom = 6 * foot
nautical_mile = 1852 * meter
# others
angstrom = 1e-10 * meter
fermi = 1e-15 * meter
astronomical_unit = 1.49598e11 * meter
light_year = 9.460e12 * kilometer
parsec = 3.084e13 * kilometer
# end of file
|
the-stack_0_8623 | #!/usr/bin/env python3
# Modules
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import GaussianNB, MultinomialNB
from sklearn.svm import SVC
import time
import torch
import torch.nn as nn
import torch.optim as optim
from xgboost import XGBClassifier
class NaiveBayes:
"""Naive Bayes classifier"""
def __init__(self):
self.categorical = 'object'
self.numerical = 'number'
def cat_num_split(self, feature):
# Split features into categorical and numberical types
feature_cat = feature.select_dtypes(include=self.categorical)
feature_num = feature.select_dtypes(include=self.numerical)
return feature_cat, feature_num
def train(self, train_cat, train_num, train_labels):
# Instantiate the classifiers
mnb = MultinomialNB()
gnb = GaussianNB()
# Train classifier
if train_cat.shape[1]:
mnb.fit(train_cat, train_labels)
if train_num.shape[1]:
gnb.fit(train_num, train_labels)
return mnb, gnb
def predict(self, feature_cat, feature_num, mnb, gnb):
# Predict labels
cat_pred = mnb.predict_proba(feature_cat) if feature_cat.shape[1] else 0
cat_pred *= feature_cat.shape[1]
num_pred = gnb.predict_proba(feature_num) if feature_num.shape[1] else 0
num_pred *= feature_num.shape[1]
return (cat_pred + num_pred).argmax(axis=1)
def __call__(self, train, test):
# Record start time
print('==============NAIVE BAYES==============')
start = time.time()
# Split train and test into categorical and numerical features
train_cat, train_num = self.cat_num_split(train.iloc[:, :-1])
test_cat, test_num = self.cat_num_split(test.iloc[:, :-1])
# Assign labels
train_labels = train.iloc[:, -1]
test_labels = test.iloc[:, -1]
# Train Gaussian and Multinomial classifiers
mnb, gnb = self.train(train_cat, train_num, train_labels)
# Predict train and test labels
train_pred = self.predict(train_cat, train_num, mnb, gnb)
test_pred = self.predict(test_cat, test_num, mnb, gnb)
# Print results
train_hit = (train_labels == train_pred).sum()
test_hit = (test_labels == test_pred).sum()
print('Train accuracy: %.2f%%'
% (100 * train_hit / len(train)))
print('Test accuracy: %.2f%%'
% (100 * test_hit / len(test)))
print('Time: %.1f seconds' % (time.time() - start))
print('')
class Logistic:
"""Logistic regression classifier"""
def __init__(self):
pass
def train(self, train):
# Instantiate the classifiers
mlr = LogisticRegression(solver='sag', max_iter=10000, n_jobs=-1,
multi_class='multinomial')
ovr = LogisticRegression(solver='sag', max_iter=10000, n_jobs=-1,
multi_class='ovr')
# Train classifier
mlr.fit(train.iloc[:, :-1], train.iloc[:, -1])
ovr.fit(train.iloc[:, :-1], train.iloc[:, -1])
return mlr, ovr
def predict(self, feature, mlr, ovr):
return mlr.predict(feature), ovr.predict(feature)
def __call__(self, train, test):
# Record start time
print('==========LOGISTIC REGRESSION==========')
start = time.time()
# Train Logistic regression classifiers
mlr, ovr = self.train(train)
# Predict train and test labels
train_pred_mlr, train_pred_ovr = self.predict(train.iloc[:, :-1], mlr, ovr)
test_pred_mlr, test_pred_ovr = self.predict(test.iloc[:, :-1], mlr, ovr)
# Print results
train_hit_mlr = (train.iloc[:, -1] == train_pred_mlr).sum()
train_hit_ovr = (train.iloc[:, -1] == train_pred_ovr).sum()
test_hit_mlr = (test.iloc[:, -1] == test_pred_mlr).sum()
test_hit_ovr = (test.iloc[:, -1] == test_pred_ovr).sum()
print('Train accuracy: %5.2f%% (Multinomial), %6.2f%% (One-vs-Rest)'
% (100 * train_hit_mlr / len(train), 100 * train_hit_ovr / len(train)))
print('Test accuracy: %5.2f%% (Multinomial), %6.2f%% (One-vs-Rest)'
% (100 * test_hit_mlr / len(test), 100 * test_hit_ovr / len(test)))
print('Time: %.1f seconds' % (time.time() - start))
print('')
class SVM:
"""Support Vector Machine classifier"""
def __init__(self):
pass
def train(self, train):
svc = SVC()
svc.fit(train.iloc[:, :-1], train.iloc[:, -1])
return svc
def predict(self, feature, svc):
return svc.predict(feature)
def __call__(self, train, test):
# Record start time
print('========SUPPORT VECTOR MACHINE=========')
start = time.time()
# Train support vector machine
svc = self.train(train)
# Predict train and test labels
train_pred = self.predict(train.iloc[:, :-1], svc)
test_pred = self.predict(test.iloc[:, :-1], svc)
# Print results
train_hit = (train.iloc[:, -1] == train_pred).sum()
test_hit = (test.iloc[:, -1] == test_pred).sum()
print('Train accuracy: %5.2f%% (Radial Basis Function)'
% (100 * train_hit / len(train)))
print('Test accuracy: %5.2f%% (Radial Basis Function)'
% (100 * test_hit / len(test)))
print('Time: %.1f seconds' % (time.time() - start))
print('')
class RandomForest:
"""Random Forest classifier"""
def __init__(self):
pass
def train(self, train, trees):
# Instantiate the classifiers
if trees == 1:
rfc = RandomForestClassifier(n_estimators=trees, n_jobs=-1, bootstrap=False)
else:
rfc = RandomForestClassifier(n_estimators=trees, n_jobs=-1, bootstrap=True)
# Train classifier
rfc.fit(train.iloc[:, :-1], train.iloc[:, -1])
return rfc
def predict(self, feature, rfc):
return rfc.predict(feature)
def __call__(self, train, test):
# Record start time
print('=============RANDOM FOREST=============')
start = time.time()
# Train Random Forest classifiers
rfc1 = self.train(train, 1)
rfc10 = self.train(train, 10)
rfc100 = self.train(train, 100)
# Predict train and test labels
train_pred_1 = self.predict(train.iloc[:, :-1], rfc1)
train_pred_10 = self.predict(train.iloc[:, :-1], rfc10)
train_pred_100 = self.predict(train.iloc[:, :-1], rfc100)
test_pred_1 = self.predict(test.iloc[:, :-1], rfc1)
test_pred_10 = self.predict(test.iloc[:, :-1], rfc10)
test_pred_100 = self.predict(test.iloc[:, :-1], rfc100)
# Print results
train_hit_1 = (train.iloc[:, -1] == train_pred_1).sum()
train_hit_10 = (train.iloc[:, -1] == train_pred_10).sum()
train_hit_100 = (train.iloc[:, -1] == train_pred_100).sum()
test_hit_1 = (test.iloc[:, -1] == test_pred_1).sum()
test_hit_10 = (test.iloc[:, -1] == test_pred_10).sum()
test_hit_100 = (test.iloc[:, -1] == test_pred_100).sum()
print('Train accuracy: %5.2f%% (1 Trees), %6.2f%% (10 Trees), %6.2f%% (100 Trees)'
% (100 * train_hit_1 / len(train),
100 * train_hit_10 / len(train),
100 * train_hit_100 / len(train)))
print('Test accuracy: %5.2f%% (1 Trees), %6.2f%% (10 Trees), %6.2f%% (100 Trees)'
% (100 * test_hit_1 / len(test),
100 * test_hit_10 / len(test),
100 * test_hit_100 / len(test)))
print('Time: %.1f seconds' % (time.time() - start))
print('')
class XGBoost:
"""XGBoost"""
def __init__(self):
pass
def train(self, train):
xgb = XGBClassifier(max_depth=3, n_estimators=100)
xgb.fit(train.iloc[:, :-1], train.iloc[:, -1])
return xgb
def predict(self, feature, xgb):
return xgb.predict(feature)
def __call__(self, train, test):
# Record start time
print('================XGBOOST================')
start = time.time()
# Train support vector machine
xgb = self.train(train)
# Predict train and test labels
train_pred = self.predict(train.iloc[:, :-1], xgb)
test_pred = self.predict(test.iloc[:, :-1], xgb)
# Print results
train_hit = (train.iloc[:, -1] == train_pred).sum()
test_hit = (test.iloc[:, -1] == test_pred).sum()
print('Train accuracy: %5.2f%% (Max Depth of 3, 100 Trees)'
% (100 * train_hit / len(train)))
print('Test accuracy: %5.2f%% (Max Depth of 3, 100 Trees)'
% (100 * test_hit / len(test)))
print('Time: %.1f seconds' % (time.time() - start))
print('')
class NeuralNet:
"""Neural network with a single hidden layer"""
def __init__(self):
self.hidden = 100
self.batch = 50
def train(self, train):
# Convert train dataset to tensor
feature = torch.from_numpy(train.iloc[:, :-1].values).float()
label = torch.from_numpy(train.iloc[:, -1].values).long()
# Initialize the neural network
net = nn.Sequential(nn.Linear(feature.shape[1], self.hidden),
nn.ReLU(),
nn.Linear(self.hidden, len(set(train.iloc[:, -1]))))
# Optimizer
optimizer = optim.Adam(net.parameters(), lr=0.01)
criterion = nn.CrossEntropyLoss()
# Train classifier
for i in range(10000):
permutation = np.random.choice(feature.shape[0], self.batch)
optimizer.zero_grad()
output = net(feature[permutation])
loss = criterion(output, label[permutation])
loss.backward()
optimizer.step()
return net
def predict(self, feature, net):
feature = torch.from_numpy(feature.values).float()
return net(feature)
def __call__(self, train, test):
# Record start time
print('============NEURAL NETWORK=============')
start = time.time()
# Train support vector machine
net = self.train(train)
# Predict train and test labels
train_pred = self.predict(train.iloc[:, :-1], net)
train_pred = train_pred.detach().numpy().argmax(axis=1)
test_pred = self.predict(test.iloc[:, :-1], net)
test_pred = test_pred.detach().numpy().argmax(axis=1)
# Print results
train_hit = (train.iloc[:, -1].values == train_pred).sum()
test_hit = (test.iloc[:, -1].values == test_pred).sum()
print('Train accuracy: %5.2f%% (Single Hidden Layer)'
% (100 * train_hit / len(train)))
print('Test accuracy: %5.2f%% (Single Hidden Layer)'
% (100 * test_hit / len(test)))
print('Time: %.1f seconds' % (time.time() - start))
print('')
|
the-stack_0_8625 | # coding: utf-8
#
# Copyright 2014 The Oppia 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 required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Unit tests for utils.py."""
from __future__ import annotations
import base64
import copy
import datetime
import os
import urllib
from core import feconf
from core import python_utils
from core import utils
from core.constants import constants
from core.tests import test_utils
from typing import Any, Dict, List
class UtilsTests(test_utils.GenericTestBase):
"""Test the core utility methods."""
def test_get_comma_sep_string_from_list(self) -> None:
"""Test get_comma_sep_string_from_list method."""
alist = ['a', 'b', 'c', 'd']
results = ['', 'a', 'a and b', 'a, b and c', 'a, b, c and d']
for i in range(len(alist) + 1):
comma_sep_string = utils.get_comma_sep_string_from_list(alist[:i])
self.assertEqual(comma_sep_string, results[i])
def test_to_ascii(self) -> None:
"""Test to_ascii method."""
parsed_str = utils.to_ascii('abc')
self.assertEqual(parsed_str, 'abc')
parsed_str = utils.to_ascii('¡Hola!')
self.assertEqual(parsed_str, 'Hola!')
parsed_str = utils.to_ascii(
u'Klüft skräms inför på fédéral électoral große')
self.assertEqual(
parsed_str, 'Kluft skrams infor pa federal electoral groe')
parsed_str = utils.to_ascii('')
self.assertEqual(parsed_str, '')
def test_yaml_dict_conversion(self) -> None:
"""Test yaml_from_dict and dict_from_yaml methods."""
test_dicts = [{}, {'a': 'b'}, {'a': 2}, {'a': ['b', 2, {'c': 3.5}]}]
for adict in test_dicts:
yaml_str = python_utils.yaml_from_dict(adict) # type: ignore[no-untyped-call]
yaml_dict = utils.dict_from_yaml(yaml_str)
self.assertEqual(adict, yaml_dict)
with self.assertRaisesRegex( # type: ignore[no-untyped-call]
utils.InvalidInputException,
'while parsing a flow node\n'
'expected the node content, but found \'<stream end>\'\n'):
yaml_str = utils.dict_from_yaml('{')
def test_recursively_remove_key_for_empty_dict(self) -> None:
"""Test recursively_remove_key method for an empty dict."""
d: Dict[str, Any] = {}
utils.recursively_remove_key(d, 'a')
self.assertEqual(d, {})
def test_recursively_remove_key_for_single_key_dict(self) -> None:
"""Test recursively_remove_key method for single key dict."""
d = {'a': 'b'}
utils.recursively_remove_key(d, 'a')
self.assertEqual(d, {})
def test_recursively_remove_key_for_multi_key_dict(self) -> None:
"""Test recursively_remove_key method for multi key dict."""
d = {'a': 'b', 'c': 'd'}
utils.recursively_remove_key(d, 'a')
self.assertEqual(d, {'c': 'd'})
def test_recursively_remove_key_for_dict_with_value_dict(self) -> None:
"""Test recursively_remove_key method for dict with a value dict."""
d = {'a': 'b', 'c': {'a': 'b'}}
utils.recursively_remove_key(d, 'a')
self.assertEqual(d, {'c': {}})
def test_recursively_remove_key_for_list(self) -> None:
"""Test recursively_remove_key method for list."""
l = ['a', 'b', {'c': 'd'}]
utils.recursively_remove_key(l, 'c')
self.assertEqual(l, ['a', 'b', {}])
def test_camelcase_to_hyphenated(self) -> None:
"""Test camelcase_to_hyphenated method."""
test_cases = [
('AbcDef', 'abc-def'),
('Abc', 'abc'),
('abc_def', 'abc_def'),
('Abc012Def345', 'abc012-def345'),
('abcDef', 'abc-def'),
]
for test_case in test_cases:
self.assertEqual(
utils.camelcase_to_hyphenated(test_case[0]), test_case[1])
def test_camelcase_to_snakecase(self) -> None:
"""Test camelcase_to_hyphenated method."""
test_cases = [
('AbcDef', 'abc_def'),
('Abc', 'abc'),
('abc_def', 'abc_def'),
('Abc012Def345', 'abc012_def345'),
('abcDef', 'abc_def'),
('abc-def', 'abc-def'),
]
for test_case in test_cases:
self.assertEqual(
utils.camelcase_to_snakecase(test_case[0]), test_case[1])
def test_set_url_query_parameter(self) -> None:
"""Test set_url_query_parameter method."""
self.assertEqual(
utils.set_url_query_parameter('http://www.test.com', 'a', 'b'),
'http://www.test.com?a=b'
)
self.assertEqual(
utils.set_url_query_parameter('http://www.test.com?a=b', 'c', 'd'),
'http://www.test.com?a=b&c=d'
)
self.assertEqual(
utils.set_url_query_parameter(
'http://test.com?a=b', 'redirectUrl', 'http://redirect.com'),
'http://test.com?a=b&redirectUrl=http%3A%2F%2Fredirect.com'
)
with self.assertRaisesRegex( # type: ignore[no-untyped-call]
Exception, 'URL query parameter name must be a string'
):
utils.set_url_query_parameter('http://test.com?a=b', None, 'value') # type: ignore[arg-type]
def test_convert_to_hash(self) -> None:
"""Test convert_to_hash() method."""
orig_string = 'name_to_convert'
full_hash = utils.convert_to_hash(orig_string, 28)
abbreviated_hash = utils.convert_to_hash(orig_string, 5)
self.assertEqual(len(full_hash), 28)
self.assertEqual(len(abbreviated_hash), 5)
self.assertEqual(full_hash[:5], abbreviated_hash)
self.assertTrue(full_hash.isalnum())
def test_vfs_construct_path(self) -> None:
"""Test vfs_construct_path method."""
p = utils.vfs_construct_path('a', 'b', 'c')
self.assertEqual(p, 'a/b/c')
p = utils.vfs_construct_path('a/', '/b', 'c')
self.assertEqual(p, '/b/c')
p = utils.vfs_construct_path('a/', 'b', 'c')
self.assertEqual(p, 'a/b/c')
p = utils.vfs_construct_path('a', '/b', 'c')
self.assertEqual(p, '/b/c')
p = utils.vfs_construct_path('/a', 'b/')
self.assertEqual(p, '/a/b/')
def test_vfs_normpath(self) -> None:
p = utils.vfs_normpath('/foo/../bar')
self.assertEqual(p, '/bar')
p = utils.vfs_normpath('foo//bar')
self.assertEqual(p, 'foo/bar')
p = utils.vfs_normpath('foo/bar/..')
self.assertEqual(p, 'foo')
p = utils.vfs_normpath('/foo//bar//baz//')
self.assertEqual(p, '/foo/bar/baz')
p = utils.vfs_normpath('')
self.assertEqual(p, '.')
p = utils.vfs_normpath('//foo//bar//baz//')
self.assertEqual(p, '//foo/bar/baz')
def test_capitalize_string(self) -> None:
test_data: List[List[str]] = [
['', ''],
['a', 'A'],
['A', 'A'],
['1', '1'],
['lowercase', 'Lowercase'],
['UPPERCASE', 'UPPERCASE'],
['Partially', 'Partially'],
['miDdle', 'MiDdle'],
['2be', '2be'],
]
for datum in test_data:
self.assertEqual(utils.capitalize_string(datum[0]), datum[1])
def test_generate_random_string(self) -> None:
# Generate a random string of length 12.
random_string = utils.generate_random_string(12)
self.assertIsInstance(random_string, str)
self.assertEqual(len(random_string), 12)
def test_convert_png_data_url_to_binary_with_incorrect_prefix(self) -> None:
with self.assertRaisesRegex( # type: ignore[no-untyped-call]
Exception, 'The given string does not represent a PNG data URL'
):
utils.convert_png_data_url_to_binary('data:image/jpg;base64,')
def test_get_thumbnail_icon_url_for_category(self) -> None:
self.assertEqual(
utils.get_thumbnail_icon_url_for_category('Architecture'),
'/subjects/Architecture.svg')
self.assertEqual(
utils.get_thumbnail_icon_url_for_category('Graph Theory'),
'/subjects/GraphTheory.svg')
self.assertEqual(
utils.get_thumbnail_icon_url_for_category('Nonexistent'),
'/subjects/Lightbulb.svg')
def test_are_datetimes_close(self) -> None:
initial_time = datetime.datetime(2016, 12, 1, 0, 0, 0)
with self.swap(feconf, 'PROXIMAL_TIMEDELTA_SECS', 2):
self.assertTrue(utils.are_datetimes_close(
datetime.datetime(2016, 12, 1, 0, 0, 1),
initial_time))
self.assertFalse(utils.are_datetimes_close(
datetime.datetime(2016, 12, 1, 0, 0, 3),
initial_time))
def test_conversion_between_string_and_naive_datetime_object(self) -> None:
"""Tests to make sure converting a naive datetime object to a string and
back doesn't alter the naive datetime object data.
"""
now = datetime.datetime.utcnow()
self.assertEqual(
utils.convert_string_to_naive_datetime_object(
utils.convert_naive_datetime_to_string(now)),
now)
def test_datetime_conversion_to_string_returns_correct_format(self) -> None:
initial_time = datetime.datetime(2016, 12, 1, 1, 2, 3)
self.assertEqual(
utils.convert_naive_datetime_to_string(initial_time),
'12/01/2016, 01:02:03:000000')
def test_string_to_datetime_conversion_returns_correct_datetime(
self
) -> None:
time_string = '12/01/2016, 01:02:03:000000'
initial_time = datetime.datetime(2016, 12, 1, 1, 2, 3)
self.assertEqual(
utils.convert_string_to_naive_datetime_object(time_string),
initial_time)
def test_create_string_from_largest_unit_in_timedelta_raises_for_zero_diff(
self
) -> None:
timedelta_object = datetime.timedelta(days=0)
with self.assertRaisesRegex( # type: ignore[no-untyped-call]
Exception, 'Expected a positive timedelta, received: %s.' % (
timedelta_object.total_seconds())):
utils.create_string_from_largest_unit_in_timedelta(timedelta_object)
def test_create_string_from_largest_unit_in_timedelta_raises_for_neg_diff(
self
) -> None:
timedelta_object = datetime.timedelta(days=-40)
with self.assertRaisesRegex( # type: ignore[no-untyped-call]
Exception, 'Expected a positive timedelta, received: %s.' % (
timedelta_object.total_seconds())):
utils.create_string_from_largest_unit_in_timedelta(timedelta_object)
def test_create_string_from_largest_unit_in_timedelta_returns_days(
self
) -> None:
timedelta_object = datetime.timedelta(
days=4, hours=1, minutes=1, seconds=1)
time_string = (
utils.create_string_from_largest_unit_in_timedelta(timedelta_object)
)
self.assertEqual(time_string, '4 days')
def test_create_string_from_largest_unit_in_timedelta_returns_a_day(
self
) -> None:
timedelta_object = datetime.timedelta(
days=1, hours=1, minutes=1, seconds=1)
time_string = (
utils.create_string_from_largest_unit_in_timedelta(timedelta_object)
)
self.assertEqual(time_string, '1 day')
def test_create_string_from_largest_unit_in_timedelta_returns_hours(
self
) -> None:
timedelta_object = datetime.timedelta(
days=0, hours=2, minutes=1, seconds=1)
time_string = (
utils.create_string_from_largest_unit_in_timedelta(timedelta_object)
)
self.assertEqual(time_string, '2 hours')
def test_create_string_from_largest_unit_in_timedelta_returns_an_hour(
self
) -> None:
timedelta_object = datetime.timedelta(
days=0, hours=1, minutes=1, seconds=1)
time_string = (
utils.create_string_from_largest_unit_in_timedelta(timedelta_object)
)
self.assertEqual(time_string, '1 hour')
def test_create_string_from_largest_unit_in_timedelta_returns_minutes(
self
) -> None:
timedelta_object = datetime.timedelta(
days=0, hours=0, minutes=4, seconds=1)
time_string = (
utils.create_string_from_largest_unit_in_timedelta(timedelta_object)
)
self.assertEqual(time_string, '4 minutes')
def test_create_string_from_largest_unit_in_timedelta_returns_a_minute(
self
) -> None:
timedelta_object = datetime.timedelta(
days=0, hours=0, minutes=1, seconds=12)
time_string = (
utils.create_string_from_largest_unit_in_timedelta(timedelta_object)
)
self.assertEqual(time_string, '1 minute')
def test_create_string_from_largest_unit_in_timedelta_returns_a_min_for_min(
self
) -> None:
timedelta_object = datetime.timedelta(
days=0, hours=0, minutes=1, seconds=0)
time_string = (
utils.create_string_from_largest_unit_in_timedelta(timedelta_object)
)
self.assertEqual(time_string, '1 minute')
def test_create_string_from_largest_unit_in_timedelta_returns_minute_if_sec(
self
) -> None:
timedelta_object = datetime.timedelta(
days=0, hours=0, minutes=0, seconds=1)
time_string = (
utils.create_string_from_largest_unit_in_timedelta(timedelta_object)
)
self.assertEqual(time_string, '1 minute')
def test_create_string_from_largest_unit_in_timedelta_returns_a_min_if_msec(
self
) -> None:
timedelta_object = datetime.timedelta(
days=0, hours=0, minutes=0, seconds=0, milliseconds=1)
time_string = (
utils.create_string_from_largest_unit_in_timedelta(timedelta_object)
)
self.assertEqual(time_string, '1 minute')
def test_get_hashable_value(self) -> None:
json1 = ['foo', 'bar', {'baz': 3}]
json2 = ['fee', {'fie': ['foe', 'fum']}]
json1_deepcopy = copy.deepcopy(json1)
json2_deepcopy = copy.deepcopy(json2)
test_set = {utils.get_hashable_value(json1)}
self.assertIn(utils.get_hashable_value(json1_deepcopy), test_set)
test_set.add(utils.get_hashable_value(json2))
self.assertEqual(
test_set, {
utils.get_hashable_value(json1_deepcopy),
utils.get_hashable_value(json2_deepcopy),
})
def test_is_supported_audio_language_code(self) -> None:
self.assertTrue(utils.is_supported_audio_language_code('hi-en'))
self.assertFalse(utils.is_supported_audio_language_code('unknown'))
def test_is_valid_language_code(self) -> None:
self.assertTrue(utils.is_valid_language_code('en'))
self.assertFalse(utils.is_valid_language_code('unknown'))
def test_require_valid_name(self) -> None:
name = 'name'
utils.require_valid_name(name, 'name_type')
invalid_name = 0
with self.assertRaisesRegex(Exception, '0 must be a string.'): # type: ignore[no-untyped-call]
# Type ignore is used below because we are providing integer
# argument instead of string for invalid_name for testing purposes.
utils.require_valid_name(invalid_name, 'name_type') # type: ignore[arg-type]
def test_require_valid_meta_tag_content(self) -> None:
meta_tag_content = 'name'
utils.require_valid_meta_tag_content(meta_tag_content)
non_string_meta_tag_content = 0
invalid_type_error = (
'Expected meta tag content to be a string, received 0')
with self.assertRaisesRegex(Exception, invalid_type_error): # type: ignore[no-untyped-call]
utils.require_valid_meta_tag_content(non_string_meta_tag_content) # type: ignore[arg-type]
lengthy_meta_tag_content = 'a' * 200
max_length_error = (
'Meta tag content should not be longer than %s characters.'
% constants.MAX_CHARS_IN_META_TAG_CONTENT)
with self.assertRaisesRegex(Exception, max_length_error): # type: ignore[no-untyped-call]
utils.require_valid_meta_tag_content(lengthy_meta_tag_content)
def test_require_valid_page_title_fragment_for_web(self) -> None:
page_title_fragment_for_web = 'name'
utils.require_valid_page_title_fragment_for_web(
page_title_fragment_for_web)
non_string_page_title_fragment_for_web = 0
invalid_type_error = (
'Expected page title fragment to be a string, received 0')
with self.assertRaisesRegex(Exception, invalid_type_error): # type: ignore[no-untyped-call]
utils.require_valid_page_title_fragment_for_web(
non_string_page_title_fragment_for_web) # type: ignore[arg-type]
lengthy_page_title_fragment_for_web = 'a' * 60
max_length_error = (
'Page title fragment should not be longer than %s characters.'
% constants.MAX_CHARS_IN_PAGE_TITLE_FRAGMENT_FOR_WEB)
with self.assertRaisesRegex(Exception, max_length_error): # type: ignore[no-untyped-call]
utils.require_valid_page_title_fragment_for_web(
lengthy_page_title_fragment_for_web)
def test_require_valid_url_fragment(self) -> None:
name = 'name'
utils.require_valid_url_fragment(name, 'name-type', 20)
name_with_spaces = 'name with spaces'
name_with_spaces_expected_error = (
'name-type field contains invalid characters. Only '
'lowercase words separated by hyphens are allowed. '
'Received name with spaces.')
with self.assertRaisesRegex( # type: ignore[no-untyped-call]
Exception, name_with_spaces_expected_error):
utils.require_valid_url_fragment(
name_with_spaces, 'name-type', 20)
name_in_caps = 'NAME'
name_in_caps_expected_error = (
'name-type field contains invalid characters. Only '
'lowercase words separated by hyphens are allowed. Received NAME.')
with self.assertRaisesRegex(Exception, name_in_caps_expected_error): # type: ignore[no-untyped-call]
utils.require_valid_url_fragment(
name_in_caps, 'name-type', 20)
name_with_numbers = 'nam3'
name_with_numbers_expected_error = (
'name-type field contains invalid characters. Only '
'lowercase words separated by hyphens are allowed. Received nam3.')
with self.assertRaisesRegex( # type: ignore[no-untyped-call]
Exception, name_with_numbers_expected_error):
utils.require_valid_url_fragment(
name_with_numbers, 'name-type', 20)
long_name = 'a-really-really-really-lengthy-name'
long_name_expected_error = (
'name-type field should not exceed 10 characters, '
'received %s' % long_name)
with self.assertRaisesRegex(Exception, long_name_expected_error): # type: ignore[no-untyped-call]
utils.require_valid_url_fragment(
long_name, 'name-type', 10)
empty_name = ''
empty_name_expected_error = 'name-type field should not be empty.'
with self.assertRaisesRegex(Exception, empty_name_expected_error): # type: ignore[no-untyped-call]
utils.require_valid_url_fragment(empty_name, 'name-type', 20)
non_string_name = 0
non_string_name_expected_error = (
'name-type field must be a string. Received 0.')
with self.assertRaisesRegex(Exception, non_string_name_expected_error): # type: ignore[no-untyped-call]
utils.require_valid_url_fragment(non_string_name, 'name-type', 20) # type: ignore[arg-type]
def test_validate_convert_to_hash(self) -> None:
with self.assertRaisesRegex( # type: ignore[no-untyped-call]
Exception, 'Expected string, received 1 of type %s' % type(1)):
utils.convert_to_hash(1, 10) # type: ignore[arg-type]
def test_convert_png_to_data_url_with_non_png_image_raises_error(
self
) -> None:
favicon_filepath = os.path.join(
self.get_static_asset_filepath(), 'assets', 'favicon.ico') # type: ignore[no-untyped-call]
with self.assertRaisesRegex( # type: ignore[no-untyped-call]
Exception, 'The given string does not represent a PNG image.'):
utils.convert_png_to_data_url(favicon_filepath)
def test_get_exploration_components_from_dir_with_invalid_path_raises_error(
self
) -> None:
with self.assertRaisesRegex( # type: ignore[no-untyped-call]
Exception,
'Found invalid non-asset file .+'
'There should only be a single non-asset file, and it should have '
'a .yaml suffix.'
):
utils.get_exploration_components_from_dir('core/tests/load_tests')
with self.assertRaisesRegex( # type: ignore[no-untyped-call]
Exception, 'The only directory in . should be assets/'):
utils.get_exploration_components_from_dir('.')
def test_get_exploration_components_from_dir_with_multiple_yaml_files(
self
) -> None:
with self.assertRaisesRegex( # type: ignore[no-untyped-call]
Exception,
'More than one non-asset file specified for '
'core/tests/data/dummy_assets/assets'):
utils.get_exploration_components_from_dir(
'core/tests/data/dummy_assets/assets/')
def test_get_exploration_components_from_dir_with_no_yaml_file(
self
) -> None:
with self.assertRaisesRegex( # type: ignore[no-untyped-call]
Exception,
'No yaml file specifed for core/tests/data/dummy_assets'):
utils.get_exploration_components_from_dir(
'core/tests/data/dummy_assets/')
def test_get_asset_dir_prefix_with_prod_mode(self) -> None:
with self.swap(constants, 'DEV_MODE', False):
self.assertEqual(utils.get_asset_dir_prefix(), '/build')
def test_base64_from_int(self) -> None:
base64_number = utils.base64_from_int(108)
self.assertEqual(base64.b64decode(base64_number), b'[108]')
def test_get_supported_audio_language_description_with_invalid_code(
self
) -> None:
valid_language_code = 'en'
expected_language_description = 'English'
self.assertEqual(
utils.get_supported_audio_language_description(valid_language_code),
expected_language_description)
invalid_language_code = 'invalid_code'
with self.assertRaisesRegex( # type: ignore[no-untyped-call]
Exception, 'Unsupported audio language code: invalid_code'):
utils.get_supported_audio_language_description(
invalid_language_code)
def test_is_user_id_valid(self) -> None:
self.assertTrue(
utils.is_user_id_valid(
feconf.SYSTEM_COMMITTER_ID, allow_system_user_id=True))
self.assertTrue(
utils.is_user_id_valid(
feconf.MIGRATION_BOT_USER_ID, allow_system_user_id=True))
self.assertTrue(
utils.is_user_id_valid(
feconf.SUGGESTION_BOT_USER_ID, allow_system_user_id=True))
self.assertTrue(
utils.is_user_id_valid(
'pid_%s' % ('a' * 32), allow_pseudonymous_id=True))
self.assertTrue(
utils.is_user_id_valid('uid_%s' % ('a' * 32)))
self.assertFalse(
utils.is_user_id_valid('pid_%s' % ('a' * 32)))
self.assertFalse(
utils.is_user_id_valid('uid_%s%s' % ('a' * 31, 'A')))
self.assertFalse(
utils.is_user_id_valid('uid_%s' % ('a' * 31)))
self.assertFalse(utils.is_user_id_valid('a' * 36))
def test_is_pseudonymous_id(self) -> None:
self.assertTrue(utils.is_pseudonymous_id('pid_' + 'a' * 32))
self.assertFalse(utils.is_pseudonymous_id('uid_' + 'a' * 32))
self.assertFalse(utils.is_pseudonymous_id('uid_' + 'a' * 31 + 'A'))
self.assertFalse(utils.is_pseudonymous_id('uid_' + 'a' * 31))
self.assertFalse(utils.is_pseudonymous_id('a' * 36))
def test_snake_case_to_camel_case(self) -> None:
camel_case_str1 = utils.snake_case_to_camel_case('user_id_number')
camel_case_str2 = utils.snake_case_to_camel_case('hello_world')
camel_case_str3 = utils.snake_case_to_camel_case('test1')
self.assertEqual(camel_case_str1, 'userIdNumber')
self.assertEqual(camel_case_str2, 'helloWorld')
self.assertEqual(camel_case_str3, 'test1')
def _assert_valid_thumbnail_filename(
self,
expected_error_substring: str,
thumbnail_filename: str
) -> None:
"""Helper method for test_require_valid_thumbnail_filename."""
with self.assertRaisesRegex( # type: ignore[no-untyped-call]
utils.ValidationError, expected_error_substring):
utils.require_valid_thumbnail_filename(
thumbnail_filename)
def test_require_valid_thumbnail_filename(self) -> None:
"""Test thumbnail filename validation."""
self._assert_valid_thumbnail_filename(
'Expected thumbnail filename to be a string, received 10', 10) # type: ignore[arg-type]
self._assert_valid_thumbnail_filename(
'Thumbnail filename should not start with a dot.', '.name')
self._assert_valid_thumbnail_filename(
'Thumbnail filename should not include slashes or '
'consecutive dot characters.', 'file/name')
self._assert_valid_thumbnail_filename(
'Thumbnail filename should not include slashes or '
'consecutive dot characters.', 'file..name')
self._assert_valid_thumbnail_filename(
'Thumbnail filename should include an extension.', 'name')
self._assert_valid_thumbnail_filename(
'Expected a filename ending in svg, received name.jpg', 'name.jpg')
filename = 'filename.svg'
utils.require_valid_thumbnail_filename(filename)
def _assert_valid_image_filename(
self, expected_error_substring: str, image_filename: str
) -> None:
"""Helper method for test_require_valid_image_filename."""
with self.assertRaisesRegex( # type: ignore[no-untyped-call]
utils.ValidationError, expected_error_substring):
utils.require_valid_image_filename(image_filename)
def test_require_valid_image_filename(self) -> None:
"""Test image filename validation."""
self._assert_valid_image_filename(
'Expected image filename to be a string, received 10', 10) # type: ignore[arg-type]
self._assert_valid_image_filename(
'Image filename should not start with a dot.', '.name')
self._assert_valid_image_filename(
'Image filename should not include slashes or '
'consecutive dot characters.', 'file/name')
self._assert_valid_image_filename(
'Image filename should not include slashes or '
'consecutive dot characters.', 'file..name')
self._assert_valid_image_filename(
'Image filename should include an extension.', 'name')
filename = 'filename.svg'
utils.require_valid_image_filename(filename)
def test_get_time_in_millisecs(self) -> None:
dt = datetime.datetime(2020, 6, 15)
msecs = utils.get_time_in_millisecs(dt)
self.assertEqual(
dt,
datetime.datetime.fromtimestamp(
python_utils.divide(msecs, 1000.0))) # type: ignore[no-untyped-call]
def test_get_time_in_millisecs_with_complicated_time(self) -> None:
dt = datetime.datetime(2020, 6, 15, 5, 18, 23, microsecond=123456)
msecs = utils.get_time_in_millisecs(dt)
self.assertEqual(
dt,
datetime.datetime.fromtimestamp(
python_utils.divide(msecs, 1000.0))) # type: ignore[no-untyped-call]
def test_grouper(self) -> None:
self.assertEqual(
[list(g) for g in utils.grouper(range(7), 3)],
[[0, 1, 2], [3, 4, 5], [6, None, None]])
# Returns an iterable of iterables, so we need to combine them into
# strings for easier comparison.
self.assertEqual(
[''.join(g) for g in utils.grouper('ABCDEFG', 3, fillvalue='x')],
['ABC', 'DEF', 'Gxx'])
def test_partition(self) -> None:
is_even = lambda n: (n % 2) == 0
evens, odds = (
utils.partition([10, 8, 1, 5, 6, 4, 3, 7], predicate=is_even))
self.assertEqual(list(evens), [10, 8, 6, 4])
self.assertEqual(list(odds), [1, 5, 3, 7])
def test_enumerated_partition(self) -> None:
logs = ['ERROR: foo', 'INFO: bar', 'INFO: fee', 'ERROR: fie']
is_error = lambda msg: msg.startswith('ERROR: ')
errors, others = (
utils.partition(logs, predicate=is_error, enumerated=True))
self.assertEqual(list(errors), [(0, 'ERROR: foo'), (3, 'ERROR: fie')])
self.assertEqual(list(others), [(1, 'INFO: bar'), (2, 'INFO: fee')])
def test_convert_png_data_url_to_binary(self) -> None:
image_data_url = '%s%s' % (
utils.PNG_DATA_URL_PREFIX,
urllib.parse.quote(base64.b64encode(b'test123'))
)
self.assertEqual(
utils.convert_png_data_url_to_binary(image_data_url), b'test123')
def test_convert_png_data_url_to_binary_raises_if_prefix_is_missing(
self
) -> None:
image_data_url = urllib.parse.quote(base64.b64encode(b'test123'))
self.assertRaisesRegex( # type: ignore[no-untyped-call]
Exception, 'The given string does not represent a PNG data URL.',
lambda: utils.convert_png_data_url_to_binary(image_data_url))
def test_quoted_string(self) -> None:
self.assertEqual(utils.quoted('a"b\'c'), '"a\\"b\'c"')
def test_is_base64_encoded(self) -> None:
image = '<svg><path d="%s" /></svg>' % (
'M150 0 L75 200 L225 200 Z ' * 1000)
self.assertFalse(utils.is_base64_encoded(image))
self.assertFalse(utils.is_base64_encoded('hello'))
self.assertTrue(utils.is_base64_encoded(
base64.b64encode(b'hello').decode('utf-8'))
)
def test_url_open(self) -> None:
response = utils.url_open('http://www.google.com')
self.assertEqual(response.getcode(), 200) # type: ignore[attr-defined]
self.assertEqual(
response.url, 'http://www.google.com') # type: ignore[attr-defined]
|
the-stack_0_8626 | import tensorflow as tf
_CSV_COLUMNS = [
'age', 'workclass', 'fnlwgt', 'education', 'education_num',
'marital_status', 'occupation', 'relationship', 'race', 'gender',
'capital_gain', 'capital_loss', 'hours_per_week', 'native_country',
'income_bracket'
]
_CSV_COLUMN_DEFAULTS = [[0], [''], [0], [''], [0], [''], [''], [''], [''], [''],
[0], [0], [0], [''], ['']]
_NUM_EXAMPLES = {
'train': 32561,
'validation': 16281,
}
# 1. Read the Census Data
# 2. Converting Data into Tensors
def input_fn(data_file, num_epochs, shuffle, batch_size):
"""为Estimator创建一个input function"""
assert tf.gfile.Exists(data_file), "{0} not found.".format(data_file)
def parse_csv(line):
print("Parsing", data_file)
# tf.decode_csv会把csv文件转换成很a list of Tensor,一列一个。record_defaults用于指明每一列的缺失值用什么填充
columns = tf.decode_csv(line, record_defaults=_CSV_COLUMN_DEFAULTS)
features = dict(zip(_CSV_COLUMNS, columns))
labels = features.pop('income_bracket')
return features, tf.equal(labels, '>50K') # tf.equal(x, y) 返回一个bool类型Tensor, 表示x == y, element-wise
dataset = tf.data.TextLineDataset(data_file) \
.map(parse_csv, num_parallel_calls=5)
if shuffle:
dataset = dataset.shuffle(buffer_size=_NUM_EXAMPLES['train'] + _NUM_EXAMPLES['validation'])
dataset = dataset.repeat(num_epochs)
dataset = dataset.batch(batch_size)
iterator = dataset.make_one_shot_iterator()
batch_features, batch_labels = iterator.get_next()
return batch_features, batch_labels
# 3. Select and Engineer Features for Model
## 3.1 Base Categorical Feature Columns
# 如果我们知道所有的取值,并且取值不是很多
relationship = tf.feature_column.categorical_column_with_vocabulary_list(
'relationship', [
'Husband', 'Not-in-family', 'Wife', 'Own-child', 'Unmarried',
'Other-relative'
]
)
# 如果不知道有多少取值
occupation = tf.feature_column.categorical_column_with_hash_bucket(
'occupation', hash_bucket_size=1000
)
education = tf.feature_column.categorical_column_with_vocabulary_list(
'education', [
'Bachelors', 'HS-grad', '11th', 'Masters', '9th', 'Some-college',
'Assoc-acdm', 'Assoc-voc', '7th-8th', 'Doctorate', 'Prof-school',
'5th-6th', '10th', '1st-4th', 'Preschool', '12th'
]
)
marital_status = tf.feature_column.categorical_column_with_vocabulary_list(
'marital_status', [
'Married-civ-spouse', 'Divorced', 'Married-spouse-absent',
'Never-married', 'Separated', 'Married-AF-spouse', 'Widowed']
)
workclass = tf.feature_column.categorical_column_with_vocabulary_list(
'workclass', [
'Self-emp-not-inc', 'Private', 'State-gov', 'Federal-gov',
'Local-gov', '?', 'Self-emp-inc', 'Without-pay', 'Never-worked'])
# 3.2 Base Continuous Feature Columns
age = tf.feature_column.numeric_column('age')
education_num = tf.feature_column.numeric_column('education_num')
capital_gain = tf.feature_column.numeric_column('capital_gain')
capital_loss = tf.feature_column.numeric_column('capital_loss')
hours_per_week = tf.feature_column.numeric_column('hours_per_week')
#Sometimes the relationship between a continuous feature and the label is not linear. As a hypothetical example, a person's income may grow with age in the early stage of one's career, then the growth may slow at some point, and finally the income decreases after retirement. In this scenario, using the raw age as a real-valued feature column might not be a good choice because the model can only learn one of the three cases:
# 3.2.1 连续特征离散化
# 之所以这么做是因为:有些时候连续特征和label之间不是线性的关系。可能刚开始是正的线性关系,后面又变成了负的线性关系,这样一个折线的关系整体来看就不再是线性关系。
# bucketization 装桶
# 10个边界,11个桶
age_buckets = tf.feature_column.bucketized_column(
age, boundaries=[18, 25, 30, 35, 40, 45, 50, 55, 60, 65])
# 3.3 组合特征/交叉特征
education_x_occupation = tf.feature_column.crossed_column(
['education', 'occupation'], hash_bucket_size=1000)
age_buckets_x_education_x_occupation = tf.feature_column.crossed_column(
[age_buckets, 'education', 'occupation'], hash_bucket_size=1000
)
# 4. 模型
"""
之前的特征:
1. CategoricalColumn
2. NumericalColumn
3. BucketizedColumn
4. CrossedColumn
这些特征都是FeatureColumn的子类,可以放到一起
"""
base_columns = [
education, marital_status, relationship, workclass, occupation,
age_buckets,
]
crossed_column = [
tf.feature_column.crossed_column(
['education', 'occupation'], hash_bucket_size=1000
),
tf.feature_column.crossed_column(
[age_buckets, 'education', 'occupation'], hash_bucket_size=1000
)
]
model_dir = "./model/wide_component"
model = tf.estimator.LinearClassifier(
model_dir=model_dir, feature_columns=base_columns + crossed_column
)
train_file = './data/adult.data'
val_file = './data/adult.data'
test_file = './data/adult.test'
# 5. Train & Evaluate & Predict
model.train(input_fn=lambda: input_fn(data_file=train_file, num_epochs=1, shuffle=True, batch_size=512))
results = model.evaluate(input_fn=lambda: input_fn(val_file, 1, False, 512))
for key in sorted(results):
print("{0:20}: {1:.4f}".format(key, results[key]))
pred_iter = model.predict(input_fn=lambda: input_fn(test_file, 1, False, 1))
for pred in pred_iter:
print(pred)
break #太多了,只打印一条
test_results = model.evaluate(input_fn=lambda: input_fn(test_file, 1, False, 512))
for key in sorted(test_results):
print("{0:20}: {1:.4f}".format(key, test_results[key]))
# 6. 正则化
model = tf.estimator.LinearClassifier(
feature_columns=base_columns + crossed_column, model_dir=model_dir,
optimizer=tf.train.FtrlOptimizer(
learning_rate=0.1,
l1_regularization_strength=1.0,
l2_regularization_strength=1.0
)
)
# if __name__ == '__main__':
# print(tf.VERSION)
# data_file = './data/adult.data'
# next_batch = input_fn(data_file, num_epochs=1, shuffle=True, batch_size=5)
# with tf.Session() as sess:
# first_batch = sess.run(next_batch)
# print(first_batch[0])
# print(first_batch[1]) |
the-stack_0_8628 | # Copyright (c) 2021, NVIDIA CORPORATION. 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 required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from enum import Enum, auto
from model_navigator.core import Container
from model_navigator.framework import Framework, PyTorch, TensorFlow1, TensorFlow2
class TRITON_LOAD_MODE(Enum):
POLL_ONCE = auto()
POLL_PERIODICALLY = auto()
EXPLICIT = auto()
NONE = auto()
class TritonServer(Container):
image = "nvcr.io/nvidia/tritonserver"
tag = "py3"
@staticmethod
def library_path(framework: Framework):
paths = {
PyTorch.name: "/opt/tritonserver/lib/pytorch",
TensorFlow1.name: "/opt/tritonserver/lib/tensorflow",
TensorFlow2.name: "/opt/tritonserver/lib/tensorflow",
}
return paths[framework.name]
@staticmethod
def command(
framework: Framework,
repository_path: str,
verbose: bool = False,
strict_mode: bool = False,
load_mode: TRITON_LOAD_MODE = TRITON_LOAD_MODE.EXPLICIT,
metrics: bool = False,
):
triton_command = f"tritonserver --model-store={repository_path}"
if load_mode in [TRITON_LOAD_MODE.POLL_ONCE, TRITON_LOAD_MODE.POLL_PERIODICALLY]:
triton_command += " --model-control-mode=poll"
if load_mode == TRITON_LOAD_MODE.POLL_PERIODICALLY:
triton_command += " --repository- poll-secs=5"
if load_mode == TRITON_LOAD_MODE.EXPLICIT:
triton_command += " --model-control-mode=explicit"
if verbose:
triton_command += " --log-verbose=1"
if not strict_mode:
triton_command += " --strict-model-config=false"
if not metrics:
triton_command += " --allow-metrics=false --allow-gpu-metrics=false"
if isinstance(framework, (TensorFlow1, TensorFlow2)):
version = 1 if framework == TensorFlow1 else 2
triton_command += f" --backend-config=tensorflow,version={version}"
return triton_command
@staticmethod
def api_method(key):
methods = {
"livenessProbe": "/v2/health/live",
"readinessProbe": "/v2/health/ready",
}
return methods[key]
|
the-stack_0_8629 | from tree_common import TreeNode, insert, inOrderTraversal
from typing import List
from ...fundamentals.linked_lists.single_list import Node as LinkedNode
"""
Use Created linked lists from a tree
"""
def tree_to_linked_lists(root:TreeNode) -> List[LinkedNode]:
result = [LinkedNode]
level_to_linked_list(root, result, 0)
return result
def level_to_linked_list(root:TreeNode, result:List[LinkedNode], level:int):
if not root:
return
if len(result) == level:
result.append([LinkedNode(root)])
else:
singly_node = result[level]
while singly_node.n:
singly_node = singly_node.n
singly_node.next = LinkedNode(root)
level_to_linked_list(root.left, result, level + 1)
level_to_linked_list(root.right, result, level + 1)
def bst(root):
if not root:
return []
result = [LinkedNode]
singly_node = LinkedNode(root)
while singly_node:
result.append(singly_node)
parents = singly_node
prehead = LinkedNode(-1)
singly_node = prehead
while parents:
if parents.data.left:
singly_node.next = LinkedNode(parents.data.left)
singly_node = singly_node.next
if parents.data.right:
singly_node.next = LinkedNode(parents.data.right)
singly_node = singly_node.next
singly_node = prehead.next
return result
### not tested
if __name__ == "__main__":
root = insert(None, 4)
n2 = insert(root, 2)
n1 = insert(root, 1)
n3 = insert(root, 3)
n8 = insert(root, 8)
n11 = insert(root, 11)
n7= insert(root, 7)
tree_to_linked_lists(root)
|
the-stack_0_8630 | # -*- coding: utf-8 -*-
'''
Manage RabbitMQ Plugins
=======================
.. versionadded:: 2014.1.0
Example:
.. code-block:: yaml
some_plugin:
rabbitmq_plugin.enabled: []
'''
# Import Python Libs
from __future__ import absolute_import, unicode_literals, print_function
import logging
# Import Salt Libs
from salt.exceptions import CommandExecutionError
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load if RabbitMQ is installed.
'''
if __salt__['cmd.has_exec']('rabbitmqctl'):
return True
return False
def enabled(name, runas=None):
'''
Ensure the RabbitMQ plugin is enabled.
name
The name of the plugin
runas
The user to run the rabbitmq-plugin command as
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
try:
plugin_enabled = __salt__['rabbitmq.plugin_is_enabled'](name, runas=runas)
except CommandExecutionError as err:
ret['result'] = False
ret['comment'] = 'Error: {0}'.format(err)
return ret
if plugin_enabled:
ret['comment'] = 'Plugin \'{0}\' is already enabled.'.format(name)
return ret
if not __opts__['test']:
try:
__salt__['rabbitmq.enable_plugin'](name, runas=runas)
except CommandExecutionError as err:
ret['result'] = False
ret['comment'] = 'Error: {0}'.format(err)
return ret
ret['changes'].update({'old': '', 'new': name})
if __opts__['test'] and ret['changes']:
ret['result'] = None
ret['comment'] = 'Plugin \'{0}\' is set to be enabled.'.format(name)
return ret
ret['comment'] = 'Plugin \'{0}\' was enabled.'.format(name)
return ret
def disabled(name, runas=None):
'''
Ensure the RabbitMQ plugin is disabled.
name
The name of the plugin
runas
The user to run the rabbitmq-plugin command as
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
try:
plugin_enabled = __salt__['rabbitmq.plugin_is_enabled'](name, runas=runas)
except CommandExecutionError as err:
ret['result'] = False
ret['comment'] = 'Error: {0}'.format(err)
return ret
if not plugin_enabled:
ret['comment'] = 'Plugin \'{0}\' is already disabled.'.format(name)
return ret
if not __opts__['test']:
try:
__salt__['rabbitmq.disable_plugin'](name, runas=runas)
except CommandExecutionError as err:
ret['result'] = False
ret['comment'] = 'Error: {0}'.format(err)
return ret
ret['changes'].update({'old': name, 'new': ''})
if __opts__['test'] and ret['changes']:
ret['result'] = None
ret['comment'] = 'Plugin \'{0}\' is set to be disabled.'.format(name)
return ret
ret['comment'] = 'Plugin \'{0}\' was disabled.'.format(name)
return ret
|
the-stack_0_8631 | # -*- coding: utf-8 -*-
# Scrapy settings for weibo_m project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# https://doc.scrapy.org/en/latest/topics/settings.html
# https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
# https://doc.scrapy.org/en/latest/topics/spider-middleware.html
BOT_NAME = 'weibo_m'
SPIDER_MODULES = ['weibo_m.spiders']
NEWSPIDER_MODULE = 'weibo_m.spiders'
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'weibo_m (+http://www.yourdomain.com)'
# Obey robots.txt rules
ROBOTSTXT_OBEY = False
# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32
# Configure a delay for requests for the same website (default: 0)
# See https://doc.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
DOWNLOAD_DELAY = 3
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16
# Disable cookies (enabled by default)
#COOKIES_ENABLED = False
# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False
# Override the default request headers:
DEFAULT_REQUEST_HEADERS = {
'Accept': 'application/json, text/plain, */*',
'Accept-Encoding': 'gzip, deflate, sdch',
'Accept-Language': 'zh-CN,zh;q=0.8,en;q=0.6,ja;q=0.4,zh-TW;q=0.2,mt;q=0.2',
'Connection': 'keep-alive',
'Host': 'm.weibo.cn',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36',
'X-Requested-With': 'XMLHttpRequest',
}
# Enable or disable spider middlewares
# See https://doc.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
# 'weibo_m.middlewares.WeiboMSpiderMiddleware': 543,
#}
# Enable or disable downloader middlewares
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
# DOWNLOADER_MIDDLEWARES = {
# 'weibo_m.middlewares.ProxyMiddleware': 543,
# 'weibo_m.middlewares.CookiesMiddleware': 544,
# }
# Enable or disable extensions
# See https://doc.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
# 'scrapy.extensions.telnet.TelnetConsole': None,
#}
# Configure item pipelines
# See https://doc.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
'weibo_m.pipelines.TimePipeline': 300,
'weibo_m.pipelines.WeiboPipeline': 301,
'weibo_m.pipelines.MongoPipeline': 302,
}
# Enable and configure the AutoThrottle extension (disabled by default)
# See https://doc.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False
# Enable and configure HTTP caching (disabled by default)
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = 'httpcache'
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'
MONGO_URI = '10.255.1.175'
MONGO_DB = 'weibo_1300419694'
REDIS_URL = 'redis://:[email protected]:6379/3'
START_USER = ['1300419694']
|
the-stack_0_8636 | from collections import OrderedDict, deque, namedtuple
import numpy as np
from sklearn.model_selection import train_test_split
from torchlib.dataset.utils import create_data_loader
from torchlib.deep_rl import BaseAgent
class Dataset(object):
def __init__(self):
self._states = []
self._actions = []
self._next_states = []
self._rewards = []
self._dones = []
@property
def is_empty(self):
return len(self) == 0
def __len__(self):
return len(self._states)
##################
### Statistics ###
##################
@property
def state_mean(self):
return np.mean(self._states, axis=0).astype(np.float32)
@property
def state_std(self):
return np.std(self._states, axis=0).astype(np.float32)
@property
def action_mean(self):
return np.mean(self._actions, axis=0).astype(np.float32)
@property
def action_std(self):
return np.std(self._actions, axis=0).astype(np.float32)
@property
def delta_state_mean(self):
return np.mean(np.array(self._next_states) - np.array(self._states), axis=0).astype(np.float32)
@property
def delta_state_std(self):
return np.std(np.array(self._next_states) - np.array(self._states), axis=0).astype(np.float32)
###################
### Adding data ###
###################
def add(self, state, action, next_state, reward, done):
"""
Add (s, a, r, s') to this dataset
"""
if not self.is_empty:
# ensure the state, action, next_state are of the same dimension
assert len(self._states[-1]) == len(np.ravel(state))
assert len(self._actions[-1]) == len(np.ravel(action))
assert len(self._next_states[-1]) == len(np.ravel(next_state))
self._states.append(np.ravel(state))
self._actions.append(np.ravel(action))
self._next_states.append(np.ravel(next_state))
self._rewards.append(reward)
self._dones.append(done)
def append(self, other_dataset):
"""
Append other_dataset to this dataset
"""
if not self.is_empty and not other_dataset.is_empty:
# ensure the state, action, next_state are of the same dimension
assert len(self._states[-1]) == len(other_dataset._states[-1])
assert len(self._actions[-1]) == len(other_dataset._actions[-1])
assert len(self._next_states[-1]) == len(other_dataset._next_states[-1])
self._states += other_dataset._states
self._actions += other_dataset._actions
self._next_states += other_dataset._next_states
self._rewards += other_dataset._rewards
self._dones += other_dataset._dones
############################
### Iterate through data ###
############################
def rollout_iterator(self):
"""
Iterate through all the rollouts in the dataset sequentially
"""
end_indices = np.nonzero(self._dones)[0] + 1
states = np.asarray(self._states)
actions = np.asarray(self._actions)
next_states = np.asarray(self._next_states)
rewards = np.asarray(self._rewards)
dones = np.asarray(self._dones)
start_idx = 0
for end_idx in end_indices:
indices = np.arange(start_idx, end_idx)
yield states[indices], actions[indices], next_states[indices], rewards[indices], dones[indices]
start_idx = end_idx
def random_iterator(self, batch_size):
"""
Iterate once through all (s, a, r, s') in batches in a random order
"""
all_indices = np.nonzero(np.logical_not(self._dones))[0]
np.random.shuffle(all_indices)
states = np.asarray(self._states)
actions = np.asarray(self._actions)
next_states = np.asarray(self._next_states)
rewards = np.asarray(self._rewards)
dones = np.asarray(self._dones)
i = 0
while i < len(all_indices):
indices = all_indices[i:i + batch_size]
yield states[indices], actions[indices], next_states[indices], rewards[indices], dones[indices]
i += batch_size
def log(self):
end_idxs = np.nonzero(self._dones)[0] + 1
returns = []
start_idx = 0
for end_idx in end_idxs:
rewards = self._rewards[start_idx:end_idx]
returns.append(np.sum(rewards))
start_idx = end_idx
stats = OrderedDict({
'ReturnAvg': np.mean(returns),
'ReturnStd': np.std(returns),
'ReturnMin': np.min(returns),
'ReturnMax': np.max(returns)
})
return stats
Transition = namedtuple('Transition', ('state', 'action', 'reward'))
ImitationTransition = namedtuple('ImitationTransition', ('state', 'action', 'reward', 'best_action'))
class EpisodicDataset(object):
def __init__(self, maxlen=10000):
self.memory = deque()
# current state
self._states = []
self._actions = []
self._rewards = []
self.size = 0
# initial state
self.initial_state = deque(maxlen=maxlen)
self.maxlen = maxlen
def __len__(self):
return self.size
@property
def num_trajectories(self):
return len(self.memory)
@property
def is_empty(self):
return len(self) == 0
@property
def state_mean(self):
states = []
for trajectory in self.memory:
states.append(trajectory.state)
return np.mean(np.concatenate(states, axis=0), axis=0)
@property
def state_std(self):
states = []
for trajectory in self.memory:
states.append(trajectory.state)
return np.std(np.concatenate(states, axis=0), axis=0)
@property
def action_mean(self):
actions = []
for trajectory in self.memory:
actions.append(trajectory.action)
return np.mean(np.concatenate(actions, axis=0), axis=0).astype(np.float32)
@property
def action_std(self):
actions = []
for trajectory in self.memory:
actions.append(trajectory.action)
return np.std(np.concatenate(actions, axis=0), axis=0).astype(np.float32)
@property
def delta_state_mean(self):
delta_states = []
for trajectory in self.memory:
states = trajectory.state
delta_states.append(states[1:] - states[:-1])
return np.mean(np.concatenate(delta_states, axis=0), axis=0)
@property
def delta_state_std(self):
delta_states = []
for trajectory in self.memory:
states = trajectory.state
delta_states.append(states[1:] - states[:-1])
return np.std(np.concatenate(delta_states, axis=0), axis=0)
@property
def reward_mean(self):
rewards = []
for trajectory in self.memory:
rewards.append(trajectory.reward)
return np.mean(np.concatenate(rewards, axis=0), axis=0).astype(np.float32)
@property
def reward_std(self):
rewards = []
for trajectory in self.memory:
rewards.append(trajectory.reward)
return np.std(np.concatenate(rewards, axis=0), axis=0).astype(np.float32)
def add(self, state, action, next_state, reward, done):
self._states.append(np.ravel(state))
if isinstance(action, np.ndarray) and len(action.shape) != 0:
self._actions.append(np.ravel(action))
else:
self._actions.append(action)
self._rewards.append(np.ravel(reward))
self.size += 1
if done:
self._states.append(next_state)
self.memory.append(Transition(state=np.array(self._states),
action=np.array(self._actions),
reward=np.array(self._rewards)))
self._states = []
self._actions = []
self._rewards = []
def append(self, other_dataset):
self.memory.extend(other_dataset.memory)
self.size += other_dataset.size
while self.size > self.maxlen:
trajectory = self.memory.popleft()
self.size -= len(trajectory.action)
def get_initial_states(self):
init_states = []
for trajectory in self.memory:
init_states.append(trajectory.state[0].copy())
return init_states
def rollout_iterator(self):
for trajectory in self.memory:
states = trajectory.state[:-1]
next_states = trajectory.state[1:]
actions = trajectory.action
rewards = trajectory.reward
dones = [False] * actions.shape[0]
dones[-1] = True
yield states, actions, next_states, rewards, dones
def random_iterator(self, batch_size, train_val_split_ratio=0.2):
states = []
actions = []
rewards = []
next_states = []
dones = []
for trajectory in self.memory:
states.append(trajectory.state[:-1])
actions.append(trajectory.action)
next_states.append(trajectory.state[1:])
rewards.append(trajectory.reward)
done = [False] * trajectory.action.shape[0]
done[-1] = True
dones.append(np.array(done))
states = np.concatenate(states, axis=0)
actions = np.concatenate(actions, axis=0)
next_states = np.concatenate(next_states, axis=0)
rewards = np.concatenate(rewards, axis=0)
dones = np.concatenate(dones, axis=0)
input_tuple = (states, actions, next_states, rewards, dones)
output_tuple = train_test_split(*input_tuple, test_size=train_val_split_ratio)
train_tuple = output_tuple[0::2]
val_tuple = output_tuple[1::2]
# in training, we drop last batch to avoid batch size 1 that may crash batch_norm layer.
train_data_loader = create_data_loader(train_tuple, batch_size=batch_size, shuffle=True,
drop_last=True)
val_data_loader = create_data_loader(val_tuple, batch_size=batch_size, shuffle=False,
drop_last=False)
return train_data_loader, val_data_loader
def log(self):
returns = []
for trajectory in self.memory:
returns.append(np.sum(trajectory.reward))
stats = OrderedDict({
'ReturnAvg': np.mean(returns),
'ReturnStd': np.std(returns),
'ReturnMin': np.min(returns),
'ReturnMax': np.max(returns)
})
return stats
class StateActionPairDataset(object):
def __init__(self, max_size):
self.states = deque(maxlen=max_size)
self.actions = deque(maxlen=max_size)
def __len__(self):
return len(self.states)
@property
def maxlen(self):
return self.states.maxlen
@property
def is_empty(self):
return len(self) == 0
def add(self, state, action):
self.states.append(state)
self.actions.append(action)
@property
def state_stats(self):
states = np.array(self.states)
return np.mean(states, axis=0), np.std(states, axis=0)
@property
def action_stats(self):
actions = np.array(self.actions)
return np.mean(actions, axis=0), np.std(actions, axis=0)
def random_iterator(self, batch_size, train_val_split_ratio=0.2):
states = np.array(self.states)
actions = np.array(self.actions)
input_tuple = (states, actions)
output_tuple = train_test_split(*input_tuple, test_size=train_val_split_ratio)
train_tuple = output_tuple[0::2]
val_tuple = output_tuple[1::2]
# in training, we drop last batch to avoid batch size 1 that may crash batch_norm layer.
train_data_loader = create_data_loader(train_tuple, batch_size=batch_size, shuffle=True,
drop_last=True)
val_data_loader = create_data_loader(val_tuple, batch_size=batch_size, shuffle=False,
drop_last=False)
return train_data_loader, val_data_loader
def gather_rollouts(env, policy: BaseAgent, num_rollouts, max_rollout_length) -> EpisodicDataset:
dataset = EpisodicDataset()
for _ in range(num_rollouts):
state = env.reset()
done = False
t = 0
while not done:
t += 1
if state.dtype == np.float:
state = state.astype(np.float32)
action = policy.predict(state)
if isinstance(action, np.ndarray) and action.dtype == np.float:
action = action.astype(np.float32)
next_state, reward, done, _ = env.step(action)
if next_state.dtype == np.float:
next_state = next_state.astype(np.float32)
done = done or (t >= max_rollout_length)
dataset.add(state, action, next_state, reward, done)
state = next_state
return dataset
|
the-stack_0_8637 | #!/usr/bin/env python3
# Copyright (c) 2016 The Magmelldollar Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.mininode import *
from test_framework.test_framework import MagmelldollarTestFramework
from test_framework.util import *
from test_framework.blocktools import create_block, create_coinbase, add_witness_commitment
from test_framework.siphash import siphash256
from test_framework.script import CScript, OP_TRUE
VB_TOP_BITS = 0x20000000
'''
CompactBlocksTest -- test compact blocks (BIP 152)
Version 1 compact blocks are pre-segwit (txids)
Version 2 compact blocks are post-segwit (wtxids)
'''
# TestNode: A peer we use to send messages to magmelldollard, and store responses.
class TestNode(SingleNodeConnCB):
def __init__(self):
SingleNodeConnCB.__init__(self)
self.last_sendcmpct = []
self.last_headers = None
self.last_inv = None
self.last_cmpctblock = None
self.block_announced = False
self.last_getdata = None
self.last_getblocktxn = None
self.last_block = None
self.last_blocktxn = None
# Store the hashes of blocks we've seen announced.
# This is for synchronizing the p2p message traffic,
# so we can eg wait until a particular block is announced.
self.set_announced_blockhashes = set()
def on_sendcmpct(self, conn, message):
self.last_sendcmpct.append(message)
def on_block(self, conn, message):
self.last_block = message
def on_cmpctblock(self, conn, message):
self.last_cmpctblock = message
self.block_announced = True
self.last_cmpctblock.header_and_shortids.header.calc_sha256()
self.set_announced_blockhashes.add(self.last_cmpctblock.header_and_shortids.header.sha256)
def on_headers(self, conn, message):
self.last_headers = message
self.block_announced = True
for x in self.last_headers.headers:
x.calc_sha256()
self.set_announced_blockhashes.add(x.sha256)
def on_inv(self, conn, message):
self.last_inv = message
for x in self.last_inv.inv:
if x.type == 2:
self.block_announced = True
self.set_announced_blockhashes.add(x.hash)
def on_getdata(self, conn, message):
self.last_getdata = message
def on_getblocktxn(self, conn, message):
self.last_getblocktxn = message
def on_blocktxn(self, conn, message):
self.last_blocktxn = message
# Requires caller to hold mininode_lock
def received_block_announcement(self):
return self.block_announced
def clear_block_announcement(self):
with mininode_lock:
self.block_announced = False
self.last_inv = None
self.last_headers = None
self.last_cmpctblock = None
def get_headers(self, locator, hashstop):
msg = msg_getheaders()
msg.locator.vHave = locator
msg.hashstop = hashstop
self.connection.send_message(msg)
def send_header_for_blocks(self, new_blocks):
headers_message = msg_headers()
headers_message.headers = [CBlockHeader(b) for b in new_blocks]
self.send_message(headers_message)
def request_headers_and_sync(self, locator, hashstop=0):
self.clear_block_announcement()
self.get_headers(locator, hashstop)
assert(wait_until(self.received_block_announcement, timeout=30))
assert(self.received_block_announcement())
self.clear_block_announcement()
# Block until a block announcement for a particular block hash is
# received.
def wait_for_block_announcement(self, block_hash, timeout=30):
def received_hash():
return (block_hash in self.set_announced_blockhashes)
return wait_until(received_hash, timeout=timeout)
class CompactBlocksTest(MagmelldollarTestFramework):
def __init__(self):
super().__init__()
self.setup_clean_chain = True
# Node0 = pre-segwit, node1 = segwit-aware
self.num_nodes = 2
self.utxos = []
def setup_network(self):
self.nodes = []
# Start up node0 to be a version 1, pre-segwit node.
self.nodes = start_nodes(self.num_nodes, self.options.tmpdir,
[["-debug", "-logtimemicros=1", "-bip9params=segwit:0:0"],
["-debug", "-logtimemicros", "-txindex"]])
connect_nodes(self.nodes[0], 1)
def build_block_on_tip(self, node, segwit=False):
height = node.getblockcount()
tip = node.getbestblockhash()
mtp = node.getblockheader(tip)['mediantime']
block = create_block(int(tip, 16), create_coinbase(height + 1), mtp + 1)
block.nVersion = VB_TOP_BITS
if segwit:
add_witness_commitment(block)
block.solve()
return block
# Create 10 more anyone-can-spend utxo's for testing.
def make_utxos(self):
# Doesn't matter which node we use, just use node0.
block = self.build_block_on_tip(self.nodes[0])
self.test_node.send_and_ping(msg_block(block))
assert(int(self.nodes[0].getbestblockhash(), 16) == block.sha256)
self.nodes[0].generate(100)
total_value = block.vtx[0].vout[0].nValue
out_value = total_value // 10
tx = CTransaction()
tx.vin.append(CTxIn(COutPoint(block.vtx[0].sha256, 0), b''))
for i in range(10):
tx.vout.append(CTxOut(out_value, CScript([OP_TRUE])))
tx.rehash()
block2 = self.build_block_on_tip(self.nodes[0])
block2.vtx.append(tx)
block2.hashMerkleRoot = block2.calc_merkle_root()
block2.solve()
self.test_node.send_and_ping(msg_block(block2))
assert_equal(int(self.nodes[0].getbestblockhash(), 16), block2.sha256)
self.utxos.extend([[tx.sha256, i, out_value] for i in range(10)])
return
# Test "sendcmpct" (between peers preferring the same version):
# - No compact block announcements unless sendcmpct is sent.
# - If sendcmpct is sent with version > preferred_version, the message is ignored.
# - If sendcmpct is sent with boolean 0, then block announcements are not
# made with compact blocks.
# - If sendcmpct is then sent with boolean 1, then new block announcements
# are made with compact blocks.
# If old_node is passed in, request compact blocks with version=preferred-1
# and verify that it receives block announcements via compact block.
def test_sendcmpct(self, node, test_node, preferred_version, old_node=None):
# Make sure we get a SENDCMPCT message from our peer
def received_sendcmpct():
return (len(test_node.last_sendcmpct) > 0)
got_message = wait_until(received_sendcmpct, timeout=30)
assert(received_sendcmpct())
assert(got_message)
with mininode_lock:
# Check that the first version received is the preferred one
assert_equal(test_node.last_sendcmpct[0].version, preferred_version)
# And that we receive versions down to 1.
assert_equal(test_node.last_sendcmpct[-1].version, 1)
test_node.last_sendcmpct = []
tip = int(node.getbestblockhash(), 16)
def check_announcement_of_new_block(node, peer, predicate):
peer.clear_block_announcement()
block_hash = int(node.generate(1)[0], 16)
peer.wait_for_block_announcement(block_hash, timeout=30)
assert(peer.block_announced)
assert(got_message)
with mininode_lock:
assert predicate(peer), (
"block_hash={!r}, cmpctblock={!r}, inv={!r}".format(
block_hash, peer.last_cmpctblock, peer.last_inv))
# We shouldn't get any block announcements via cmpctblock yet.
check_announcement_of_new_block(node, test_node, lambda p: p.last_cmpctblock is None)
# Try one more time, this time after requesting headers.
test_node.request_headers_and_sync(locator=[tip])
check_announcement_of_new_block(node, test_node, lambda p: p.last_cmpctblock is None and p.last_inv is not None)
# Test a few ways of using sendcmpct that should NOT
# result in compact block announcements.
# Before each test, sync the headers chain.
test_node.request_headers_and_sync(locator=[tip])
# Now try a SENDCMPCT message with too-high version
sendcmpct = msg_sendcmpct()
sendcmpct.version = preferred_version+1
sendcmpct.announce = True
test_node.send_and_ping(sendcmpct)
check_announcement_of_new_block(node, test_node, lambda p: p.last_cmpctblock is None)
# Headers sync before next test.
test_node.request_headers_and_sync(locator=[tip])
# Now try a SENDCMPCT message with valid version, but announce=False
sendcmpct.version = preferred_version
sendcmpct.announce = False
test_node.send_and_ping(sendcmpct)
check_announcement_of_new_block(node, test_node, lambda p: p.last_cmpctblock is None)
# Headers sync before next test.
test_node.request_headers_and_sync(locator=[tip])
# Finally, try a SENDCMPCT message with announce=True
sendcmpct.version = preferred_version
sendcmpct.announce = True
test_node.send_and_ping(sendcmpct)
check_announcement_of_new_block(node, test_node, lambda p: p.last_cmpctblock is not None)
# Try one more time (no headers sync should be needed!)
check_announcement_of_new_block(node, test_node, lambda p: p.last_cmpctblock is not None)
# Try one more time, after turning on sendheaders
test_node.send_and_ping(msg_sendheaders())
check_announcement_of_new_block(node, test_node, lambda p: p.last_cmpctblock is not None)
# Try one more time, after sending a version-1, announce=false message.
sendcmpct.version = preferred_version-1
sendcmpct.announce = False
test_node.send_and_ping(sendcmpct)
check_announcement_of_new_block(node, test_node, lambda p: p.last_cmpctblock is not None)
# Now turn off announcements
sendcmpct.version = preferred_version
sendcmpct.announce = False
test_node.send_and_ping(sendcmpct)
check_announcement_of_new_block(node, test_node, lambda p: p.last_cmpctblock is None and p.last_headers is not None)
if old_node is not None:
# Verify that a peer using an older protocol version can receive
# announcements from this node.
sendcmpct.version = preferred_version-1
sendcmpct.announce = True
old_node.send_and_ping(sendcmpct)
# Header sync
old_node.request_headers_and_sync(locator=[tip])
check_announcement_of_new_block(node, old_node, lambda p: p.last_cmpctblock is not None)
# This test actually causes magmelldollard to (reasonably!) disconnect us, so do this last.
def test_invalid_cmpctblock_message(self):
self.nodes[0].generate(101)
block = self.build_block_on_tip(self.nodes[0])
cmpct_block = P2PHeaderAndShortIDs()
cmpct_block.header = CBlockHeader(block)
cmpct_block.prefilled_txn_length = 1
# This index will be too high
prefilled_txn = PrefilledTransaction(1, block.vtx[0])
cmpct_block.prefilled_txn = [prefilled_txn]
self.test_node.send_and_ping(msg_cmpctblock(cmpct_block))
assert(int(self.nodes[0].getbestblockhash(), 16) == block.hashPrevBlock)
# Compare the generated shortids to what we expect based on BIP 152, given
# magmelldollard's choice of nonce.
def test_compactblock_construction(self, node, test_node, version, use_witness_address):
# Generate a bunch of transactions.
node.generate(101)
num_transactions = 25
address = node.getnewaddress()
if use_witness_address:
# Want at least one segwit spend, so move all funds to
# a witness address.
address = node.addwitnessaddress(address)
value_to_send = node.getbalance()
node.sendtoaddress(address, satoshi_round(value_to_send-Decimal(0.1)))
node.generate(1)
segwit_tx_generated = False
for i in range(num_transactions):
txid = node.sendtoaddress(address, 0.1)
hex_tx = node.gettransaction(txid)["hex"]
tx = FromHex(CTransaction(), hex_tx)
if not tx.wit.is_null():
segwit_tx_generated = True
if use_witness_address:
assert(segwit_tx_generated) # check that our test is not broken
# Wait until we've seen the block announcement for the resulting tip
tip = int(node.getbestblockhash(), 16)
assert(test_node.wait_for_block_announcement(tip))
# Now mine a block, and look at the resulting compact block.
test_node.clear_block_announcement()
block_hash = int(node.generate(1)[0], 16)
# Store the raw block in our internal format.
block = FromHex(CBlock(), node.getblock("%02x" % block_hash, False))
[tx.calc_sha256() for tx in block.vtx]
block.rehash()
# Don't care which type of announcement came back for this test; just
# request the compact block if we didn't get one yet.
wait_until(test_node.received_block_announcement, timeout=30)
assert(test_node.received_block_announcement())
with mininode_lock:
if test_node.last_cmpctblock is None:
test_node.clear_block_announcement()
inv = CInv(4, block_hash) # 4 == "CompactBlock"
test_node.send_message(msg_getdata([inv]))
wait_until(test_node.received_block_announcement, timeout=30)
assert(test_node.received_block_announcement())
# Now we should have the compactblock
header_and_shortids = None
with mininode_lock:
assert(test_node.last_cmpctblock is not None)
# Convert the on-the-wire representation to absolute indexes
header_and_shortids = HeaderAndShortIDs(test_node.last_cmpctblock.header_and_shortids)
# Check that we got the right block!
header_and_shortids.header.calc_sha256()
assert_equal(header_and_shortids.header.sha256, block_hash)
# Make sure the prefilled_txn appears to have included the coinbase
assert(len(header_and_shortids.prefilled_txn) >= 1)
assert_equal(header_and_shortids.prefilled_txn[0].index, 0)
# Check that all prefilled_txn entries match what's in the block.
for entry in header_and_shortids.prefilled_txn:
entry.tx.calc_sha256()
# This checks the non-witness parts of the tx agree
assert_equal(entry.tx.sha256, block.vtx[entry.index].sha256)
# And this checks the witness
wtxid = entry.tx.calc_sha256(True)
if version == 2:
assert_equal(wtxid, block.vtx[entry.index].calc_sha256(True))
else:
# Shouldn't have received a witness
assert(entry.tx.wit.is_null())
# Check that the cmpctblock message announced all the transactions.
assert_equal(len(header_and_shortids.prefilled_txn) + len(header_and_shortids.shortids), len(block.vtx))
# And now check that all the shortids are as expected as well.
# Determine the siphash keys to use.
[k0, k1] = header_and_shortids.get_siphash_keys()
index = 0
while index < len(block.vtx):
if (len(header_and_shortids.prefilled_txn) > 0 and
header_and_shortids.prefilled_txn[0].index == index):
# Already checked prefilled transactions above
header_and_shortids.prefilled_txn.pop(0)
else:
tx_hash = block.vtx[index].sha256
if version == 2:
tx_hash = block.vtx[index].calc_sha256(True)
shortid = calculate_shortid(k0, k1, tx_hash)
assert_equal(shortid, header_and_shortids.shortids[0])
header_and_shortids.shortids.pop(0)
index += 1
# Test that magmelldollard requests compact blocks when we announce new blocks
# via header or inv, and that responding to getblocktxn causes the block
# to be successfully reconstructed.
# Post-segwit: upgraded nodes would only make this request of cb-version-2,
# NODE_WITNESS peers. Unupgraded nodes would still make this request of
# any cb-version-1-supporting peer.
def test_compactblock_requests(self, node, test_node, version, segwit):
# Try announcing a block with an inv or header, expect a compactblock
# request
for announce in ["inv", "header"]:
block = self.build_block_on_tip(node, segwit=segwit)
with mininode_lock:
test_node.last_getdata = None
if announce == "inv":
test_node.send_message(msg_inv([CInv(2, block.sha256)]))
else:
test_node.send_header_for_blocks([block])
success = wait_until(lambda: test_node.last_getdata is not None, timeout=30)
assert(success)
assert_equal(len(test_node.last_getdata.inv), 1)
assert_equal(test_node.last_getdata.inv[0].type, 4)
assert_equal(test_node.last_getdata.inv[0].hash, block.sha256)
# Send back a compactblock message that omits the coinbase
comp_block = HeaderAndShortIDs()
comp_block.header = CBlockHeader(block)
comp_block.nonce = 0
[k0, k1] = comp_block.get_siphash_keys()
coinbase_hash = block.vtx[0].sha256
if version == 2:
coinbase_hash = block.vtx[0].calc_sha256(True)
comp_block.shortids = [
calculate_shortid(k0, k1, coinbase_hash) ]
test_node.send_and_ping(msg_cmpctblock(comp_block.to_p2p()))
assert_equal(int(node.getbestblockhash(), 16), block.hashPrevBlock)
# Expect a getblocktxn message.
with mininode_lock:
assert(test_node.last_getblocktxn is not None)
absolute_indexes = test_node.last_getblocktxn.block_txn_request.to_absolute()
assert_equal(absolute_indexes, [0]) # should be a coinbase request
# Send the coinbase, and verify that the tip advances.
if version == 2:
msg = msg_witness_blocktxn()
else:
msg = msg_blocktxn()
msg.block_transactions.blockhash = block.sha256
msg.block_transactions.transactions = [block.vtx[0]]
test_node.send_and_ping(msg)
assert_equal(int(node.getbestblockhash(), 16), block.sha256)
# Create a chain of transactions from given utxo, and add to a new block.
def build_block_with_transactions(self, node, utxo, num_transactions):
block = self.build_block_on_tip(node)
for i in range(num_transactions):
tx = CTransaction()
tx.vin.append(CTxIn(COutPoint(utxo[0], utxo[1]), b''))
tx.vout.append(CTxOut(utxo[2] - 100000, CScript([OP_TRUE])))
tx.rehash()
utxo = [tx.sha256, 0, tx.vout[0].nValue]
block.vtx.append(tx)
block.hashMerkleRoot = block.calc_merkle_root()
block.solve()
return block
# Test that we only receive getblocktxn requests for transactions that the
# node needs, and that responding to them causes the block to be
# reconstructed.
def test_getblocktxn_requests(self, node, test_node, version):
with_witness = (version==2)
def test_getblocktxn_response(compact_block, peer, expected_result):
msg = msg_cmpctblock(compact_block.to_p2p())
peer.send_and_ping(msg)
with mininode_lock:
assert(peer.last_getblocktxn is not None)
absolute_indexes = peer.last_getblocktxn.block_txn_request.to_absolute()
assert_equal(absolute_indexes, expected_result)
def test_tip_after_message(node, peer, msg, tip):
peer.send_and_ping(msg)
assert_equal(int(node.getbestblockhash(), 16), tip)
# First try announcing compactblocks that won't reconstruct, and verify
# that we receive getblocktxn messages back.
utxo = self.utxos.pop(0)
block = self.build_block_with_transactions(node, utxo, 5)
self.utxos.append([block.vtx[-1].sha256, 0, block.vtx[-1].vout[0].nValue])
comp_block = HeaderAndShortIDs()
comp_block.initialize_from_block(block, use_witness=with_witness)
test_getblocktxn_response(comp_block, test_node, [1, 2, 3, 4, 5])
msg_bt = msg_blocktxn()
if with_witness:
msg_bt = msg_witness_blocktxn() # serialize with witnesses
msg_bt.block_transactions = BlockTransactions(block.sha256, block.vtx[1:])
test_tip_after_message(node, test_node, msg_bt, block.sha256)
utxo = self.utxos.pop(0)
block = self.build_block_with_transactions(node, utxo, 5)
self.utxos.append([block.vtx[-1].sha256, 0, block.vtx[-1].vout[0].nValue])
# Now try interspersing the prefilled transactions
comp_block.initialize_from_block(block, prefill_list=[0, 1, 5], use_witness=with_witness)
test_getblocktxn_response(comp_block, test_node, [2, 3, 4])
msg_bt.block_transactions = BlockTransactions(block.sha256, block.vtx[2:5])
test_tip_after_message(node, test_node, msg_bt, block.sha256)
# Now try giving one transaction ahead of time.
utxo = self.utxos.pop(0)
block = self.build_block_with_transactions(node, utxo, 5)
self.utxos.append([block.vtx[-1].sha256, 0, block.vtx[-1].vout[0].nValue])
test_node.send_and_ping(msg_tx(block.vtx[1]))
assert(block.vtx[1].hash in node.getrawmempool())
# Prefill 4 out of the 6 transactions, and verify that only the one
# that was not in the mempool is requested.
comp_block.initialize_from_block(block, prefill_list=[0, 2, 3, 4], use_witness=with_witness)
test_getblocktxn_response(comp_block, test_node, [5])
msg_bt.block_transactions = BlockTransactions(block.sha256, [block.vtx[5]])
test_tip_after_message(node, test_node, msg_bt, block.sha256)
# Now provide all transactions to the node before the block is
# announced and verify reconstruction happens immediately.
utxo = self.utxos.pop(0)
block = self.build_block_with_transactions(node, utxo, 10)
self.utxos.append([block.vtx[-1].sha256, 0, block.vtx[-1].vout[0].nValue])
for tx in block.vtx[1:]:
test_node.send_message(msg_tx(tx))
test_node.sync_with_ping()
# Make sure all transactions were accepted.
mempool = node.getrawmempool()
for tx in block.vtx[1:]:
assert(tx.hash in mempool)
# Clear out last request.
with mininode_lock:
test_node.last_getblocktxn = None
# Send compact block
comp_block.initialize_from_block(block, prefill_list=[0], use_witness=with_witness)
test_tip_after_message(node, test_node, msg_cmpctblock(comp_block.to_p2p()), block.sha256)
with mininode_lock:
# Shouldn't have gotten a request for any transaction
assert(test_node.last_getblocktxn is None)
# Incorrectly responding to a getblocktxn shouldn't cause the block to be
# permanently failed.
def test_incorrect_blocktxn_response(self, node, test_node, version):
if (len(self.utxos) == 0):
self.make_utxos()
utxo = self.utxos.pop(0)
block = self.build_block_with_transactions(node, utxo, 10)
self.utxos.append([block.vtx[-1].sha256, 0, block.vtx[-1].vout[0].nValue])
# Relay the first 5 transactions from the block in advance
for tx in block.vtx[1:6]:
test_node.send_message(msg_tx(tx))
test_node.sync_with_ping()
# Make sure all transactions were accepted.
mempool = node.getrawmempool()
for tx in block.vtx[1:6]:
assert(tx.hash in mempool)
# Send compact block
comp_block = HeaderAndShortIDs()
comp_block.initialize_from_block(block, prefill_list=[0], use_witness=(version == 2))
test_node.send_and_ping(msg_cmpctblock(comp_block.to_p2p()))
absolute_indexes = []
with mininode_lock:
assert(test_node.last_getblocktxn is not None)
absolute_indexes = test_node.last_getblocktxn.block_txn_request.to_absolute()
assert_equal(absolute_indexes, [6, 7, 8, 9, 10])
# Now give an incorrect response.
# Note that it's possible for magmelldollard to be smart enough to know we're
# lying, since it could check to see if the shortid matches what we're
# sending, and eg disconnect us for misbehavior. If that behavior
# change were made, we could just modify this test by having a
# different peer provide the block further down, so that we're still
# verifying that the block isn't marked bad permanently. This is good
# enough for now.
msg = msg_blocktxn()
if version==2:
msg = msg_witness_blocktxn()
msg.block_transactions = BlockTransactions(block.sha256, [block.vtx[5]] + block.vtx[7:])
test_node.send_and_ping(msg)
# Tip should not have updated
assert_equal(int(node.getbestblockhash(), 16), block.hashPrevBlock)
# We should receive a getdata request
success = wait_until(lambda: test_node.last_getdata is not None, timeout=10)
assert(success)
assert_equal(len(test_node.last_getdata.inv), 1)
assert(test_node.last_getdata.inv[0].type == 2 or test_node.last_getdata.inv[0].type == 2|MSG_WITNESS_FLAG)
assert_equal(test_node.last_getdata.inv[0].hash, block.sha256)
# Deliver the block
if version==2:
test_node.send_and_ping(msg_witness_block(block))
else:
test_node.send_and_ping(msg_block(block))
assert_equal(int(node.getbestblockhash(), 16), block.sha256)
def test_getblocktxn_handler(self, node, test_node, version):
# magmelldollard will not send blocktxn responses for blocks whose height is
# more than 10 blocks deep.
MAX_GETBLOCKTXN_DEPTH = 10
chain_height = node.getblockcount()
current_height = chain_height
while (current_height >= chain_height - MAX_GETBLOCKTXN_DEPTH):
block_hash = node.getblockhash(current_height)
block = FromHex(CBlock(), node.getblock(block_hash, False))
msg = msg_getblocktxn()
msg.block_txn_request = BlockTransactionsRequest(int(block_hash, 16), [])
num_to_request = random.randint(1, len(block.vtx))
msg.block_txn_request.from_absolute(sorted(random.sample(range(len(block.vtx)), num_to_request)))
test_node.send_message(msg)
success = wait_until(lambda: test_node.last_blocktxn is not None, timeout=10)
assert(success)
[tx.calc_sha256() for tx in block.vtx]
with mininode_lock:
assert_equal(test_node.last_blocktxn.block_transactions.blockhash, int(block_hash, 16))
all_indices = msg.block_txn_request.to_absolute()
for index in all_indices:
tx = test_node.last_blocktxn.block_transactions.transactions.pop(0)
tx.calc_sha256()
assert_equal(tx.sha256, block.vtx[index].sha256)
if version == 1:
# Witnesses should have been stripped
assert(tx.wit.is_null())
else:
# Check that the witness matches
assert_equal(tx.calc_sha256(True), block.vtx[index].calc_sha256(True))
test_node.last_blocktxn = None
current_height -= 1
# Next request should send a full block response, as we're past the
# allowed depth for a blocktxn response.
block_hash = node.getblockhash(current_height)
msg.block_txn_request = BlockTransactionsRequest(int(block_hash, 16), [0])
with mininode_lock:
test_node.last_block = None
test_node.last_blocktxn = None
test_node.send_and_ping(msg)
with mininode_lock:
test_node.last_block.block.calc_sha256()
assert_equal(test_node.last_block.block.sha256, int(block_hash, 16))
assert_equal(test_node.last_blocktxn, None)
def test_compactblocks_not_at_tip(self, node, test_node):
# Test that requesting old compactblocks doesn't work.
MAX_CMPCTBLOCK_DEPTH = 5
new_blocks = []
for i in range(MAX_CMPCTBLOCK_DEPTH + 1):
test_node.clear_block_announcement()
new_blocks.append(node.generate(1)[0])
wait_until(test_node.received_block_announcement, timeout=30)
test_node.clear_block_announcement()
test_node.send_message(msg_getdata([CInv(4, int(new_blocks[0], 16))]))
success = wait_until(lambda: test_node.last_cmpctblock is not None, timeout=30)
assert(success)
test_node.clear_block_announcement()
node.generate(1)
wait_until(test_node.received_block_announcement, timeout=30)
test_node.clear_block_announcement()
with mininode_lock:
test_node.last_block = None
test_node.send_message(msg_getdata([CInv(4, int(new_blocks[0], 16))]))
success = wait_until(lambda: test_node.last_block is not None, timeout=30)
assert(success)
with mininode_lock:
test_node.last_block.block.calc_sha256()
assert_equal(test_node.last_block.block.sha256, int(new_blocks[0], 16))
# Generate an old compactblock, and verify that it's not accepted.
cur_height = node.getblockcount()
hashPrevBlock = int(node.getblockhash(cur_height-5), 16)
block = self.build_block_on_tip(node)
block.hashPrevBlock = hashPrevBlock
block.solve()
comp_block = HeaderAndShortIDs()
comp_block.initialize_from_block(block)
test_node.send_and_ping(msg_cmpctblock(comp_block.to_p2p()))
tips = node.getchaintips()
found = False
for x in tips:
if x["hash"] == block.hash:
assert_equal(x["status"], "headers-only")
found = True
break
assert(found)
# Requesting this block via getblocktxn should silently fail
# (to avoid fingerprinting attacks).
msg = msg_getblocktxn()
msg.block_txn_request = BlockTransactionsRequest(block.sha256, [0])
with mininode_lock:
test_node.last_blocktxn = None
test_node.send_and_ping(msg)
with mininode_lock:
assert(test_node.last_blocktxn is None)
def activate_segwit(self, node):
node.generate(144*3)
assert_equal(get_bip9_status(node, "segwit")["status"], 'active')
def test_end_to_end_block_relay(self, node, listeners):
utxo = self.utxos.pop(0)
block = self.build_block_with_transactions(node, utxo, 10)
[l.clear_block_announcement() for l in listeners]
# ToHex() won't serialize with witness, but this block has no witnesses
# anyway. TODO: repeat this test with witness tx's to a segwit node.
node.submitblock(ToHex(block))
for l in listeners:
wait_until(lambda: l.received_block_announcement(), timeout=30)
with mininode_lock:
for l in listeners:
assert(l.last_cmpctblock is not None)
l.last_cmpctblock.header_and_shortids.header.calc_sha256()
assert_equal(l.last_cmpctblock.header_and_shortids.header.sha256, block.sha256)
# Test that we don't get disconnected if we relay a compact block with valid header,
# but invalid transactions.
def test_invalid_tx_in_compactblock(self, node, test_node, use_segwit):
assert(len(self.utxos))
utxo = self.utxos[0]
block = self.build_block_with_transactions(node, utxo, 5)
del block.vtx[3]
block.hashMerkleRoot = block.calc_merkle_root()
if use_segwit:
# If we're testing with segwit, also drop the coinbase witness,
# but include the witness commitment.
add_witness_commitment(block)
block.vtx[0].wit.vtxinwit = []
block.solve()
# Now send the compact block with all transactions prefilled, and
# verify that we don't get disconnected.
comp_block = HeaderAndShortIDs()
comp_block.initialize_from_block(block, prefill_list=[0, 1, 2, 3, 4], use_witness=use_segwit)
msg = msg_cmpctblock(comp_block.to_p2p())
test_node.send_and_ping(msg)
# Check that the tip didn't advance
assert(int(node.getbestblockhash(), 16) is not block.sha256)
test_node.sync_with_ping()
# Helper for enabling cb announcements
# Send the sendcmpct request and sync headers
def request_cb_announcements(self, peer, node, version):
tip = node.getbestblockhash()
peer.get_headers(locator=[int(tip, 16)], hashstop=0)
msg = msg_sendcmpct()
msg.version = version
msg.announce = True
peer.send_and_ping(msg)
def test_compactblock_reconstruction_multiple_peers(self, node, stalling_peer, delivery_peer):
assert(len(self.utxos))
def announce_cmpct_block(node, peer):
utxo = self.utxos.pop(0)
block = self.build_block_with_transactions(node, utxo, 5)
cmpct_block = HeaderAndShortIDs()
cmpct_block.initialize_from_block(block)
msg = msg_cmpctblock(cmpct_block.to_p2p())
peer.send_and_ping(msg)
with mininode_lock:
assert(peer.last_getblocktxn is not None)
return block, cmpct_block
block, cmpct_block = announce_cmpct_block(node, stalling_peer)
for tx in block.vtx[1:]:
delivery_peer.send_message(msg_tx(tx))
delivery_peer.sync_with_ping()
mempool = node.getrawmempool()
for tx in block.vtx[1:]:
assert(tx.hash in mempool)
delivery_peer.send_and_ping(msg_cmpctblock(cmpct_block.to_p2p()))
assert_equal(int(node.getbestblockhash(), 16), block.sha256)
self.utxos.append([block.vtx[-1].sha256, 0, block.vtx[-1].vout[0].nValue])
# Now test that delivering an invalid compact block won't break relay
block, cmpct_block = announce_cmpct_block(node, stalling_peer)
for tx in block.vtx[1:]:
delivery_peer.send_message(msg_tx(tx))
delivery_peer.sync_with_ping()
cmpct_block.prefilled_txn[0].tx.wit.vtxinwit = [ CTxInWitness() ]
cmpct_block.prefilled_txn[0].tx.wit.vtxinwit[0].scriptWitness.stack = [ser_uint256(0)]
cmpct_block.use_witness = True
delivery_peer.send_and_ping(msg_cmpctblock(cmpct_block.to_p2p()))
assert(int(node.getbestblockhash(), 16) != block.sha256)
msg = msg_blocktxn()
msg.block_transactions.blockhash = block.sha256
msg.block_transactions.transactions = block.vtx[1:]
stalling_peer.send_and_ping(msg)
assert_equal(int(node.getbestblockhash(), 16), block.sha256)
def run_test(self):
# Setup the p2p connections and start up the network thread.
self.test_node = TestNode()
self.segwit_node = TestNode()
self.old_node = TestNode() # version 1 peer <--> segwit node
connections = []
connections.append(NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], self.test_node))
connections.append(NodeConn('127.0.0.1', p2p_port(1), self.nodes[1],
self.segwit_node, services=NODE_NETWORK|NODE_WITNESS))
connections.append(NodeConn('127.0.0.1', p2p_port(1), self.nodes[1],
self.old_node, services=NODE_NETWORK))
self.test_node.add_connection(connections[0])
self.segwit_node.add_connection(connections[1])
self.old_node.add_connection(connections[2])
NetworkThread().start() # Start up network handling in another thread
# Test logic begins here
self.test_node.wait_for_verack()
# We will need UTXOs to construct transactions in later tests.
self.make_utxos()
print("Running tests, pre-segwit activation:")
print("\tTesting SENDCMPCT p2p message... ")
self.test_sendcmpct(self.nodes[0], self.test_node, 1)
sync_blocks(self.nodes)
self.test_sendcmpct(self.nodes[1], self.segwit_node, 2, old_node=self.old_node)
sync_blocks(self.nodes)
print("\tTesting compactblock construction...")
self.test_compactblock_construction(self.nodes[0], self.test_node, 1, False)
sync_blocks(self.nodes)
self.test_compactblock_construction(self.nodes[1], self.segwit_node, 2, False)
sync_blocks(self.nodes)
print("\tTesting compactblock requests... ")
self.test_compactblock_requests(self.nodes[0], self.test_node, 1, False)
sync_blocks(self.nodes)
self.test_compactblock_requests(self.nodes[1], self.segwit_node, 2, False)
sync_blocks(self.nodes)
print("\tTesting getblocktxn requests...")
self.test_getblocktxn_requests(self.nodes[0], self.test_node, 1)
sync_blocks(self.nodes)
self.test_getblocktxn_requests(self.nodes[1], self.segwit_node, 2)
sync_blocks(self.nodes)
print("\tTesting getblocktxn handler...")
self.test_getblocktxn_handler(self.nodes[0], self.test_node, 1)
sync_blocks(self.nodes)
self.test_getblocktxn_handler(self.nodes[1], self.segwit_node, 2)
self.test_getblocktxn_handler(self.nodes[1], self.old_node, 1)
sync_blocks(self.nodes)
print("\tTesting compactblock requests/announcements not at chain tip...")
self.test_compactblocks_not_at_tip(self.nodes[0], self.test_node)
sync_blocks(self.nodes)
self.test_compactblocks_not_at_tip(self.nodes[1], self.segwit_node)
self.test_compactblocks_not_at_tip(self.nodes[1], self.old_node)
sync_blocks(self.nodes)
print("\tTesting handling of incorrect blocktxn responses...")
self.test_incorrect_blocktxn_response(self.nodes[0], self.test_node, 1)
sync_blocks(self.nodes)
self.test_incorrect_blocktxn_response(self.nodes[1], self.segwit_node, 2)
sync_blocks(self.nodes)
# End-to-end block relay tests
print("\tTesting end-to-end block relay...")
self.request_cb_announcements(self.test_node, self.nodes[0], 1)
self.request_cb_announcements(self.old_node, self.nodes[1], 1)
self.request_cb_announcements(self.segwit_node, self.nodes[1], 2)
self.test_end_to_end_block_relay(self.nodes[0], [self.segwit_node, self.test_node, self.old_node])
self.test_end_to_end_block_relay(self.nodes[1], [self.segwit_node, self.test_node, self.old_node])
print("\tTesting handling of invalid compact blocks...")
self.test_invalid_tx_in_compactblock(self.nodes[0], self.test_node, False)
self.test_invalid_tx_in_compactblock(self.nodes[1], self.segwit_node, False)
self.test_invalid_tx_in_compactblock(self.nodes[1], self.old_node, False)
print("\tTesting reconstructing compact blocks from all peers...")
self.test_compactblock_reconstruction_multiple_peers(self.nodes[1], self.segwit_node, self.old_node)
sync_blocks(self.nodes)
# Advance to segwit activation
print ("\nAdvancing to segwit activation\n")
self.activate_segwit(self.nodes[1])
print ("Running tests, post-segwit activation...")
print("\tTesting compactblock construction...")
self.test_compactblock_construction(self.nodes[1], self.old_node, 1, True)
self.test_compactblock_construction(self.nodes[1], self.segwit_node, 2, True)
sync_blocks(self.nodes)
print("\tTesting compactblock requests (unupgraded node)... ")
self.test_compactblock_requests(self.nodes[0], self.test_node, 1, True)
print("\tTesting getblocktxn requests (unupgraded node)...")
self.test_getblocktxn_requests(self.nodes[0], self.test_node, 1)
# Need to manually sync node0 and node1, because post-segwit activation,
# node1 will not download blocks from node0.
print("\tSyncing nodes...")
assert(self.nodes[0].getbestblockhash() != self.nodes[1].getbestblockhash())
while (self.nodes[0].getblockcount() > self.nodes[1].getblockcount()):
block_hash = self.nodes[0].getblockhash(self.nodes[1].getblockcount()+1)
self.nodes[1].submitblock(self.nodes[0].getblock(block_hash, False))
assert_equal(self.nodes[0].getbestblockhash(), self.nodes[1].getbestblockhash())
print("\tTesting compactblock requests (segwit node)... ")
self.test_compactblock_requests(self.nodes[1], self.segwit_node, 2, True)
print("\tTesting getblocktxn requests (segwit node)...")
self.test_getblocktxn_requests(self.nodes[1], self.segwit_node, 2)
sync_blocks(self.nodes)
print("\tTesting getblocktxn handler (segwit node should return witnesses)...")
self.test_getblocktxn_handler(self.nodes[1], self.segwit_node, 2)
self.test_getblocktxn_handler(self.nodes[1], self.old_node, 1)
# Test that if we submitblock to node1, we'll get a compact block
# announcement to all peers.
# (Post-segwit activation, blocks won't propagate from node0 to node1
# automatically, so don't bother testing a block announced to node0.)
print("\tTesting end-to-end block relay...")
self.request_cb_announcements(self.test_node, self.nodes[0], 1)
self.request_cb_announcements(self.old_node, self.nodes[1], 1)
self.request_cb_announcements(self.segwit_node, self.nodes[1], 2)
self.test_end_to_end_block_relay(self.nodes[1], [self.segwit_node, self.test_node, self.old_node])
print("\tTesting handling of invalid compact blocks...")
self.test_invalid_tx_in_compactblock(self.nodes[0], self.test_node, False)
self.test_invalid_tx_in_compactblock(self.nodes[1], self.segwit_node, True)
self.test_invalid_tx_in_compactblock(self.nodes[1], self.old_node, True)
print("\tTesting invalid index in cmpctblock message...")
self.test_invalid_cmpctblock_message()
if __name__ == '__main__':
CompactBlocksTest().main()
|
the-stack_0_8639 | import numpy as np
from yt.testing import \
fake_random_ds, \
fake_particle_ds, \
assert_equal, \
assert_rel_equal, \
assert_almost_equal
from yt import particle_filter
def setup():
from yt.config import ytcfg
ytcfg["yt","__withintesting"] = "True"
def test_extrema():
for nprocs in [1, 2, 4, 8]:
ds = fake_random_ds(16, nprocs = nprocs, fields = ("density",
"velocity_x", "velocity_y", "velocity_z"))
for sp in [ds.sphere("c", (0.25, 'unitary')), ds.r[0.5,:,:]]:
mi, ma = sp.quantities["Extrema"]("density")
assert_equal(mi, np.nanmin(sp["density"]))
assert_equal(ma, np.nanmax(sp["density"]))
dd = ds.all_data()
mi, ma = dd.quantities["Extrema"]("density")
assert_equal(mi, np.nanmin(dd["density"]))
assert_equal(ma, np.nanmax(dd["density"]))
sp = ds.sphere("max", (0.25, 'unitary'))
assert_equal(np.any(np.isnan(sp["radial_velocity"])), False)
mi, ma = dd.quantities["Extrema"]("radial_velocity")
assert_equal(mi, np.nanmin(dd["radial_velocity"]))
assert_equal(ma, np.nanmax(dd["radial_velocity"]))
def test_average():
for nprocs in [1, 2, 4, 8]:
ds = fake_random_ds(16, nprocs = nprocs, fields = ("density",))
for ad in [ds.all_data(), ds.r[0.5, :, :]]:
my_mean = ad.quantities["WeightedAverageQuantity"]("density", "ones")
assert_rel_equal(my_mean, ad["density"].mean(), 12)
my_mean = ad.quantities["WeightedAverageQuantity"]("density", "cell_mass")
a_mean = (ad["density"] * ad["cell_mass"]).sum() / ad["cell_mass"].sum()
assert_rel_equal(my_mean, a_mean, 12)
def test_variance():
for nprocs in [1, 2, 4, 8]:
ds = fake_random_ds(16, nprocs = nprocs, fields = ("density", ))
for ad in [ds.all_data(), ds.r[0.5, :, :]]:
my_std, my_mean = ad.quantities["WeightedVariance"]("density", "ones")
assert_rel_equal(my_mean, ad["density"].mean(), 12)
assert_rel_equal(my_std, ad["density"].std(), 12)
my_std, my_mean = ad.quantities["WeightedVariance"]("density", "cell_mass")
a_mean = (ad["density"] * ad["cell_mass"]).sum() / ad["cell_mass"].sum()
assert_rel_equal(my_mean, a_mean, 12)
a_std = np.sqrt((ad["cell_mass"] * (ad["density"] - a_mean)**2).sum() /
ad["cell_mass"].sum())
assert_rel_equal(my_std, a_std, 12)
def test_max_location():
for nprocs in [1, 2, 4, 8]:
ds = fake_random_ds(16, nprocs = nprocs, fields = ("density", ))
for ad in [ds.all_data(), ds.r[0.5, :, :]]:
mv, x, y, z = ad.quantities.max_location(("gas", "density"))
assert_equal(mv, ad["density"].max())
mi = np.argmax(ad["density"])
assert_equal(ad["x"][mi], x)
assert_equal(ad["y"][mi], y)
assert_equal(ad["z"][mi], z)
def test_min_location():
for nprocs in [1, 2, 4, 8]:
ds = fake_random_ds(16, nprocs = nprocs, fields = ("density", ))
for ad in [ds.all_data(), ds.r[0.5, :, :]]:
mv, x, y, z = ad.quantities.min_location(("gas", "density"))
assert_equal(mv, ad["density"].min())
mi = np.argmin(ad["density"])
assert_equal(ad["x"][mi], x)
assert_equal(ad["y"][mi], y)
assert_equal(ad["z"][mi], z)
def test_sample_at_min_field_values():
for nprocs in [1, 2, 4, 8]:
ds = fake_random_ds(16, nprocs = nprocs,
fields = ("density", "temperature", "velocity_x"))
for ad in [ds.all_data(), ds.r[0.5, :, :]]:
mv, temp, vm = ad.quantities.sample_at_min_field_values(
"density", ["temperature", "velocity_x"])
assert_equal(mv, ad["density"].min())
mi = np.argmin(ad["density"])
assert_equal(ad["temperature"][mi], temp)
assert_equal(ad["velocity_x"][mi], vm)
def test_sample_at_max_field_values():
for nprocs in [1, 2, 4, 8]:
ds = fake_random_ds(16, nprocs = nprocs,
fields = ("density", "temperature", "velocity_x"))
for ad in [ds.all_data(), ds.r[0.5, :, :]]:
mv, temp, vm = ad.quantities.sample_at_max_field_values(
"density", ["temperature", "velocity_x"])
assert_equal(mv, ad["density"].max())
mi = np.argmax(ad["density"])
assert_equal(ad["temperature"][mi], temp)
assert_equal(ad["velocity_x"][mi], vm)
def test_derived_quantities_with_particle_types():
ds = fake_particle_ds()
@particle_filter(requires=["particle_position_x"], filtered_type='all')
def low_x(pfilter,data):
return data['particle_position_x'].in_units('code_length')<0.5
ds.add_particle_filter('low_x')
ad=ds.all_data()
for ptype in ['all','low_x']:
#Check bulk velocity
bulk_vx=(ad[(ptype,'particle_mass')]*ad[(ptype,'particle_velocity_x')]/ad[(ptype,'particle_mass')].sum()).sum()
assert_almost_equal(ad.quantities.bulk_velocity(use_gas=False,use_particles=True,particle_type=ptype)[0],bulk_vx,5)
#Check center of mass
com_x=(ad[(ptype,'particle_mass')]*ad[(ptype,'particle_position_x')]/ad[(ptype,'particle_mass')].sum()).sum()
assert_almost_equal(ad.quantities.center_of_mass(use_gas=False,use_particles=True,particle_type=ptype)[0],com_x,5)
#Check angular momentum vector
l_x=(ad[(ptype,'particle_specific_angular_momentum_x')]*ad[(ptype,'particle_mass')]/ad[(ptype,'particle_mass')].sum()).sum()
assert_almost_equal(ad.quantities.angular_momentum_vector(use_gas=False,use_particles=True,particle_type=ptype)[0],l_x,5)
#Check spin parameter values
assert_almost_equal(ad.quantities.spin_parameter(use_gas=False,use_particles=True),655.7311454765503)
assert_almost_equal(ad.quantities.spin_parameter(use_gas=False,use_particles=True,particle_type='low_x'),1309.164886405665)
|
the-stack_0_8640 | from tensorflow.keras import Input
from tensorflow.keras.layers import Dropout, Dense
from tensorflow.keras.optimizers import Adam
from tensorflow.keras import regularizers
from tensorflow.keras.losses import SparseCategoricalCrossentropy
from graphgallery import floatx
from graphgallery.nn.models import TFKeras
class MLP(TFKeras):
def __init__(self, in_features, out_features,
hids=[16],
acts=['relu'],
dropout=0.5,
weight_decay=5e-4,
lr=0.01, bias=False):
if len(hids) != len(acts):
raise RuntimeError(f"Arguments 'hids' and 'acts' should have the same length."
" Or you can set both of them to `[]`.")
x = Input(batch_shape=[None, in_features],
dtype=floatx(), name='node_attr')
h = x
for hid, act in zip(hids, acts):
h = Dropout(rate=dropout)(h)
h = Dense(hid, use_bias=bias,
activation=act,
kernel_regularizer=regularizers.l2(weight_decay))(h)
h = Dropout(rate=dropout)(h)
h = Dense(out_features, use_bias=bias,
kernel_regularizer=regularizers.l2(weight_decay))(h)
super().__init__(inputs=x, outputs=h)
self.compile(loss=SparseCategoricalCrossentropy(from_logits=True),
optimizer=Adam(lr=lr), metrics=['accuracy'])
|
the-stack_0_8641 | import graphistry, os, pandas as pd, streamlit as st
from time import sleep
from components import GraphistrySt, URLParam
from css import all_css
from util import getChild
############################################
#
# DASHBOARD SETTINGS
#
############################################
# Controls how entrypoint.py picks it up
app_id = 'app_01'
logger = getChild(app_id)
urlParams = URLParam(app_id)
def info():
return {
'id': app_id,
'name': 'INTRO: fancy graph',
'enabled': True,
'tags': ['demo', 'demo_intro']
}
def run():
run_all()
############################################
#
# CUSTOM CSS
#
############################################
# Have fun!
def custom_css():
all_css() # our favorites
############################################
#
# SIDEBAR RENDER AERA
#
############################################
# Given URL params, render left sidebar form and return combined filter settings
##https://docs.streamlit.io/en/stable/api.html#display-interactive-widgets
def sidebar_area():
st.sidebar.title('Pick graph')
n_init = urlParams.get_field('N', 100)
n = st.sidebar.number_input('Number of nodes', min_value=10, max_value=100000, value=n_init, step=20)
urlParams.set_field('N', n)
base_url = os.environ['BASE_URL']
edges_df = pd.concat([
pd.DataFrame({
's': [x for x in range(n)],
'd': [(x + 1) % n for x in range(n)],
'link': [
'<a href="' + base_url + '/?view_index=app1&app1_N=' + str(x % n) + '">' + str(x % n) + " nodes</a>"
for x in range(n)
]
}),
pd.DataFrame({
's': [x for x in range(n)],
'd': [(x + 6) % n for x in range(n)],
'link': [
'<a href="' + base_url + '/?view_index=app1&app1_N=' + str(x % n) + '">' + str(x % n) + " nodes</a>"
for x in range(n)
]
})
], sort=False, ignore_index=True)
st.sidebar.title("Filter")
option_to_label = {
'all': 'All',
'odd': 'Odds',
'even': 'Evens'
}
filter_by_node_type_init = urlParams.get_field('filter_by_type', default='all')
filter_by_node_type = st.sidebar.selectbox('Filter nodes by:',
('all', 'odd', 'even'),
index=('all', 'odd', 'even').index(filter_by_node_type_init),
format_func=(lambda option: option_to_label[option]))
urlParams.set_field('filter_by_type', filter_by_node_type)
filter_by_node_range_init = (
urlParams.get_field('filter_by_node_range_min', default=0),
urlParams.get_field('filter_by_node_range_max', default=n))
logger.info('filter_by_node_range_init: %s :: %s', filter_by_node_range_init, type(filter_by_node_range_init))
filter_by_node_range = st.sidebar.slider('Filter for nodes in range:',
min_value=0, max_value=n, value=filter_by_node_range_init, step=1)
urlParams.set_field('filter_by_node_range_min', filter_by_node_range[0])
urlParams.set_field('filter_by_node_range_max', filter_by_node_range[1])
return {
'n': n,
'edges_df': edges_df,
'node_type': filter_by_node_type,
'node_range': filter_by_node_range
}
############################################
#
# FILTER PIPELINE
#
############################################
# Given filter settings, generate/cache/return dataframes & viz
@st.cache(suppress_st_warning=True, allow_output_mutation=True)
def run_filters(node_type, node_range, edges_df, n):
filtered_edges_df = edges_df
if node_type == 'all':
pass
elif node_type == 'odd':
filtered_edges_df = filtered_edges_df[ filtered_edges_df['s'] % 2 == 1 ]
filtered_edges_df = filtered_edges_df[ filtered_edges_df['d'] % 2 == 1 ]
elif node_type == 'even':
filtered_edges_df = filtered_edges_df[ filtered_edges_df['s'] % 2 == 0 ]
filtered_edges_df = filtered_edges_df[ filtered_edges_df['d'] % 2 == 0 ]
else:
raise Exception('Unknown filter1 option result: %s' % node_type)
if node_range[0] > 0:
filtered_edges_df = filtered_edges_df[ filtered_edges_df['s'] >= node_range[0] ]
filtered_edges_df = filtered_edges_df[ filtered_edges_df['d'] >= node_range[0] ]
if node_range[1] <= n:
filtered_edges_df = filtered_edges_df[ filtered_edges_df['s'] <= node_range[1] ]
filtered_edges_df = filtered_edges_df[ filtered_edges_df['d'] <= node_range[1] ]
#include viz generation as part of cache
url = plot_url(filtered_edges_df, n)
return {
'edges_df': filtered_edges_df,
'url': url
}
############################################
#
# VIZ
#
############################################
def plot_url(edges_df, n):
nodes_df = pd.DataFrame({
'n': pd.concat([edges_df['s'], edges_df['d']]).unique()
})
nodes_df['nc'] = nodes_df['n'].apply(lambda v: 0x01000000 * round(255 * v / n))
logger.info('Starting graphistry plot')
if not GraphistrySt().test_login():
return ''
url = graphistry\
.bind(source="s", destination="d")\
.edges(edges_df)\
.nodes(nodes_df)\
.bind(node='n', point_color='nc')\
.settings(url_params={
'pointSize': 0.3,
'splashAfter': 'false',
'bg': '%23' + 'f0f2f6'
})\
.plot(render=False)
logger.info('Generated viz, got back urL: %s', url)
return url
############################################
#
# MAIN RENDER AERA
#
############################################
# Given configured filters and computed results (cached), render
def main_area(edges_df, url):
logger.debug('rendering main area, with url: %s', url)
GraphistrySt().render_url(url)
############################################
#
# Putting it all together
#
############################################
def run_all():
custom_css()
try:
# Render sidebar and get current settings
sidebar_filters = sidebar_area()
logger.debug('sidebar_filters: %s', sidebar_filters)
# Compute filter pipeline (with auto-caching based on filter setting inputs)
# Selective mark these as URL params as well
filter_pipeline_result = run_filters(**sidebar_filters)
# Render main viz area based on computed filter pipeline results and sidebar settings
main_area(**filter_pipeline_result)
except Exception as exn:
st.write('Error loading dashboard')
st.write(exn)
|
the-stack_0_8644 | import gc
import os
from os.path import join as pjoin
import sys
from argparse import ArgumentTypeError
from pprint import pprint
import yaml
from datetime import datetime
import logging
import numpy as np
import numpy.random
import tensorflow as tf
from PIL import Image
import matplotlib as mpl
from matplotlib import colors
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.python.client import device_lib
logger = logging.getLogger("MCDose."+__name__)
def limited_float(low, high):
"""argparse string to float with requirement on allowable range of values"""
def convert(x):
try:
x = float(x)
except ValueError:
raise argparse.ArgumentTypeError("{} is not a floating point literal".format(x))
if x < low or x > high:
raise argparse.ArgumentTypeError("{} not in allowable range [{}, {}]".format(x, low, high))
return x
return convert
def randbool(p_true=0.5):
p_true = max(0.0, min(1.0, p_true))
return bool(np.random.rand()<p_true)
def augment_data(samples, labels):
for mode in range(8):
if randbool(0.2):
samples = data_augmentation(samples, mode)
labels = data_augmentation(labels, mode)
return samples, labels
def data_augmentation(image, mode):
if mode == 0:
# original
return image
elif mode == 1:
# flip up and down
return np.flipud(image)
elif mode == 2:
# rotate counterwise 90 degree
return np.rot90(image)
elif mode == 3:
# rotate 90 degree and flip up and down
image = np.rot90(image)
return np.flipud(image)
elif mode == 4:
# rotate 180 degree
return np.rot90(image, k=2)
elif mode == 5:
# rotate 180 degree and flip
image = np.rot90(image, k=2)
return np.flipud(image)
elif mode == 6:
# rotate 270 degree
return np.rot90(image, k=3)
elif mode == 7:
# rotate 270 degree and flip
image = np.rot90(image, k=3)
return np.flipud(image)
def load_images(filelist):
# pixel value range 0-255
if not isinstance(filelist, list):
im = Image.open(filelist).convert('L')
return np.array(im).reshape(1, im.size[1], im.size[0], 1)
data = []
for file in filelist:
im = Image.open(file).convert('L')
data.append(np.array(im).reshape(1, im.size[1], im.size[0], 1))
return data
def load_bin(fname, size, add_channel_axis=False, norm=False):
"""loads binary double-precision data in ZYX order and returns an array in XZY order
note: only works with 3d array"""
with open(fname, 'rb') as fd:
excepts = []
for t in [np.float64, np.float32]:
try:
arr = np.frombuffer(fd.read(), dtype=t)
arr = np.reshape(arr, size[::-1])
break
except Exception as e:
excepts.append(e)
if not (isinstance(arr, np.ndarray) and arr.size):
raise RuntimeError(str('\n\n'.join([str(e) for e in excepts])))
arr = arr.transpose(2,0,1).copy("C")
if norm:
arr /= np.max(arr)
if add_channel_axis:
arr = np.expand_dims(arr, axis=arr.ndim)
return arr
def save_bin(fname, arr):
"""takes array in XZY order and saves to binary file as double-precision in ZYX order
note: only works with 3d array"""
arr = arr.transpose(1,2,0).copy("C")
with open(fname, 'wb') as fd:
fd.write(arr)
def save_as_image(filepath, arr, cmap=None, scale=1):
_min = np.min(np.min(arr, axis=0), axis=0)
_max = np.max(np.max(arr, axis=0), axis=0)
outimg = (arr-_min)/(_max-_min)
if cmap is not None:
outimg = cmap(outimg)
im = Image.fromarray(np.uint8(outimg*255))
im = im.resize((scale*im.size[0], scale*im.size[1])) # make the image larger
im.save(filepath)
def save_bin_slices(filepath, low_var, high_var, out_low_var, array_spacing=0):
scale = 6
with open(filepath+'.bin', 'wb') as f:
output = np.zeros((low_var.shape[0], low_var.shape[1], 2))
spacer = np.max(output)*np.ones((low_var.shape[0], low_var.shape[1], array_spacing))
output = np.concatenate((output,high_var), axis=2)
output = np.concatenate((output,spacer), axis=2)
output = np.concatenate((output,low_var), axis=2)
output = np.concatenate((output,spacer), axis=2)
output = np.concatenate((output,out_low_var), axis=2)
output = output.transpose(1,2,0)
output = output.copy(order='C')
f.write(output) # save to bin
save_as_image(filepath+'.png', output, cmap=mpl.cm.get_cmap('viridis'), scale=scale)
def tf_split_var(mode,images, percent, size, rank=4):
k = tf.cast(tf.floor(tf.scalar_mul(percent, tf.cast(tf.size(input=images), tf.float32))), tf.int32)
if mode =='low':
values, idx = tf.nn.top_k(-images,k)
elif mode == 'high':
values, idx = tf.nn.top_k(images,k)
mask = tf.compat.v1.sparse_to_dense(idx, tf.shape(input=images), sparse_values=0, default_value=1)
images = tf.multiply(images,tf.cast(mask, tf.float32))
if rank == 3:
# The input is a single image with shape [height, width, channels].
# Calculate the difference of neighboring pixel-values.
# The images are shifted one pixel along the height and width by slicing.
pixel_dif1 = images[1:, :, :] - images[:-1, :, :]
pixel_dif2 = images[:, 1:, :] - images[:, :-1, :]
# Sum for all axis. (None is an alias for all axis.)
sum_axis = None
elif rank == 4:
# The input is a batch of images with shape:
# [batch, height, width, channels].
# Calculate the difference of neighboring pixel-values.
# The images are shifted one pixel along the height and width by slicing.
pixel_dif1 = images[:, 1:, :, :] - images[:, :-1, :, :]
pixel_dif2 = images[:, :, 1:, :] - images[:, :, :-1, :]
# Only sum for the last 3 axis.
# This results in a 1-D tensor with the total variation for each image.
sum_axis = [1, 2, 3]
else:
raise ValueError('\'images\' must be either 3 or 4-dimensional.')
# Calculate the total variation by taking the absolute value of the
# pixel-differences and summing over the appropriate axis.
tot_var = (
tf.reduce_sum(input_tensor=tf.abs(pixel_dif1), axis=sum_axis) +
tf.reduce_sum(input_tensor=tf.abs(pixel_dif2), axis=sum_axis))
return tot_var
class BatchConstructor():
"""Construct batches in sequence from a set of example (input, label) paired tensors """
def __init__(self, inputs, labels):
""" note: currently only handles 2D inputs. 3D extension should be simple
Args:
inputs (np.ndarray[N,H,W,C])
labels (np.ndarray[N,H,W,C])
"""
self.inputs = inputs
self.labels = labels
self.mark = 0
def reset(self):
"""re-init the array of available example indices"""
self.mark=0
def iter_batches(self, batch_size):
"""construct batch in NHWC format where the first axis (N) is constucted of examples drawn from list of unused examples"""
remain = len(self.labels) - self.mark
mark = 0
while remain > 0:
_batch_size = min(remain, batch_size)
yield (self.inputs[mark:mark+_batch_size,], self.labels[mark:mark+_batch_size,])
remain -= _batch_size
mark += _batch_size
class RandomBatchConstructor():
"""Construct batches randomly from a set of example (input, label) paired tensors """
def __init__(self, inputs, labels):
""" note: currently only handles 2D inputs. 3D extension should be simple
Args:
inputs (np.ndarray[N,H,W,C])
labels (np.ndarray[N,H,W,C])
"""
self.inputs = inputs
self.labels = labels
self.randorder = np.arange(self.inputs.shape[0])
self.mark = 0
self.initialized = False # lazy loading of index
def reset(self):
"""re-init the array of available example indices"""
self.initialized = True
np.random.shuffle(self.randorder)
self.mark = 0
def make_batch(self, batch_size):
"""construct batch in NHWC format where the first axis (N) is constucted of random examples drawn from list of unused examples"""
if not self.initialized:
self.reset()
remaining = len(self.randorder) - self.mark
_batch_size = min(remaining, batch_size)
if remaining < _batch_size:
raise RuntimeError('There are not enough examples ({:d}) to fill the requested batch ({:d})'.format(remaining, _batch_size))
selection = self.randorder[self.mark:self.mark+_batch_size]
self.mark += _batch_size
return (self.inputs[selection,], self.labels[selection,])
class RandomBatchConstructor_MultiTensor():
"""Construct batches randomly from a set of example (input, label) paired tensors. This class differs from
RandomBatchConstructor in that it handles datasets consisting of more than one tensor of different dims"""
def __init__(self, inputs, labels):
""" note: currently only handles 2D inputs. 3D extension should be simple
Args:
inputs ([np.ndarray[N,H,W,C], ...])
labels ([np.ndarray[N,H,W,C], ...])
"""
self.inputs = inputs
self.labels = labels
self.index = [[]]*len(inputs)
self.initialized = False # lazy loading of index
def reset(self):
"""re-init the array of available example indices"""
self.initialized = True
self.index = []
for input in self.inputs:
self.index.append( list(range(input.shape[0])) )
def make_batch(self, batch_size, reuse=False):
"""construct batch in NHWC format where the first axis (N) is constructed of random examples drawn from list of unused examples"""
if not self.initialized:
self.reset()
# randomly select a dataset tensor
unseen = list(range(len(self.inputs)))
while True:
if not len(unseen):
raise RuntimeError('There are no remaining examples from which to fill the requested batch')
tidx = np.random.choice(unseen)
if len(self.index[tidx]):
break
unseen.remove(tidx)
_batch_size = min(len(self.index[tidx]), batch_size)
if len(self.index[tidx]) < _batch_size:
raise RuntimeError('There are not enough examples ({:d}) to fill the requested batch ({:d})'.format(len(self.index[tidx]), _batch_size))
select = np.random.choice(range(len(self.index[tidx])), _batch_size, replace=False)
if not reuse:
for idx in sorted(select, reverse=True):
del self.index[tidx][idx]
return (self.inputs[tidx][select,], self.labels[tidx][select,])
def get_available_gpus():
with tf.compat.v1.Session(config=tf.compat.v1.ConfigProto(gpu_options=tf.compat.v1.GPUOptions(per_process_gpu_memory_fraction=0.01, allow_growth=True))) as sess:
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.WARN)
local_device_protos = device_lib.list_local_devices()
devs = [x.name for x in local_device_protos if x.device_type=='GPU']
return devs
def get_unique_run_name(base, timestamp=False):
"""get unique directory name with lowest integer prefix"""
runs = [int(x.split('-')[0]) for x in os.listdir(base) if os.path.isdir(pjoin(base, x))]
runid = max(runs)+1 if len(runs) else 1
runname = '{:04d}'.format(runid)
if timestamp:
timestamp = datetime.strftime('%Y%m%d-%H%M%S')
runname += '-' + timestamp
return runname
def save_config(dest, config):
assert os.path.isdir(dest)
dest = pjoin(dest, 'config.yml')
with open(dest, 'w') as fd:
yaml.safe_dump(config, fd)
def load_config(src):
if os.path.isdir(src):
src = pjoin(src, 'config.yml')
with open(src, 'r') as fd:
config = yaml.safe_load(fd)
logger.info('Config loaded from "{}"'.format(src))
return config
def combine_config(c1, c2):
d = c1.copy()
for k, v in c2.items():
if k not in d or d[k] is None:
d[k] = v
return d
|
the-stack_0_8646 | from unittest import TestCase
from shutil import copyfile
import os
from pysumma.Simulation import Simulation
class TestSimulation(TestCase):
# Create a new fileManager.txt file with the correct file paths for the system it's run on
my_path = os.path.abspath(os.path.dirname(__file__))
filename = 'fileManager.txt'
filepath = os.path.join(my_path, filename)
filename2 = 'tmp_{}'.format(filename)
filepath2 = os.path.join(my_path, filename2)
copyfile(filepath, filepath2)
with open(filepath2, 'r') as infile:
text = infile.readlines()
out_text = []
# Replaces the fileManager.txt placeholders with the paths/values for this system
for line in text:
if '{file version}' in line:
line = line.replace('{file version}', "'SUMMA FILE_MANAGER_V1.0'")
if '{settings path}' in line:
line = line.replace('{settings path}', "'" + my_path + "/'")
if '{input path}' in line:
line = line.replace('{input path}', "'" + my_path + "/'")
if '{output path}' in line:
line = line.replace('{output path}', "'" + my_path + "/'")
out_text.append(line)
with open(filepath2, 'w') as outfile:
outfile.writelines(out_text)
Simulation_obj = Simulation(filepath2)
def read_value_from_file(self, setting_name):
with open(self.filepath2) as fileManager_file:
for line in fileManager_file:
if setting_name in line:
return line.split("!")[0].strip().strip("'")
def get_filepath_from_value(self, setting_name):
value = self.read_value_from_file(setting_name)
if not value.endswith('/'):
return "/".join(value.split('/')[:-1]) + "/"
else:
return value
def get_filename_from_value(self, setting_name):
value = self.read_value_from_file(setting_name)
return value.split('/')[-1]
def read_text_from_file(self, setting_name):
with open(self.read_value_from_file(setting_name)) as file:
return ''.join(file.readlines())
# Test the setting_path, input_path, and output_path FM objects (they represent paths, not files)
def test_path_FM_objects(self):
# Are the names, values, filepaths, and filenames correct upon FileManagerOption object instantiation?
fileManagerObject = self.Simulation_obj.setting_path
setting_name = 'setting_path'
self.assertEqual(fileManagerObject.name, setting_name)
self.assertEqual(fileManagerObject.value, self.read_value_from_file(setting_name))
self.assertEqual(fileManagerObject.filepath, self.get_filepath_from_value(setting_name))
self.assertEqual(fileManagerObject.filename, self.get_filename_from_value(setting_name))
fileManagerObject = self.Simulation_obj.input_path
setting_name = 'input_path'
self.assertEqual(fileManagerObject.name, setting_name)
self.assertEqual(fileManagerObject.value, self.read_value_from_file(setting_name))
self.assertEqual(fileManagerObject.filepath, self.get_filepath_from_value(setting_name))
self.assertEqual(fileManagerObject.filename, self.get_filename_from_value(setting_name))
fileManagerObject = self.Simulation_obj.output_path
setting_name = 'output_path'
self.assertEqual(fileManagerObject.name, setting_name)
self.assertEqual(fileManagerObject.value, self.read_value_from_file(setting_name))
self.assertEqual(fileManagerObject.filepath, self.get_filepath_from_value(setting_name))
self.assertEqual(fileManagerObject.filename, self.get_filename_from_value(setting_name))
# Save the old path values
old_setting_path_value = self.Simulation_obj.setting_path.value
old_input_path_value = self.Simulation_obj.input_path.value
old_output_path_value = self.Simulation_obj.output_path.value
# Set new values for the path variables
new_setting_path_value = self.Simulation_obj.setting_path.value + "settingsample/"
new_input_path_value = self.Simulation_obj.input_path.value + "inputsample/"
new_output_path_value = self.Simulation_obj.output_path.value + "outputsample/"
self.Simulation_obj.setting_path.value = new_setting_path_value
self.Simulation_obj.input_path.value = new_input_path_value
self.Simulation_obj.output_path.value = new_output_path_value
# Did ModelOutput change them in the file?
self.assertEqual(self.read_value_from_file('setting_path'), new_setting_path_value)
self.assertEqual(self.read_value_from_file('input_path'), new_input_path_value)
self.assertEqual(self.read_value_from_file('output_path'), new_output_path_value)
# Change the values back
self.Simulation_obj.setting_path.value = old_setting_path_value
self.Simulation_obj.input_path.value = old_input_path_value
self.Simulation_obj.output_path.value = old_output_path_value
# Are the values updated correctly?
self.assertEqual(self.read_value_from_file('setting_path'), old_setting_path_value)
self.assertEqual(self.read_value_from_file('input_path'), old_input_path_value)
self.assertEqual(self.read_value_from_file('output_path'), old_output_path_value)
def test_FM_ModelOutput_obj(self):
# Make sure that the ModelOutput object can read from the master file
self.assertNotEqual([], self.Simulation_obj.modeloutput_obj.read_master_file())
# Add a variable that's already in the file
with self.assertRaises(ValueError):
self.Simulation_obj.modeloutput_obj.add_variable('pptrate')
# Add a valid variable and make sure it's in the file
self.Simulation_obj.modeloutput_obj.add_variable('aquiferScaleFactor')
self.assertIn('aquiferScaleFactor', self.Simulation_obj.modeloutput_obj.read_variables_from_file())
# Remove that variable, make sure it isn't in the file
self.Simulation_obj.modeloutput_obj.remove_variable('aquiferScaleFactor')
self.assertNotIn('aquiferScaleFactor', self.Simulation_obj.modeloutput_obj.read_variables_from_file())
|
the-stack_0_8647 | ALPHABET = "abcdefghijklmnopqrstuvwxyz"
def increment(pwd):
incremented = ""
pos_not_z = len(pwd) - 1
while pwd[pos_not_z] == "z":
incremented = "a" + incremented
pos_not_z -= 1
incremented = pwd[:pos_not_z] + ALPHABET[ALPHABET.index(pwd[pos_not_z]) + 1] + incremented
return incremented
def valid(pwd):
if any([forbidden in pwd for forbidden in ["i", "l", "o"]]):
return False
# check for a sequence of 3 consecutive letters
contains_seq = False
for i in range(0, 6):
if pwd[i:i+3] in ALPHABET:
contains_seq = True
break
if not contains_seq:
return False
# check for 2 pairs
pairs = 0
pos = 0
while pos <= 6:
if pwd[pos] == pwd[pos + 1]:
pairs += 1
pos += 2
else:
pos += 1
return pairs >= 2
def get_next_valid(pwd):
pwd = increment(pwd)
while not valid(pwd):
pwd = increment(pwd)
return pwd
def solve(current_pwd):
return get_next_valid(current_pwd)
def parse(file_name):
with open(file_name, "r") as f:
return f.readline().strip()
if __name__ == '__main__':
print(solve(parse("sample.txt")))
|
the-stack_0_8648 | """
(C) Copyright 2021 IBM Corp.
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 writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Created on June 30, 2021
"""
import logging
import os
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data.dataloader import DataLoader
import pathlib
from fuse.data.dataset.dataset_base import FuseDatasetBase
from fuse.metrics.classification.metric_roc_curve import FuseMetricROCCurve
from fuse.metrics.classification.metric_auc import FuseMetricAUC
from fuse.analyzer.analyzer_default import FuseAnalyzerDefault
from fuse.data.sampler.sampler_balanced_batch import FuseSamplerBalancedBatch
from fuse.losses.loss_default import FuseLossDefault
from fuse.managers.callbacks.callback_metric_statistics import FuseMetricStatisticsCallback
from fuse.managers.callbacks.callback_tensorboard import FuseTensorboardCallback
from fuse.managers.callbacks.callback_time_statistics import FuseTimeStatisticsCallback
from fuse.managers.manager_default import FuseManagerDefault
from fuse.utils.utils_gpu import FuseUtilsGPU
from fuse.utils.utils_logger import fuse_logger_start
from fuse.models.heads.head_1d_classifier import FuseHead1dClassifier
from fuse_examples.classification.prostate_x.backbone_3d_multichannel import Fuse_model_3d_multichannel,ResNet
from fuse_examples.classification.prostate_x.patient_data_source import FuseProstateXDataSourcePatient
from fuse_examples.classification.duke_breast_cancer.dataset import duke_breast_cancer_dataset
from fuse_examples.classification.duke_breast_cancer.tasks import FuseTask
##########################################
# Output Paths
# ##########################################
# # TODO: path to save model
root_path = '.'
# TODO: path for duke data
# Download instructions can be found in README
root_data = './Data/Duke-Breast-Cancer-MRI/manifest-1607053360376/'
PATHS = {'force_reset_model_dir': False,
# If True will reset model dir automatically - otherwise will prompt 'are you sure' message.
'model_dir': root_path + '/my_model/',
'cache_dir': root_path + '/my_cache/',
'inference_dir': root_path + '/my_model/inference/',
'analyze_dir': root_path + '/my_model/analyze/',
'data_dir':root_path,
'data_path' : root_data + 'Duke-Breast-Cancer-MRI',
'metadata_path': root_data + 'metadata.csv',
'ktrans_path': '',
}
#################################
# Train Template
#################################
##########################################
# Train Common Params
##########################################
# ============
# Data
# ============
TRAIN_COMMON_PARAMS = {}
TRAIN_COMMON_PARAMS['db_name'] = 'DUKE'
TRAIN_COMMON_PARAMS['partition_version'] = '11102021TumorSize'
TRAIN_COMMON_PARAMS['fold_no'] = 0
TRAIN_COMMON_PARAMS['data.batch_size'] = 50
TRAIN_COMMON_PARAMS['data.train_num_workers'] = 8
TRAIN_COMMON_PARAMS['data.validation_num_workers'] = 8
# ===============
# Manager - Train
# ===============
TRAIN_COMMON_PARAMS['manager.train_params'] = {
'num_gpus': 1,
'num_epochs': 150,
'virtual_batch_size': 1, # number of batches in one virtual batch
'start_saving_epochs': 120, # first epoch to start saving checkpoints from
'gap_between_saving_epochs': 1, # number of epochs between saved checkpoint
}
TRAIN_COMMON_PARAMS['manager.best_epoch_source'] = [
{
'source': 'metrics.auc.macro_avg', # can be any key from losses or metrics dictionaries
'optimization': 'max', # can be either min/max
'on_equal_values': 'better',
# can be either better/worse - whether to consider best epoch when values are equal
},
]
TRAIN_COMMON_PARAMS['manager.learning_rate'] = 1e-5
TRAIN_COMMON_PARAMS['manager.weight_decay'] = 1e-3
TRAIN_COMMON_PARAMS['manager.dropout'] = 0.5
TRAIN_COMMON_PARAMS['manager.momentum'] = 0.9
TRAIN_COMMON_PARAMS['manager.resume_checkpoint_filename'] = None
TRAIN_COMMON_PARAMS['num_backbone_features_imaging'] = 512
# in order to add relevant tabular feature uncomment:
# num_backbone_features_clinical, post_concat_inputs,post_concat_model
TRAIN_COMMON_PARAMS['num_backbone_features_clinical'] = None#256
TRAIN_COMMON_PARAMS['post_concat_inputs'] = None#[('data.clinical_features',9),]
TRAIN_COMMON_PARAMS['post_concat_model'] = None#(256,256)
if TRAIN_COMMON_PARAMS['num_backbone_features_clinical'] is None:
TRAIN_COMMON_PARAMS['num_backbone_features'] = TRAIN_COMMON_PARAMS['num_backbone_features_imaging']
else:
TRAIN_COMMON_PARAMS['num_backbone_features'] = \
TRAIN_COMMON_PARAMS['num_backbone_features_imaging']+TRAIN_COMMON_PARAMS['num_backbone_features_clinical']
# classification_task:
# supported tasks are: 'Staging Tumor Size','Histology Type','is High Tumor Grade Total','PCR'
TRAIN_COMMON_PARAMS['classification_task'] = 'Staging Tumor Size'
TRAIN_COMMON_PARAMS['task'] = FuseTask(TRAIN_COMMON_PARAMS['classification_task'], 0)
TRAIN_COMMON_PARAMS['class_num'] = TRAIN_COMMON_PARAMS['task'].num_classes()
# backbone parameters
TRAIN_COMMON_PARAMS['backbone_model_dict'] = \
{'input_channels_num': 1,
}
def train_template(paths: dict, train_common_params: dict):
# ==============================================================================
# Logger
# ==============================================================================
fuse_logger_start(output_path=paths['model_dir'], console_verbose_level=logging.INFO,
list_of_source_files=[])
lgr = logging.getLogger('Fuse')
lgr.info('Fuse Train', {'attrs': ['bold', 'underline']})
lgr.info(f'model_dir={paths["model_dir"]}', {'color': 'magenta'})
lgr.info(f'cache_dir={paths["cache_dir"]}', {'color': 'magenta'})
#Data
train_dataset,validation_dataset = duke_breast_cancer_dataset(paths, train_common_params, lgr)
## Create dataloader
lgr.info(f'- Create sampler:')
sampler = FuseSamplerBalancedBatch(dataset=train_dataset,
balanced_class_name='data.ground_truth',
num_balanced_classes=train_common_params['class_num'],
batch_size=train_common_params['data.batch_size'],
balanced_class_weights=
[int(train_common_params['data.batch_size']/train_common_params['class_num'])] * train_common_params['class_num'],
use_dataset_cache=True)
lgr.info(f'- Create sampler: Done')
# ## Create dataloader
train_dataloader = DataLoader(dataset=train_dataset,
batch_sampler=sampler,
collate_fn=train_dataset.collate_fn,
num_workers=train_common_params['data.train_num_workers'])
lgr.info(f'Train Data: Done', {'attrs': 'bold'})
validation_dataloader = DataLoader(dataset=validation_dataset,
shuffle=False,
drop_last=False,
batch_size=train_common_params['data.batch_size'],
num_workers=train_common_params['data.validation_num_workers'],
collate_fn=validation_dataset.collate_fn)
lgr.info(f'Validation Data: Done', {'attrs': 'bold'})
# ==============================================================================
# Model
# ==============================================================================
lgr.info('Model:', {'attrs': 'bold'})
model = Fuse_model_3d_multichannel(
conv_inputs=(('data.input', 1),),
backbone= ResNet(ch_num=TRAIN_COMMON_PARAMS['backbone_model_dict']['input_channels_num']),
# since backbone resnet contains pooling and fc, the feature output is 1D,
# hence we use FuseHead1dClassifier as classification head
heads=[
FuseHead1dClassifier(head_name='isLargeTumorSize',
conv_inputs=[('model.backbone_features', train_common_params['num_backbone_features'])],
post_concat_inputs = train_common_params['post_concat_inputs'],
post_concat_model = train_common_params['post_concat_model'],
dropout_rate=0.25,
shared_classifier_head=None,
layers_description=None,
num_classes=2),
]
)
lgr.info('Model: Done', {'attrs': 'bold'})
# ====================================================================================
# Loss
# ====================================================================================
lgr.info('Losses: CrossEntropy', {'attrs': 'bold'})
losses = {
'cls_loss': FuseLossDefault(pred_name='model.logits.isLargeTumorSize',
target_name='data.ground_truth',
callable=F.cross_entropy, weight=1.0),
}
# ====================================================================================
# Metrics
# ====================================================================================
lgr.info('Metrics:', {'attrs': 'bold'})
metrics = {
'auc': FuseMetricAUC(pred_name='model.output.isLargeTumorSize', target_name='data.ground_truth',
class_names=train_common_params['task'].class_names()),
}
()# =====================================================================================
# Callbacks
# =====================================================================================
callbacks = [
FuseTensorboardCallback(model_dir=paths['model_dir']), # save statistics for tensorboard
FuseMetricStatisticsCallback(output_path=paths['model_dir'] + "/metrics.csv"),
# save statistics for tensorboard in a csv file
FuseTimeStatisticsCallback(num_epochs=train_common_params['manager.train_params']['num_epochs'],
load_expected_part=0.1) # time profiler
]
# =====================================================================================
# Manager - Train
# =====================================================================================
lgr.info('Train:', {'attrs': 'bold'})
# create optimizer
optimizer = optim.Adam(model.parameters(),
lr=train_common_params['manager.learning_rate'],
weight_decay=train_common_params['manager.weight_decay'])
#
# create scheduler
scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, patience=3, verbose=True)
# train from scratch
manager = FuseManagerDefault(output_model_dir=paths['model_dir'], force_reset=paths['force_reset_model_dir'])
# Providing the objects required for the training process.
manager.set_objects(net=model,
optimizer=optimizer,
losses=losses,
metrics=metrics,
best_epoch_source=train_common_params['manager.best_epoch_source'],
lr_scheduler=scheduler,
callbacks=callbacks,
train_params=train_common_params['manager.train_params'])
## Continue training
if train_common_params['manager.resume_checkpoint_filename'] is not None:
# Loading the checkpoint including model weights, learning rate, and epoch_index.
manager.load_checkpoint(checkpoint=train_common_params['manager.resume_checkpoint_filename'], mode='train')
# Start training
manager.train(train_dataloader=train_dataloader,
validation_dataloader=validation_dataloader)
lgr.info('Train: Done', {'attrs': 'bold'})
######################################
# Inference Common Params
######################################
INFER_COMMON_PARAMS = {}
INFER_COMMON_PARAMS['partition_version'] = '11102021TumorSize'
INFER_COMMON_PARAMS['db_name'] = 'DUKE'
INFER_COMMON_PARAMS['fold_no'] = 0
INFER_COMMON_PARAMS['infer_filename'] = os.path.join(PATHS['inference_dir'], 'validation_set_infer.pickle.gz')
INFER_COMMON_PARAMS['checkpoint'] = 'best' # Fuse TIP: possible values are 'best', 'last' or epoch_index.
######################################
# Inference Template
######################################
def infer_template(paths: dict, infer_common_params: dict):
#### Logger
# fuse_logger_start(output_path=paths['inference_dir'], console_verbose_level=logging.INFO)
lgr = logging.getLogger('Fuse')
lgr.info('Fuse Inference', {'attrs': ['bold', 'underline']})
lgr.info(f'infer_filename={infer_common_params["infer_filename"]}', {'color': 'magenta'})
#### create infer datasource
## Create data source:
infer_data_source = FuseProstateXDataSourcePatient(paths['data_dir'],'validation',
db_ver=infer_common_params['partition_version'],
db_name = infer_common_params['db_name'],
fold_no=infer_common_params['fold_no'])
lgr.info(f'db_name={infer_common_params["db_name"]}', {'color': 'magenta'})
### load dataset
data_set_filename = os.path.join(paths["model_dir"], "inference_dataset.pth")
dataset = FuseDatasetBase.load(filename=data_set_filename, override_datasource=infer_data_source, override_cache_dest=paths["cache_dir"], num_workers=0)
dataloader = DataLoader(dataset=dataset,
shuffle=False,
drop_last=False,
batch_size=50,
num_workers=5,
collate_fn=dataset.collate_fn)
#### Manager for inference
manager = FuseManagerDefault()
# extract just the global classification per sample and save to a file
output_columns = ['model.output.isLargeTumorSize','data.ground_truth']
manager.infer(data_loader=dataloader,
input_model_dir=paths['model_dir'],
checkpoint=infer_common_params['checkpoint'],
output_columns=output_columns,
output_file_name = infer_common_params['infer_filename'])
######################################
# Analyze Common Params
######################################
ANALYZE_COMMON_PARAMS = {}
ANALYZE_COMMON_PARAMS['infer_filename'] = INFER_COMMON_PARAMS['infer_filename']
ANALYZE_COMMON_PARAMS['output_filename'] = os.path.join(PATHS['analyze_dir'], 'all_metrics_DCE_T0_fold0')
######################################
# Analyze Template
######################################
def analyze_template(paths: dict, analyze_common_params: dict):
fuse_logger_start(output_path=None, console_verbose_level=logging.INFO)
lgr = logging.getLogger('Fuse')
lgr.info('Fuse Analyze', {'attrs': ['bold', 'underline']})
fuse_logger_start(output_path=None, console_verbose_level=logging.INFO)
lgr = logging.getLogger('Fuse')
lgr.info('Fuse Analyze', {'attrs': ['bold', 'underline']})
# metrics
metrics = {
'roc': FuseMetricROCCurve(pred_name='model.output.isLargeTumorSize', target_name='data.ground_truth',
output_filename=os.path.join(paths['inference_dir'], 'roc_curve.png')),
'auc': FuseMetricAUC(pred_name='model.output.isLargeTumorSize', target_name='data.ground_truth')
}
# create analyzer
analyzer = FuseAnalyzerDefault()
# run
results = analyzer.analyze(gt_processors={},
data_pickle_filename=analyze_common_params["infer_filename"],
metrics=metrics,
output_filename=analyze_common_params['output_filename'])
return results
######################################
# Run
######################################
if __name__ == "__main__":
# allocate gpus
NUM_GPUS = 1
if NUM_GPUS == 0:
TRAIN_COMMON_PARAMS['manager.train_params']['device'] = 'cpu'
# uncomment if you want to use specific gpus instead of automatically looking for free ones
force_gpus = None # [0]
FuseUtilsGPU.choose_and_enable_multiple_gpus(NUM_GPUS, force_gpus=force_gpus)
RUNNING_MODES = ['train','infer', 'analyze'] # Options: 'train', 'infer', 'analyze'
if 'train' in RUNNING_MODES:
train_template(paths=PATHS, train_common_params=TRAIN_COMMON_PARAMS)
if 'infer' in RUNNING_MODES:
infer_template(paths=PATHS, infer_common_params=INFER_COMMON_PARAMS)
if 'analyze' in RUNNING_MODES:
analyze_template(paths=PATHS,analyze_common_params=ANALYZE_COMMON_PARAMS) |
the-stack_0_8649 | """
This file offers the methods to automatically retrieve the graph Thermoplasmatales archaeon E-plasma.
The graph is automatically retrieved from the STRING repository.
References
---------------------
Please cite the following if you use the data:
```bib
@article{szklarczyk2019string,
title={STRING v11: protein--protein association networks with increased coverage, supporting functional discovery in genome-wide experimental datasets},
author={Szklarczyk, Damian and Gable, Annika L and Lyon, David and Junge, Alexander and Wyder, Stefan and Huerta-Cepas, Jaime and Simonovic, Milan and Doncheva, Nadezhda T and Morris, John H and Bork, Peer and others},
journal={Nucleic acids research},
volume={47},
number={D1},
pages={D607--D613},
year={2019},
publisher={Oxford University Press}
}
```
"""
from typing import Dict
from ..automatic_graph_retrieval import AutomaticallyRetrievedGraph
from ...ensmallen import Graph # pylint: disable=import-error
def ThermoplasmatalesArchaeonEPlasma(
directed: bool = False,
preprocess: bool = True,
load_nodes: bool = True,
verbose: int = 2,
cache: bool = True,
cache_path: str = "graphs/string",
version: str = "links.v11.5",
**additional_graph_kwargs: Dict
) -> Graph:
"""Return new instance of the Thermoplasmatales archaeon E-plasma graph.
The graph is automatically retrieved from the STRING repository.
Parameters
-------------------
directed: bool = False
Wether to load the graph as directed or undirected.
By default false.
preprocess: bool = True
Whether to preprocess the graph to be loaded in
optimal time and memory.
load_nodes: bool = True,
Whether to load the nodes vocabulary or treat the nodes
simply as a numeric range.
verbose: int = 2,
Wether to show loading bars during the retrieval and building
of the graph.
cache: bool = True
Whether to use cache, i.e. download files only once
and preprocess them only once.
cache_path: str = "graphs"
Where to store the downloaded graphs.
version: str = "links.v11.5"
The version of the graph to retrieve.
The available versions are:
- homology.v11.5
- physical.links.v11.5
- links.v11.5
additional_graph_kwargs: Dict
Additional graph kwargs.
Returns
-----------------------
Instace of Thermoplasmatales archaeon E-plasma graph.
References
---------------------
Please cite the following if you use the data:
```bib
@article{szklarczyk2019string,
title={STRING v11: protein--protein association networks with increased coverage, supporting functional discovery in genome-wide experimental datasets},
author={Szklarczyk, Damian and Gable, Annika L and Lyon, David and Junge, Alexander and Wyder, Stefan and Huerta-Cepas, Jaime and Simonovic, Milan and Doncheva, Nadezhda T and Morris, John H and Bork, Peer and others},
journal={Nucleic acids research},
volume={47},
number={D1},
pages={D607--D613},
year={2019},
publisher={Oxford University Press}
}
```
"""
return AutomaticallyRetrievedGraph(
graph_name="ThermoplasmatalesArchaeonEPlasma",
repository="string",
version=version,
directed=directed,
preprocess=preprocess,
load_nodes=load_nodes,
verbose=verbose,
cache=cache,
cache_path=cache_path,
additional_graph_kwargs=additional_graph_kwargs
)()
|
the-stack_0_8650 | # pyright:reportUnknownMemberType=false
# pyright:reportUnknownArgumentType=false
# pyright:reportUnknownLambdaType=false
import re
from itertools import accumulate
from typing import Any, List
import ja_core_news_sm
from py_pdf_term._common.consts import JAPANESE_REGEX, NOSPACE_REGEX, SYMBOL_REGEX
from ..data import Token
from .base import BaseLanguageTokenizer
SPACES = re.compile(r"\s+")
DELIM_SPACE = re.compile(rf"(?<={NOSPACE_REGEX}) (?={NOSPACE_REGEX})")
class JapaneseTokenizer(BaseLanguageTokenizer):
def __init__(self) -> None:
enable_pipes = []
self._model = ja_core_news_sm.load()
self._model.select_pipes(enable=enable_pipes)
self._ja_regex = re.compile(JAPANESE_REGEX)
self._symbol_regex = re.compile(rf"({SYMBOL_REGEX})")
def inscope(self, text: str) -> bool:
return self._ja_regex.search(text) is not None
def tokenize(self, text: str) -> List[Token]:
text = SPACES.sub(" ", text).strip()
orginal_space_pos = {
match.start() - offset
for offset, match in enumerate(re.finditer(r" ", text))
if DELIM_SPACE.match(text, match.start()) is not None
}
text = DELIM_SPACE.sub("", text)
text = self._symbol_regex.sub(r" \1 ", text)
tokens = list(map(self._create_token, self._model(text)))
if not orginal_space_pos:
return tokens
tokenized_space_pos = set(
accumulate(map(lambda token: len(str(token)), tokens))
)
if not orginal_space_pos.issubset(tokenized_space_pos):
return tokens
pos, i = 0, 0
num_token = len(tokens) + len(orginal_space_pos)
while i < num_token:
if pos in orginal_space_pos:
pos += len(str(tokens[i]))
space = Token(
"ja",
" ",
"空白",
"*",
"*",
"*",
"SPACE",
" ",
" ",
False,
)
tokens.insert(i, space)
i += 2
else:
pos += len(str(tokens[i]))
i += 1
return tokens
def _create_token(self, token: Any) -> Token:
if self._symbol_regex.fullmatch(token.text):
return Token(
"ja",
token.text,
"補助記号",
"一般",
"*",
"*",
"SYM",
token.text,
token.text,
False,
)
pos_with_categories = token.tag_.split("-")
num_categories = len(pos_with_categories) - 1
pos = pos_with_categories[0]
category = pos_with_categories[1] if num_categories >= 1 else "*"
subcategory = pos_with_categories[2] if num_categories >= 2 else "*"
subsubcategory = pos_with_categories[3] if num_categories >= 3 else "*"
return Token(
"ja",
token.text,
pos,
category,
subcategory,
subsubcategory,
token.pos_,
token.lemma_.lower(),
token.shape_,
token.is_stop,
)
class JapaneseTokenClassifier:
def is_modifying_particle(self, token: Token) -> bool:
return token.surface_form == "の" and token.pos == "助詞"
def is_symbol(self, token: Token) -> bool:
return token.pos in {"補助記号"}
def is_connector_symbol(self, token: Token) -> bool:
return token.surface_form in {"・", "-"} and token.pos == "補助記号"
def is_meaningless(self, token: Token) -> bool:
return self.is_symbol(token) or self.is_modifying_particle(token)
|
the-stack_0_8651 | import theano.tensor as T
def cca_loss(outdim_size, use_all_singular_values):
"""
The main loss function (inner_cca_objective) is wrapped in this function due to
the constraints imposed by Keras on objective functions
"""
def inner_cca_objective(y_true, y_pred):
"""
It is the loss function of CCA as introduced in the original paper. There can be other formulations.
It is implemented by Theano tensor operations, and does not work on Tensorflow backend
y_true is just ignored
"""
r1 = 1e-4
r2 = 1e-4
eps = 1e-12
o1 = o2 = y_pred.shape[1]//2
# unpack (separate) the output of networks for view 1 and view 2
H1 = y_pred[:, 0:o1].T
H2 = y_pred[:, o1:o1+o2].T
m = H1.shape[1]
H1bar = H1 - (1.0 / m) * T.dot(H1, T.ones([m, m]))
H2bar = H2 - (1.0 / m) * T.dot(H2, T.ones([m, m]))
SigmaHat12 = (1.0 / (m - 1)) * T.dot(H1bar, H2bar.T)
SigmaHat11 = (1.0 / (m - 1)) * T.dot(H1bar, H1bar.T) + r1 * T.eye(o1)
SigmaHat22 = (1.0 / (m - 1)) * T.dot(H2bar, H2bar.T) + r2 * T.eye(o2)
# Calculating the root inverse of covariance matrices by using eigen decomposition
[D1, V1] = T.nlinalg.eigh(SigmaHat11)
[D2, V2] = T.nlinalg.eigh(SigmaHat22)
# Added to increase stability
posInd1 = T.gt(D1, eps).nonzero()[0]
D1 = D1[posInd1]
V1 = V1[:, posInd1]
posInd2 = T.gt(D2, eps).nonzero()[0]
D2 = D2[posInd2]
V2 = V2[:, posInd2]
SigmaHat11RootInv = T.dot(T.dot(V1, T.nlinalg.diag(D1 ** -0.5)), V1.T)
SigmaHat22RootInv = T.dot(T.dot(V2, T.nlinalg.diag(D2 ** -0.5)), V2.T)
Tval = T.dot(T.dot(SigmaHat11RootInv, SigmaHat12), SigmaHat22RootInv)
if use_all_singular_values:
# all singular values are used to calculate the correlation
corr = T.sqrt(T.nlinalg.trace(T.dot(Tval.T, Tval)))
else:
# just the top outdim_size singular values are used
[U, V] = T.nlinalg.eigh(T.dot(Tval.T, Tval))
U = U[T.gt(U, eps).nonzero()[0]]
U = U.sort()
corr = T.sum(T.sqrt(U[0:outdim_size]))
return -corr
return inner_cca_objective
|
the-stack_0_8652 | _base_ = [
'../_base_/models/mask_rcnn_swin_fpn.py',
'../_base_/datasets/coco_instance.py',
'../_base_/schedules/schedule_1x.py',
'../_base_/default_runtime.py'
]
model = dict(
backbone=dict(
in_chans=3,
embed_dim=96,
depths=[2, 2, 6, 2],
num_heads=[3, 6, 12, 24],
window_size=7,
ape=False,
drop_path_rate=0.1,
patch_norm=True,
use_checkpoint=False
),
neck=dict(in_channels=[96, 192, 384, 768]),
roi_head=dict(
bbox_head=dict(num_classes=1),
mask_head=dict(
num_classes=1,
loss_mask=dict(
type='CrossEntropyLoss', use_mask=True, loss_weight=0.1))
),
test_cfg=dict(
rcnn=dict(
score_thr=0.01,
nms=dict(type='nms', iou_threshold=0.5),
max_per_img=300
)
)
)
img_norm_cfg = dict(
mean=[134.756, 134.756, 134.756], std=[61.680, 61.680, 61.680], to_rgb=True)
# augmentation strategy originates from DETR / Sparse RCNN
_input_size = 1280
_widths = list(range(int(_input_size / 2), int(_input_size * 1.5), 64))
_ratios = list([v / 10 for v in range(7, 13 + 1, 1)])
_img_scale = []
for _w in _widths:
_img_scale += [(_w, int(_w * r)) for r in _ratios]
_img_fill_val = 134.756
_autoaug_transforms = [
'Shear', 'Translate', 'Rotate',
'BrightnessTransform', 'ContrastTransform', 'EqualizeTransform'
]
_n_subpolicies = 100
_prob_cands = list([v / 10 for v in range(0, 10 + 1, 1)])
_level_cands = list(range(0, 10 + 1, 1))
_direction_cands = ['horizontal', 'vertical']
import random
_autoaug_policies = []
for _ in range(_n_subpolicies):
_subpolicy = []
for _ in range(2):
_transform = dict(
type=random.choice(_autoaug_transforms),
prob=random.choice(_prob_cands)
)
if _transform['type'] not in ['EqualizeTransform']:
_transform['level'] = random.choice(_level_cands)
if _transform['type'] in ['Shear', 'Translate', 'Rotate']:
_transform['img_fill_val'] = _img_fill_val
if _transform['type'] in ['Shear', 'Translate']:
_transform['direction'] = random.choice(_direction_cands)
_subpolicy.append(_transform)
_autoaug_policies.append(_subpolicy)
del random
train_pipeline = [
dict(type='LoadImageFromFile', color_type='color'),
dict(type='LoadAnnotations', with_bbox=True, with_mask=True),
dict(type='RandomFlip', flip_ratio=0.5),
dict(type='Resize',
img_scale=_img_scale,
multiscale_mode='value',
keep_ratio=False),
dict(type='AutoAugment',
policies=_autoaug_policies),
dict(type='RandomCrop',
crop_type='absolute',
crop_size=(_input_size, _input_size),
allow_negative_crop=True),
dict(type='Normalize', **img_norm_cfg),
dict(type='Pad', size_divisor=32),
dict(type='DefaultFormatBundle'),
dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels', 'gt_masks']),
]
test_pipeline = [
dict(type='LoadImageFromFile', color_type='color'),
dict(
type='MultiScaleFlipAug',
img_scale=[(int(_input_size), int(_input_size)),
(int(_input_size * 1.25), int(_input_size * 1.25)),
],
flip=True,
transforms=[
dict(type='Resize', keep_ratio=True),
dict(type='RandomFlip'),
dict(type='Normalize', **img_norm_cfg),
dict(type='ImageToTensor', keys=['img']),
dict(type='Collect', keys=['img']),
])
]
# Modify dataset related settings
img_dir = '/kaggle/working/data/siim/2048x2048'
anno_dir = '/kaggle/working/data/siim/mmdet_annos'
fold = 0
classes = ('opacity',)
data = dict(
samples_per_gpu=2,
workers_per_gpu=2,
train=dict(
img_prefix=img_dir,
classes=classes,
ann_file=f'{anno_dir}/train.json',
pipeline=train_pipeline),
val=dict(
img_prefix=img_dir,
classes=classes,
ann_file=f'{anno_dir}/test.json',
pipeline=test_pipeline),
test=dict(
img_prefix=img_dir,
classes=classes,
ann_file=f'{anno_dir}/test.json',
pipeline=test_pipeline),
)
# scheduler
optimizer = dict(_delete_=True, type='AdamW', lr=0.00001, betas=(0.9, 0.999), weight_decay=0.05,
paramwise_cfg=dict(custom_keys={'absolute_pos_embed': dict(decay_mult=0.),
'relative_position_bias_table': dict(decay_mult=0.),
'norm': dict(decay_mult=0.)}))
lr_config = dict(step=[24, 33])
runner = dict(type='EpochBasedRunnerAmp', max_epochs=36)
# do not use mmdet version fp16
fp16 = None
optimizer_config = dict(
type="DistOptimizerHook",
update_interval=1,
grad_clip=None,
coalesce=True,
bucket_size_mb=-1,
use_fp16=False,
)
# We can use the pre-trained Mask RCNN model to obtain higher performance
load_from = 'checkpoints/mask_rcnn_swin_tiny_patch4_window7.pth'
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.