prompt
stringlengths 19
1.03M
| completion
stringlengths 4
2.12k
| api
stringlengths 8
90
|
---|---|---|
# Copyright (C) 2021, <NAME>, <NAME> <<EMAIL>>
#
# License: MIT (see COPYING file)
import warnings
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
# __all__ = ['CytOpT']
from CytOpT.descentAscent import cytoptDesasc
from CytOpT.minmaxSwapping import cytoptMinmax
from CytOpT.plots import resultPlot, BlandAltman
def stopRunning():
warnings.warn("deprecated", DeprecationWarning)
def getLengthUniqueNumbers(values):
list_of_unique_value = []
unique_values = set(values)
for number in unique_values:
list_of_unique_value.append(number)
return {'list_of_unique_value': list_of_unique_value, 'length': len(list_of_unique_value)}
# CytOpT
def CytOpT(xSource, xTarget, labSource, labTarget=None, thetaTrue=None,
method=None, eps=1e-04, nIter=4000, power=0.99,
stepGrad=10, step=5, lbd=1e-04, nItGrad=10000, nItSto=10,
cont=True, monitoring=False, minMaxScaler=True, thresholding=True):
""" CytOpT algorithm. This methods is designed to estimate the proportions of cells in an unclassified Cytometry
data set denoted xTarget. CytOpT is a supervised method that levarge the classification denoted labSource associated
to the flow cytometry data set xSource. The estimation relies on the resolution of an optimization problem.
two procedures are provided "minmax" and "desasc". We recommend to use the default method that is
``minmax``.
:param xSource: np.array of shape (n_samples_source, n_biomarkers). The source cytometry data set.
A cytometry dataframe. The columns correspond to the different biological markers tracked.
One line corresponds to the cytometry measurements performed on one cell. The classification
of this Cytometry data set must be provided with the labSource parameters.
:param xTarget: np.array of shape (n_samples_target, n_biomarkers). The target cytometry data set.
A cytometry dataframe. The columns correspond to the different biological markers tracked.
One line corresponds to the cytometry measurements performed on one cell. The CytOpT algorithm
targets the cell type proportion in this Cytometry data set
:param labSource: np.array of shape (n_samples_source,). The classification of the source data set.
:param labTarget: np.array of shape (n_samples_target,), ``default=None``. The classification of the target data set.
:param thetaTrue: np.array of shape (K,), ``default=None``. This array stores the true proportions of the K type of
cells estimated in the target data set. This parameter is required if the user enables the monitoring option.
:param method: {"minmax", "desasc", "both"}, ``default="minmax"``. Method chosen to
to solve the optimization problem involved in CytOpT. It is advised to rely on the default choice that is
"minmax".
:param eps: float, ``default=0.0001``. Regularization parameter of the Wasserstein distance. This parameter must be
positive.
:param nIter: int, ``default=10000``. Number of iterations of the stochastic gradient ascent for the Minmax swapping
optimization method.
:param power: float, ``default=0.99``. Decreasing rate for the step-size policy of the stochastic gradient ascent
for the Minmax swapping optimization method. The step-size decreases at a rate of 1/n^power.
:param stepGrad: float, ``default=10``. Constant step_size policy for the gradient descent of the descent-ascent
optimization strategy.
:param step: float, ``default=5``. Multiplication factor of the stochastic gradient ascent step-size policy for
the minmax optimization method.
:param lbd: float, ``default=0.0001``. Additionnal regularization parameter of the Minmax swapping optimization method.
This parameter lbd should be greater or equal to eps.
:param nItGrad: int, ``default=10000``. Number of iterations of the outer loop of the descent-ascent optimization method.
This loop corresponds to the descent part of descent-ascent strategy.
:param nItSto: int, ``default = 10``. Number of iterations of the inner loop of the descent-ascent optimization method.
This loop corresponds to the stochastic ascent part of this optimization procedure.
:param cont: bool, ``default=True``. When set to true, the progress is displayed.
:param monitoring: bool, ``default=False``. When set to true, the evolution of the Kullback-Leibler between the
estimated proportions and the benchmark proportions is tracked and stored.
:param minMaxScaler: bool, ``default = True``. When set to True, the source and target data sets are scaled in [0,1]^d,
where d is the number of biomarkers monitored.
:param thresholding: bool, ``default = True``. When set to True, all the coefficients of the source and target data sets
are replaced by their positive part. This preprocessing is relevant for Cytometry Data as the signal acquisition of
the cytometer can induce convtrived negative values.
:return:
- hat_theta : np.array of shape (K,), where K is the number of different type of cell populations in the source data set.
- KL_monitoring: np.array of shape (n_out, ) or (nIter,) depending on the choice of the optimization method. This array stores the evolution of the Kullback-Leibler divergence between the estimate and benchmark proportions, if monitoring==True.
Reference:
<NAME>, <NAME>,and <NAME> CytOpT: Optimal Transport with Domain Adaptation for Interpreting Flow Cytometry data,
arXiv:2006.09003 [stat.AP].
"""
if method is None:
method = ["minmax", "desasc", "both"]
if isinstance(method, list):
method = method[0]
if method not in ["minmax", "desasc", "both"]:
warnings.warn('"choose method in list : \"minmax or","desasc or", "both\""')
method = "minmax"
if thetaTrue is None:
if labTarget is None and labSource is None:
with warnings.catch_warnings():
warnings.simplefilter("labTarget and theta can not be null at the same time\n"
"Initialize at least one of the two parameters")
stopRunning()
elif labTarget is not None:
labTargetInfo = getLengthUniqueNumbers(labTarget)
thetaTrue = np.zeros(labTargetInfo['length'])
for index in range(labTargetInfo['length']):
thetaTrue[index] = sum(labTarget == index + 1) / len(labTarget)
else:
labSourceInfo = getLengthUniqueNumbers(labSource)
thetaTrue = np.zeros(labSourceInfo['length'])
for index in range(labSourceInfo['length']):
thetaTrue[index] = sum(labSource == index + 1) / len(labSource)
if xSource is None or xTarget is None:
with warnings.catch_warnings():
warnings.simplefilter("xSource and xTarget can not be null\n"
"Initialize at two parameters")
stopRunning()
else:
xSource = np.asarray(xSource)
xTarget = np.asarray(xTarget)
h_res = {}
monitoring_res = {}
h_res["GoldStandard"] = thetaTrue
if method in ["minmax", "both"]:
results = cytoptMinmax(xSource, xTarget, labSource,
eps=eps, lbd=lbd, nIter=nIter,
step=step, cont=cont, power=power, thetaTrue=thetaTrue,
monitoring=monitoring, thresholding=thresholding, minMaxScaler=minMaxScaler)
h_res['minmax'] = results[0]
if monitoring:
monitoring_res["minmax"] = results[1][:min(nIter, nItGrad)]
if method in ["desasc", "both"]:
results = cytoptDesasc(xSource, xTarget, labSource,
eps=eps, nItGrad=nItGrad, nItSto=nItSto,
stepGrad=stepGrad, cont=cont, thetaTrue=thetaTrue,
monitoring=monitoring, thresholding=thresholding, minMaxScaler=minMaxScaler)
h_res['desasc'] = results[0]
if monitoring:
monitoring_res["desasc"] = results[1][:min(nIter, nItGrad)]
if monitoring:
return {"proportions":
|
pd.DataFrame(h_res)
|
pandas.DataFrame
|
#!/usr/bin/env python
import pandas as pd
import numpy as np
import math
import sys
import os
import argparse
import warnings
import pysam
import collections
import multiprocessing
def parseargs():
parser=argparse.ArgumentParser(description="Calculate coverage/fragment coverage of assemblies")
parser.add_argument('--bam',help='index bam file for alignment')
parser.add_argument('--output',help='output directory for MetaREA results')
parser.add_argument("--mlen",type=int, default=5000,help='minimum contig length')
args=parser.parse_args()
return args
def fragment_distribution(args,samfile):
all_reads=samfile.fetch()
references=samfile.references
lengths=samfile.lengths
size_freq=collections.defaultdict(int)
pool={}
contig_pool={}
discordant_pool={}
for ref,lens in zip(references,lengths):
if lens < args.mlen:
continue
contig_pool[ref]=[]
discordant_pool[ref]=[]
for read in all_reads:
contig = samfile.get_reference_name(read.tid)
if contig not in contig_pool:
continue
if read.rnext == read.tid:
if read.qname in pool and pool[read.qname][0] == read.tid:
mate_read = pool[read.qname]
size=abs(max(mate_read[1] + mate_read[2] - read.pos, read.pos+read.rlen-mate_read[1]))
size_freq[size]+=1
contig_pool[contig].append([min(mate_read[1],read.pos),size])
else:
pool[read.qname] = (read.tid,read.pos,read.rlen)
else:
contig1=samfile.get_reference_name(read.tid)
contig2=samfile.get_reference_name(read.rnext)
discordant_pool[contig1].append([read.pos,contig2])
return size_freq, contig_pool, discordant_pool
def FragMAD(freq):
"""
calculate median and median absolute deviation fragment size distribution
"""
all_size=[]
for key,value in freq.items():
all_size.extend([key]*int(value))
median_size = np.median(all_size)
residuals = abs(np.array(all_size)-median_size)
mad_size = 1.4826*np.median(residuals)
return median_size,mad_size
def discordant_loc_count(args,discordant_pool):
"""
Read pairs with mates mapped to different contigs
"""
discs={"contig":[],"start_pos":[],"discordant_loc_count":[]}
for key,value in discordant_pool.items():
if len(discordant_pool[key]) == 0:
continue
subdata = pd.DataFrame(value)
subdata['start_pos']=[math.floor((x-300)/100)*100+300 for x in subdata[0]]
subdata=subdata.loc[subdata['start_pos']>=300,]
if subdata.shape[0]==0:
continue
subdata['count']=1
grouped=subdata.groupby(['start_pos'])
data=pd.DataFrame(grouped[1].value_counts())
data['start_pos'] = [x[0] for x in data.index]
data['target'] = [x[1] for x in data.index]
data.index=range(data.shape[0])
grouped=data.groupby(['start_pos'])
data=pd.DataFrame(grouped[1].max())
positions=list(data.index)
discs["contig"].extend([key]*len(positions))
discs["start_pos"].extend(positions)
discs["discordant_loc_count"].extend(list(data[1]))
data=pd.DataFrame(discs)
os.makedirs(os.path.join(args.output, "temp/read_feature/"), exist_ok=True)
data.to_csv(os.path.join(args.output, "temp/read_feature/discordant_loc_feature.txt"), sep='\t')
def discordant_size_count(args,contig_frag,mu,dev):
"""
Read pairs with mates too for or too close to each other
"""
discs={"contig":[],"start_pos":[],"discordant_size_count":[]}
for key,value in contig_frag.items():
if len(contig_frag[key])==0:
continue
subdata =
|
pd.DataFrame(value)
|
pandas.DataFrame
|
import unittest
import pandas as pd
import numpy as np
from scipy.sparse.csr import csr_matrix
from string_grouper.string_grouper import DEFAULT_MIN_SIMILARITY, \
DEFAULT_REGEX, DEFAULT_NGRAM_SIZE, DEFAULT_N_PROCESSES, DEFAULT_IGNORE_CASE, \
StringGrouperConfig, StringGrouper, StringGrouperNotFitException, \
match_most_similar, group_similar_strings, match_strings, \
compute_pairwise_similarities
from unittest.mock import patch, Mock
def mock_symmetrize_matrix(x: csr_matrix) -> csr_matrix:
return x
class SimpleExample(object):
def __init__(self):
self.customers_df = pd.DataFrame(
[
('BB016741P', 'Mega Enterprises Corporation', 'Address0', 'Tel0', 'Description0', 0.2),
('CC082744L', 'Hyper Startup Incorporated', '', 'Tel1', '', 0.5),
('AA098762D', 'Hyper Startup Inc.', 'Address2', 'Tel2', 'Description2', 0.3),
('BB099931J', 'Hyper-Startup Inc.', 'Address3', 'Tel3', 'Description3', 0.1),
('HH072982K', 'Hyper Hyper Inc.', 'Address4', '', 'Description4', 0.9),
('EE059082Q', 'Mega Enterprises Corp.', 'Address5', 'Tel5', 'Description5', 1.0)
],
columns=('Customer ID', 'Customer Name', 'Address', 'Tel', 'Description', 'weight')
)
self.customers_df2 = pd.DataFrame(
[
('BB016741P', 'Mega Enterprises Corporation', 'Address0', 'Tel0', 'Description0', 0.2),
('CC082744L', 'Hyper Startup Incorporated', '', 'Tel1', '', 0.5),
('AA098762D', 'Hyper Startup Inc.', 'Address2', 'Tel2', 'Description2', 0.3),
('BB099931J', 'Hyper-Startup Inc.', 'Address3', 'Tel3', 'Description3', 0.1),
('DD012339M', 'HyperStartup Inc.', 'Address4', 'Tel4', 'Description4', 0.1),
('HH072982K', 'Hyper Hyper Inc.', 'Address5', '', 'Description5', 0.9),
('EE059082Q', 'Mega Enterprises Corp.', 'Address6', 'Tel6', 'Description6', 1.0)
],
columns=('Customer ID', 'Customer Name', 'Address', 'Tel', 'Description', 'weight')
)
self.a_few_strings = pd.Series(['BB016741P', 'BB082744L', 'BB098762D', 'BB099931J', 'BB072982K', 'BB059082Q'])
self.one_string = pd.Series(['BB0'])
self.two_strings = pd.Series(['Hyper', 'Hyp'])
self.whatever_series_1 = pd.Series(['whatever'])
self.expected_result_with_zeroes = pd.DataFrame(
[
(1, 'Hyper Startup Incorporated', 0.08170638, 'whatever', 0),
(0, 'Mega Enterprises Corporation', 0., 'whatever', 0),
(2, 'Hyper Startup Inc.', 0., 'whatever', 0),
(3, 'Hyper-Startup Inc.', 0., 'whatever', 0),
(4, 'Hyper Hyper Inc.', 0., 'whatever', 0),
(5, 'Mega Enterprises Corp.', 0., 'whatever', 0)
],
columns=['left_index', 'left_Customer Name', 'similarity', 'right_side', 'right_index']
)
self.expected_result_centroid = pd.Series(
[
'Mega Enterprises Corporation',
'Hyper Startup Inc.',
'Hyper Startup Inc.',
'Hyper Startup Inc.',
'Hyper Hyper Inc.',
'Mega Enterprises Corporation'
],
name='group_rep_Customer Name'
)
self.expected_result_centroid_with_index_col = pd.DataFrame(
[
(0, 'Mega Enterprises Corporation'),
(2, 'Hyper Startup Inc.'),
(2, 'Hyper Startup Inc.'),
(2, 'Hyper Startup Inc.'),
(4, 'Hyper Hyper Inc.'),
(0, 'Mega Enterprises Corporation')
],
columns=['group_rep_index', 'group_rep_Customer Name']
)
self.expected_result_first = pd.Series(
[
'Mega Enterprises Corporation',
'Hyper Startup Incorporated',
'Hyper Startup Incorporated',
'Hyper Startup Incorporated',
'Hyper Hyper Inc.',
'Mega Enterprises Corporation'
],
name='group_rep_Customer Name'
)
class StringGrouperConfigTest(unittest.TestCase):
def test_config_defaults(self):
"""Empty initialisation should set default values"""
config = StringGrouperConfig()
self.assertEqual(config.min_similarity, DEFAULT_MIN_SIMILARITY)
self.assertEqual(config.max_n_matches, None)
self.assertEqual(config.regex, DEFAULT_REGEX)
self.assertEqual(config.ngram_size, DEFAULT_NGRAM_SIZE)
self.assertEqual(config.number_of_processes, DEFAULT_N_PROCESSES)
self.assertEqual(config.ignore_case, DEFAULT_IGNORE_CASE)
def test_config_immutable(self):
"""Configurations should be immutable"""
config = StringGrouperConfig()
with self.assertRaises(Exception) as _:
config.min_similarity = 0.1
def test_config_non_default_values(self):
"""Configurations should be immutable"""
config = StringGrouperConfig(min_similarity=0.1, max_n_matches=100, number_of_processes=1)
self.assertEqual(0.1, config.min_similarity)
self.assertEqual(100, config.max_n_matches)
self.assertEqual(1, config.number_of_processes)
class StringGrouperTest(unittest.TestCase):
def test_auto_blocking_single_DataFrame(self):
"""tests whether automatic blocking yields consistent results"""
# This function will force an OverflowError to occur when
# the input Series have a combined length above a given number:
# OverflowThreshold. This will in turn trigger automatic splitting
# of the Series/matrices into smaller blocks when n_blocks = None
sort_cols = ['right_index', 'left_index']
def fix_row_order(df):
return df.sort_values(sort_cols).reset_index(drop=True)
simple_example = SimpleExample()
df1 = simple_example.customers_df2['<NAME>']
# first do manual blocking
sg = StringGrouper(df1, min_similarity=0.1)
pd.testing.assert_series_equal(sg.master, df1)
self.assertEqual(sg.duplicates, None)
matches = fix_row_order(sg.match_strings(df1, n_blocks=(1, 1)))
self.assertEqual(sg._config.n_blocks, (1, 1))
# Create a custom wrapper for this StringGrouper instance's
# _build_matches() method which will later be used to
# mock _build_matches().
# Note that we have to define the wrapper here because
# _build_matches() is a non-static function of StringGrouper
# and needs access to the specific StringGrouper instance sg
# created here.
def mock_build_matches(OverflowThreshold,
real_build_matches=sg._build_matches):
def wrapper(left_matrix,
right_matrix,
nnz_rows=None,
sort=True):
if (left_matrix.shape[0] + right_matrix.shape[0]) > \
OverflowThreshold:
raise OverflowError
return real_build_matches(left_matrix, right_matrix, nnz_rows, sort)
return wrapper
def do_test_with(OverflowThreshold):
nonlocal sg # allows reference to sg, as sg will be modified below
# Now let us mock sg._build_matches:
sg._build_matches = Mock(side_effect=mock_build_matches(OverflowThreshold))
sg.clear_data()
matches_auto = fix_row_order(sg.match_strings(df1, n_blocks=None))
pd.testing.assert_series_equal(sg.master, df1)
pd.testing.assert_frame_equal(matches, matches_auto)
self.assertEqual(sg._config.n_blocks, None)
# Note that _build_matches is called more than once if and only if
# a split occurred (that is, there was more than one pair of
# matrix-blocks multiplied)
if len(sg._left_Series) + len(sg._right_Series) > \
OverflowThreshold:
# Assert that split occurred:
self.assertGreater(sg._build_matches.call_count, 1)
else:
# Assert that split did not occur:
self.assertEqual(sg._build_matches.call_count, 1)
# now test auto blocking by forcing an OverflowError when the
# combined Series' lengths is greater than 10, 5, 3, 2
do_test_with(OverflowThreshold=100) # does not trigger auto blocking
do_test_with(OverflowThreshold=10)
do_test_with(OverflowThreshold=5)
do_test_with(OverflowThreshold=3)
do_test_with(OverflowThreshold=2)
def test_n_blocks_single_DataFrame(self):
"""tests whether manual blocking yields consistent results"""
sort_cols = ['right_index', 'left_index']
def fix_row_order(df):
return df.sort_values(sort_cols).reset_index(drop=True)
simple_example = SimpleExample()
df1 = simple_example.customers_df2['<NAME>']
matches11 = fix_row_order(match_strings(df1, min_similarity=0.1))
matches12 = fix_row_order(
match_strings(df1, n_blocks=(1, 2), min_similarity=0.1))
pd.testing.assert_frame_equal(matches11, matches12)
matches13 = fix_row_order(
match_strings(df1, n_blocks=(1, 3), min_similarity=0.1))
pd.testing.assert_frame_equal(matches11, matches13)
matches14 = fix_row_order(
match_strings(df1, n_blocks=(1, 4), min_similarity=0.1))
pd.testing.assert_frame_equal(matches11, matches14)
matches15 = fix_row_order(
match_strings(df1, n_blocks=(1, 5), min_similarity=0.1))
pd.testing.assert_frame_equal(matches11, matches15)
matches16 = fix_row_order(
match_strings(df1, n_blocks=(1, 6), min_similarity=0.1))
pd.testing.assert_frame_equal(matches11, matches16)
matches17 = fix_row_order(
match_strings(df1, n_blocks=(1, 7), min_similarity=0.1))
pd.testing.assert_frame_equal(matches11, matches17)
matches18 = fix_row_order(
match_strings(df1, n_blocks=(1, 8), min_similarity=0.1))
pd.testing.assert_frame_equal(matches11, matches18)
matches21 = fix_row_order(
match_strings(df1, n_blocks=(2, 1), min_similarity=0.1))
pd.testing.assert_frame_equal(matches11, matches21)
matches22 = fix_row_order(
match_strings(df1, n_blocks=(2, 2), min_similarity=0.1))
pd.testing.assert_frame_equal(matches11, matches22)
matches32 = fix_row_order(
match_strings(df1, n_blocks=(3, 2), min_similarity=0.1))
pd.testing.assert_frame_equal(matches11, matches32)
# Create a custom wrapper for this StringGrouper instance's
# _build_matches() method which will later be used to
# mock _build_matches().
# Note that we have to define the wrapper here because
# _build_matches() is a non-static function of StringGrouper
# and needs access to the specific StringGrouper instance sg
# created here.
sg = StringGrouper(df1, min_similarity=0.1)
def mock_build_matches(OverflowThreshold,
real_build_matches=sg._build_matches):
def wrapper(left_matrix,
right_matrix,
nnz_rows=None,
sort=True):
if (left_matrix.shape[0] + right_matrix.shape[0]) > \
OverflowThreshold:
raise OverflowError
return real_build_matches(left_matrix, right_matrix, nnz_rows, sort)
return wrapper
def test_overflow_error_with(OverflowThreshold, n_blocks):
nonlocal sg
sg._build_matches = Mock(side_effect=mock_build_matches(OverflowThreshold))
sg.clear_data()
max_left_block_size = (len(df1)//n_blocks[0]
+ (1 if len(df1) % n_blocks[0] > 0 else 0))
max_right_block_size = (len(df1)//n_blocks[1]
+ (1 if len(df1) % n_blocks[1] > 0 else 0))
if (max_left_block_size + max_right_block_size) > OverflowThreshold:
with self.assertRaises(Exception):
_ = sg.match_strings(df1, n_blocks=n_blocks)
else:
matches_manual = fix_row_order(sg.match_strings(df1, n_blocks=n_blocks))
pd.testing.assert_frame_equal(matches11, matches_manual)
test_overflow_error_with(OverflowThreshold=100, n_blocks=(1, 1))
test_overflow_error_with(OverflowThreshold=10, n_blocks=(1, 1))
test_overflow_error_with(OverflowThreshold=10, n_blocks=(2, 1))
test_overflow_error_with(OverflowThreshold=10, n_blocks=(1, 2))
test_overflow_error_with(OverflowThreshold=10, n_blocks=(4, 4))
def test_n_blocks_both_DataFrames(self):
"""tests whether manual blocking yields consistent results"""
sort_cols = ['right_index', 'left_index']
def fix_row_order(df):
return df.sort_values(sort_cols).reset_index(drop=True)
simple_example = SimpleExample()
df1 = simple_example.customers_df['Customer Name']
df2 = simple_example.customers_df2['Customer Name']
matches11 = fix_row_order(match_strings(df1, df2, min_similarity=0.1))
matches12 = fix_row_order(
match_strings(df1, df2, n_blocks=(1, 2), min_similarity=0.1))
pd.testing.assert_frame_equal(matches11, matches12)
matches13 = fix_row_order(
match_strings(df1, df2, n_blocks=(1, 3), min_similarity=0.1))
pd.testing.assert_frame_equal(matches11, matches13)
matches14 = fix_row_order(
match_strings(df1, df2, n_blocks=(1, 4), min_similarity=0.1))
pd.testing.assert_frame_equal(matches11, matches14)
matches15 = fix_row_order(
match_strings(df1, df2, n_blocks=(1, 5), min_similarity=0.1))
pd.testing.assert_frame_equal(matches11, matches15)
matches16 = fix_row_order(
match_strings(df1, df2, n_blocks=(1, 6), min_similarity=0.1))
pd.testing.assert_frame_equal(matches11, matches16)
matches17 = fix_row_order(
match_strings(df1, df2, n_blocks=(1, 7), min_similarity=0.1))
pd.testing.assert_frame_equal(matches11, matches17)
matches18 = fix_row_order(
match_strings(df1, df2, n_blocks=(1, 8), min_similarity=0.1))
pd.testing.assert_frame_equal(matches11, matches18)
matches21 = fix_row_order(
match_strings(df1, df2, n_blocks=(2, 1), min_similarity=0.1))
pd.testing.assert_frame_equal(matches11, matches21)
matches22 = fix_row_order(
match_strings(df1, df2, n_blocks=(2, 2), min_similarity=0.1))
pd.testing.assert_frame_equal(matches11, matches22)
matches32 = fix_row_order(
match_strings(df1, df2, n_blocks=(3, 2), min_similarity=0.1))
pd.testing.assert_frame_equal(matches11, matches32)
def test_n_blocks_bad_option_value(self):
"""Tests that bad option values for n_blocks are caught"""
simple_example = SimpleExample()
df1 = simple_example.customers_df2['<NAME>']
with self.assertRaises(Exception):
_ = match_strings(df1, n_blocks=2)
with self.assertRaises(Exception):
_ = match_strings(df1, n_blocks=(0, 2))
with self.assertRaises(Exception):
_ = match_strings(df1, n_blocks=(1, 2.5))
with self.assertRaises(Exception):
_ = match_strings(df1, n_blocks=(1, 2, 3))
with self.assertRaises(Exception):
_ = match_strings(df1, n_blocks=(1, ))
def test_tfidf_dtype_bad_option_value(self):
"""Tests that bad option values for n_blocks are caught"""
simple_example = SimpleExample()
df1 = simple_example.customers_df2['<NAME>']
with self.assertRaises(Exception):
_ = match_strings(df1, tfidf_matrix_dtype=None)
with self.assertRaises(Exception):
_ = match_strings(df1, tfidf_matrix_dtype=0)
with self.assertRaises(Exception):
_ = match_strings(df1, tfidf_matrix_dtype='whatever')
def test_compute_pairwise_similarities(self):
"""tests the high-level function compute_pairwise_similarities"""
simple_example = SimpleExample()
df1 = simple_example.customers_df['<NAME>']
df2 = simple_example.expected_result_centroid
similarities = compute_pairwise_similarities(df1, df2)
expected_result = pd.Series(
[
1.0,
0.6336195351561589,
1.0000000000000004,
1.0000000000000004,
1.0,
0.826462625999832
],
name='similarity'
)
expected_result = expected_result.astype(np.float32)
pd.testing.assert_series_equal(expected_result, similarities)
sg = StringGrouper(df1, df2)
similarities = sg.compute_pairwise_similarities(df1, df2)
|
pd.testing.assert_series_equal(expected_result, similarities)
|
pandas.testing.assert_series_equal
|
# Copyright Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file 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 unittest.mock
import pytest
import shutil
import tempfile
import os
import datetime
from smexperiments import api_types, tracker, trial_component, _utils, _environment
import pandas as pd
@pytest.fixture
def boto3_session():
mocked = unittest.mock.Mock()
mocked.client.return_value.get_caller_identity.return_value = {"Account": unittest.mock.Mock()}
return mocked
@pytest.fixture
def tempdir():
dir = tempfile.mkdtemp()
yield dir
shutil.rmtree(dir)
@pytest.fixture
def metrics_dir(tempdir):
saved = os.environ.get("SAGEMAKER_METRICS_DIRECTORY")
os.environ["SAGEMAKER_METRICS_DIRECTORY"] = tempdir
yield os.environ
del os.environ["SAGEMAKER_METRICS_DIRECTORY"]
if saved:
os.environ["SAGEMAKER_METRICS_DIRECTORY"] = saved
@pytest.fixture
def sagemaker_boto_client(boto3_session):
return boto3_session.client("sagemaker")
@pytest.fixture
def source_arn():
return "source_arn"
@pytest.fixture
def environ(source_arn):
contains = _utils.TRAINING_JOB_ARN_ENV in os.environ
original_value = os.environ.get(_utils.TRAINING_JOB_ARN_ENV)
os.environ[_utils.TRAINING_JOB_ARN_ENV] = source_arn
yield
if contains:
os.environ[_utils.TRAINING_JOB_ARN_ENV] = original_value
else:
del os.environ[_utils.TRAINING_JOB_ARN_ENV]
@unittest.mock.patch("smexperiments._environment.TrialComponentEnvironment")
def test_load_in_sagemaker_training_job(mocked_tce, sagemaker_boto_client):
trial_component_obj = trial_component.TrialComponent(
trial_component_name="foo-bar", sagemaker_boto_client=sagemaker_boto_client
)
rv = unittest.mock.Mock()
rv.source_arn = "arn:1234"
rv.environment_type = _environment.EnvironmentType.SageMakerTrainingJob
rv.get_trial_component.return_value = trial_component_obj
mocked_tce.load.return_value = rv
tracker_obj = tracker.Tracker.load(sagemaker_boto_client=sagemaker_boto_client)
assert tracker_obj._in_sagemaker_job
assert tracker_obj._metrics_writer
assert tracker_obj.trial_component == trial_component_obj
@unittest.mock.patch("smexperiments._environment.TrialComponentEnvironment")
def test_load_in_sagemaker_processing_job(mocked_tce, sagemaker_boto_client):
trial_component_obj = trial_component.TrialComponent(
trial_component_name="foo-bar", sagemaker_boto_client=sagemaker_boto_client
)
rv = unittest.mock.Mock()
rv.source_arn = "arn:1234"
rv.environment_type = _environment.EnvironmentType.SageMakerProcessingJob
rv.get_trial_component.return_value = trial_component_obj
mocked_tce.load.return_value = rv
tracker_obj = tracker.Tracker.load(sagemaker_boto_client=sagemaker_boto_client)
assert tracker_obj._in_sagemaker_job
assert tracker_obj._metrics_writer is None
assert tracker_obj.trial_component == trial_component_obj
def test_load_in_sagemaker_job_no_resolved_tc(sagemaker_boto_client):
with pytest.raises(ValueError):
tracker.Tracker.load(sagemaker_boto_client=sagemaker_boto_client)
def test_load(boto3_session, sagemaker_boto_client):
trial_component_name = "foo-trial-component"
sagemaker_boto_client.describe_trial_component.return_value = {"TrialComponentName": trial_component_name}
assert (
trial_component_name
== tracker.Tracker.load(
trial_component_name=trial_component_name, sagemaker_boto_client=sagemaker_boto_client
).trial_component.trial_component_name
)
def test_load_by_training_job_name(boto3_session, sagemaker_boto_client):
training_job_name = "foo-training-job"
trial_component_name = training_job_name + "-aws-training-job"
sagemaker_boto_client.describe_trial_component.return_value = {"TrialComponentName": trial_component_name}
assert (
trial_component_name
== tracker.Tracker.load(
training_job_name=training_job_name, sagemaker_boto_client=sagemaker_boto_client
).trial_component.trial_component_name
)
def test_load_by_processing_job_name(boto3_session, sagemaker_boto_client):
processing_job_name = "foo-processing-job"
trial_component_name = processing_job_name + "-aws-processing-job"
sagemaker_boto_client.describe_trial_component.return_value = {"TrialComponentName": trial_component_name}
assert (
trial_component_name
== tracker.Tracker.load(
processing_job_name=processing_job_name, sagemaker_boto_client=sagemaker_boto_client
).trial_component.trial_component_name
)
def test_create(boto3_session, sagemaker_boto_client):
trial_component_name = "foo-trial-component"
trial_component_display_name = "foo-trial-component-display-name"
sagemaker_boto_client.create_trial_component.return_value = {"TrialComponentName": trial_component_name}
tracker_created = tracker.Tracker.create(
display_name=trial_component_display_name, sagemaker_boto_client=sagemaker_boto_client
)
assert trial_component_name == tracker_created.trial_component.trial_component_name
assert tracker_created._metrics_writer is None
@pytest.fixture
def trial_component_obj(sagemaker_boto_client):
return trial_component.TrialComponent(sagemaker_boto_client)
@pytest.fixture
def under_test(trial_component_obj):
return tracker.Tracker(trial_component_obj, unittest.mock.Mock(), unittest.mock.Mock(), unittest.mock.Mock())
def test_log_parameter(under_test):
under_test.log_parameter("foo", "bar")
assert under_test.trial_component.parameters["foo"] == "bar"
under_test.log_parameter("whizz", 1)
assert under_test.trial_component.parameters["whizz"] == 1
def test_enter(under_test):
under_test.__enter__()
assert isinstance(under_test.trial_component.start_time, datetime.datetime)
assert under_test.trial_component.status.primary_status == "InProgress"
def test_cm(sagemaker_boto_client, under_test):
sagemaker_boto_client.update_trial_component.return_value = {}
with under_test:
pass
assert under_test.trial_component.status.primary_status == "Completed"
assert isinstance(under_test.trial_component.end_time, datetime.datetime)
def test_cm_fail(sagemaker_boto_client, under_test):
sagemaker_boto_client.update_trial_component.return_value = {}
try:
with under_test:
raise ValueError("Foo")
except ValueError:
pass
assert under_test.trial_component.status.primary_status == "Failed"
assert under_test.trial_component.status.message
assert isinstance(under_test.trial_component.end_time, datetime.datetime)
def test_enter_sagemaker_job(sagemaker_boto_client, under_test):
sagemaker_boto_client.update_trial_component.return_value = {}
under_test._in_sagemaker_job = True
with under_test:
pass
assert under_test.trial_component.start_time is None
assert under_test.trial_component.end_time is None
assert under_test.trial_component.status is None
def test_log_parameters(under_test):
under_test.log_parameters({"a": "b", "c": "d", "e": 5})
assert under_test.trial_component.parameters == {"a": "b", "c": "d", "e": 5}
def test_log_input(under_test):
under_test.log_input("foo", "baz", "text/text")
assert under_test.trial_component.input_artifacts == {
"foo": api_types.TrialComponentArtifact(value="baz", media_type="text/text")
}
def test_log_output(under_test):
under_test.log_output("foo", "baz", "text/text")
assert under_test.trial_component.output_artifacts == {
"foo": api_types.TrialComponentArtifact(value="baz", media_type="text/text")
}
def test_log_metric(under_test):
now = datetime.datetime.now()
under_test.log_metric("foo", 1.0, 1, now)
under_test._metrics_writer.log_metric.assert_called_with("foo", 1.0, 1, now)
def test_log_metric_attribute_error(under_test):
now = datetime.datetime.now()
exception = AttributeError
under_test._metrics_writer.log_metric.side_effect = exception
with pytest.raises(AttributeError):
under_test.log_metric("foo", 1.0, 1, now)
def test_log_metric_attribute_error_warned(under_test):
now = datetime.datetime.now()
under_test._metrics_writer = None
under_test._warned_on_metrics = None
under_test.log_metric("foo", 1.0, 1, now)
assert under_test._warned_on_metrics == True
def test_log_output_artifact(under_test):
under_test._artifact_uploader.upload_artifact.return_value = ("s3uri_value", "etag_value")
under_test.log_output_artifact("foo.txt", "name", "whizz/bang")
under_test._artifact_uploader.upload_artifact.assert_called_with("foo.txt")
assert "whizz/bang" == under_test.trial_component.output_artifacts["name"].media_type
under_test.log_output_artifact("foo.txt")
under_test._artifact_uploader.upload_artifact.assert_called_with("foo.txt")
under_test._lineage_artifact_tracker.add_output_artifact.assert_called_with(
"foo.txt", "s3uri_value", "etag_value", "text/plain"
)
assert "foo.txt" in under_test.trial_component.output_artifacts
assert "text/plain" == under_test.trial_component.output_artifacts["foo.txt"].media_type
def test_log_input_artifact(under_test):
under_test._artifact_uploader.upload_artifact.return_value = ("s3uri_value", "etag_value")
under_test.log_input_artifact("foo.txt", "name", "whizz/bang")
under_test._artifact_uploader.upload_artifact.assert_called_with("foo.txt")
assert "whizz/bang" == under_test.trial_component.input_artifacts["name"].media_type
under_test.log_input_artifact("foo.txt")
under_test._artifact_uploader.upload_artifact.assert_called_with("foo.txt")
under_test._lineage_artifact_tracker.add_input_artifact.assert_called_with(
"foo.txt", "s3uri_value", "etag_value", "text/plain"
)
assert "foo.txt" in under_test.trial_component.input_artifacts
assert "text/plain" == under_test.trial_component.input_artifacts["foo.txt"].media_type
def test_log_inputs_error(under_test):
for index in range(0, 30):
file_path = "foo" + str(index) + ".txt"
under_test.trial_component.input_artifacts[file_path] = {
"foo": api_types.TrialComponentArtifact(value="baz" + str(index), media_type="text/text")
}
with pytest.raises(ValueError):
under_test.log_input("foo.txt", "name", "whizz/bang")
def test_log_outputs(under_test):
for index in range(0, 30):
file_path = "foo" + str(index) + ".txt"
under_test.trial_component.output_artifacts[file_path] = {
"foo": api_types.TrialComponentArtifact(value="baz" + str(index), media_type="text/text")
}
with pytest.raises(ValueError):
under_test.log_output("foo.txt", "name", "whizz/bang")
def test_log_multiple_input_artifact(under_test):
for index in range(0, 30):
file_path = "foo" + str(index) + ".txt"
under_test._artifact_uploader.upload_artifact.return_value = (
"s3uri_value" + str(index),
"etag_value" + str(index),
)
under_test.log_input_artifact(file_path, "name" + str(index), "whizz/bang" + str(index))
under_test._artifact_uploader.upload_artifact.assert_called_with(file_path)
under_test._artifact_uploader.upload_artifact.return_value = ("s3uri_value", "etag_value")
with pytest.raises(ValueError):
under_test.log_input_artifact("foo.txt", "name", "whizz/bang")
def test_log_multiple_output_artifact(under_test):
for index in range(0, 30):
file_path = "foo" + str(index) + ".txt"
under_test._artifact_uploader.upload_artifact.return_value = (
"s3uri_value" + str(index),
"etag_value" + str(index),
)
under_test.log_output_artifact(file_path, "name" + str(index), "whizz/bang" + str(index))
under_test._artifact_uploader.upload_artifact.assert_called_with(file_path)
under_test._artifact_uploader.upload_artifact.return_value = ("s3uri_value", "etag_value")
with pytest.raises(ValueError):
under_test.log_output_artifact("foo.txt", "name", "whizz/bang")
def test_log_pr_curve(under_test):
y_true = [0, 0, 1, 1]
y_scores = [0.1, 0.4, 0.35, 0.8]
no_skill = 0.1
under_test._artifact_uploader.upload_object_artifact.return_value = ("s3uri_value", "etag_value")
under_test.log_precision_recall(y_true, y_scores, title="TestPRCurve", no_skill=no_skill)
expected_data = {
"type": "PrecisionRecallCurve",
"version": 0,
"title": "TestPRCurve",
"precision": [0.6666666666666666, 0.5, 1.0, 1.0],
"recall": [1.0, 0.5, 0.5, 0.0],
"averagePrecisionScore": 0.8333333333333333,
"noSkill": 0.1,
}
under_test._artifact_uploader.upload_object_artifact.assert_called_with(
"TestPRCurve", expected_data, file_extension="json"
)
under_test._lineage_artifact_tracker.add_input_artifact(
"TestPRCurve", "s3uri_value", "etag_value", "PrecisionRecallCurve"
)
def test_log_confusion_matrix(under_test):
y_true = [2, 0, 2, 2, 0, 1]
y_pred = [0, 0, 2, 2, 0, 2]
under_test._artifact_uploader.upload_object_artifact.return_value = ("s3uri_value", "etag_value")
under_test.log_confusion_matrix(y_true, y_pred, title="TestConfusionMatrix")
expected_data = {
"type": "ConfusionMatrix",
"version": 0,
"title": "TestConfusionMatrix",
"confusionMatrix": [[2, 0, 0], [0, 0, 1], [1, 0, 2]],
}
under_test._artifact_uploader.upload_object_artifact.assert_called_with(
"TestConfusionMatrix", expected_data, file_extension="json"
)
under_test._lineage_artifact_tracker.add_input_artifact(
"TestConfusionMatrix", "s3uri_value", "etag_value", "ConfusionMatrix"
)
def test_resolve_artifact_name():
file_names = {
"a": "a",
"a.txt": "a.txt",
"b.": "b.",
".c": ".c",
"/x/a/a.txt": "a.txt",
"/a/b/c.": "c.",
"./.a": ".a",
"../b.txt": "b.txt",
"~/a.txt": "a.txt",
"c/d.txt": "d.txt",
}
for file_name, artifact_name in file_names.items():
assert artifact_name == tracker._resolve_artifact_name(file_name)
@pytest.fixture
def artifact_uploader(boto3_session):
return tracker._ArtifactUploader("trial_component_name", "artifact_bucket", "artifact_prefix", boto3_session)
def test_artifact_uploader_init(artifact_uploader):
assert "trial_component_name" == artifact_uploader.trial_component_name
assert "artifact_bucket" == artifact_uploader.artifact_bucket
assert "artifact_prefix" == artifact_uploader.artifact_prefix
def test_artifact_uploader_upload_artifact_file_not_exists(tempdir, artifact_uploader):
not_exist_file = os.path.join(tempdir, "not.exists")
with pytest.raises(ValueError):
artifact_uploader.upload_artifact(not_exist_file)
def test_artifact_uploader_s3(tempdir, artifact_uploader):
path = os.path.join(tempdir, "exists")
with open(path, "a") as f:
f.write("boo")
name = tracker._resolve_artifact_name(path)
artifact_uploader.s3_client.head_object.return_value = {"ETag": "etag_value"}
s3_uri, etag = artifact_uploader.upload_artifact(path)
expected_key = "{}/{}/{}".format(artifact_uploader.artifact_prefix, artifact_uploader.trial_component_name, name)
artifact_uploader.s3_client.upload_file.assert_called_with(path, artifact_uploader.artifact_bucket, expected_key)
expected_uri = "s3://{}/{}".format(artifact_uploader.artifact_bucket, expected_key)
assert expected_uri == s3_uri
def test_guess_media_type():
assert "text/plain" == tracker._guess_media_type("foo.txt")
@pytest.fixture
def lineage_artifact_tracker(sagemaker_boto_client):
return tracker._LineageArtifactTracker("test_trial_component_arn", sagemaker_boto_client)
def test_lineage_artifact_tracker(lineage_artifact_tracker, sagemaker_boto_client):
lineage_artifact_tracker.add_input_artifact("input_name", "input_source_uri", "input_etag", "text/plain")
lineage_artifact_tracker.add_output_artifact("output_name", "output_source_uri", "output_etag", "text/plain")
sagemaker_boto_client.create_artifact.side_effect = [
{"ArtifactArn": "created_arn_1"},
{"ArtifactArn": "created_arn_2"},
]
lineage_artifact_tracker.save()
expected_calls = [
unittest.mock.call(
ArtifactName="input_name",
ArtifactType="text/plain",
Source={
"SourceUri": "input_source_uri",
"SourceTypes": [{"SourceIdType": "S3ETag", "Value": "input_etag"}],
},
),
unittest.mock.call(
ArtifactName="output_name",
ArtifactType="text/plain",
Source={
"SourceUri": "output_source_uri",
"SourceTypes": [{"SourceIdType": "S3ETag", "Value": "output_etag"}],
},
),
]
assert expected_calls == sagemaker_boto_client.create_artifact.mock_calls
expected_calls = [
unittest.mock.call(
SourceArn="created_arn_1", DestinationArn="test_trial_component_arn", AssociationType="ContributedTo"
),
unittest.mock.call(
SourceArn="test_trial_component_arn", DestinationArn="created_arn_2", AssociationType="Produced"
),
]
assert expected_calls == sagemaker_boto_client.add_association.mock_calls
def test_convert_dict_to_fields():
values = {"x": [1, 2, 3], "y": [4, 5, 6]}
fields = tracker._ArtifactConverter.convert_dict_to_fields(values)
expected_fields = [
{"name": "x", "type": "string"},
{"name": "y", "type": "string"},
]
assert expected_fields == fields
def test_convert_data_frame_to_values():
df = pd.DataFrame({"col1": [1, 2], "col2": [0.5, 0.75]})
values = tracker._ArtifactConverter.convert_data_frame_to_values(df)
expected_values = {"col1": [1, 2], "col2": [0.5, 0.75]}
assert expected_values == values
def test_convert_data_frame_to_fields():
df =
|
pd.DataFrame({"col1": [1, 2], "col2": [0.5, 0.75]})
|
pandas.DataFrame
|
# -*- coding: utf-8 -*-
# pylint: disable=E1101
# flake8: noqa
from datetime import datetime
import csv
import os
import sys
import re
import nose
import platform
from multiprocessing.pool import ThreadPool
from numpy import nan
import numpy as np
from pandas.io.common import DtypeWarning
from pandas import DataFrame, Series, Index, MultiIndex, DatetimeIndex
from pandas.compat import(
StringIO, BytesIO, PY3, range, long, lrange, lmap, u
)
from pandas.io.common import URLError
import pandas.io.parsers as parsers
from pandas.io.parsers import (read_csv, read_table, read_fwf,
TextFileReader, TextParser)
import pandas.util.testing as tm
import pandas as pd
from pandas.compat import parse_date
import pandas.lib as lib
from pandas import compat
from pandas.lib import Timestamp
from pandas.tseries.index import date_range
import pandas.tseries.tools as tools
from numpy.testing.decorators import slow
import pandas.parser
class ParserTests(object):
"""
Want to be able to test either C+Cython or Python+Cython parsers
"""
data1 = """index,A,B,C,D
foo,2,3,4,5
bar,7,8,9,10
baz,12,13,14,15
qux,12,13,14,15
foo2,12,13,14,15
bar2,12,13,14,15
"""
def read_csv(self, *args, **kwargs):
raise NotImplementedError
def read_table(self, *args, **kwargs):
raise NotImplementedError
def setUp(self):
import warnings
warnings.filterwarnings(action='ignore', category=FutureWarning)
self.dirpath = tm.get_data_path()
self.csv1 = os.path.join(self.dirpath, 'test1.csv')
self.csv2 = os.path.join(self.dirpath, 'test2.csv')
self.xls1 = os.path.join(self.dirpath, 'test.xls')
def construct_dataframe(self, num_rows):
df = DataFrame(np.random.rand(num_rows, 5), columns=list('abcde'))
df['foo'] = 'foo'
df['bar'] = 'bar'
df['baz'] = 'baz'
df['date'] = pd.date_range('20000101 09:00:00',
periods=num_rows,
freq='s')
df['int'] = np.arange(num_rows, dtype='int64')
return df
def generate_multithread_dataframe(self, path, num_rows, num_tasks):
def reader(arg):
start, nrows = arg
if not start:
return pd.read_csv(path, index_col=0, header=0, nrows=nrows,
parse_dates=['date'])
return pd.read_csv(path,
index_col=0,
header=None,
skiprows=int(start) + 1,
nrows=nrows,
parse_dates=[9])
tasks = [
(num_rows * i / num_tasks,
num_rows / num_tasks) for i in range(num_tasks)
]
pool = ThreadPool(processes=num_tasks)
results = pool.map(reader, tasks)
header = results[0].columns
for r in results[1:]:
r.columns = header
final_dataframe = pd.concat(results)
return final_dataframe
def test_converters_type_must_be_dict(self):
with tm.assertRaisesRegexp(TypeError, 'Type converters.+'):
self.read_csv(StringIO(self.data1), converters=0)
def test_empty_decimal_marker(self):
data = """A|B|C
1|2,334|5
10|13|10.
"""
self.assertRaises(ValueError, read_csv, StringIO(data), decimal='')
def test_empty_thousands_marker(self):
data = """A|B|C
1|2,334|5
10|13|10.
"""
self.assertRaises(ValueError, read_csv, StringIO(data), thousands='')
def test_multi_character_decimal_marker(self):
data = """A|B|C
1|2,334|5
10|13|10.
"""
self.assertRaises(ValueError, read_csv, StringIO(data), thousands=',,')
def test_empty_string(self):
data = """\
One,Two,Three
a,1,one
b,2,two
,3,three
d,4,nan
e,5,five
nan,6,
g,7,seven
"""
df = self.read_csv(StringIO(data))
xp = DataFrame({'One': ['a', 'b', np.nan, 'd', 'e', np.nan, 'g'],
'Two': [1, 2, 3, 4, 5, 6, 7],
'Three': ['one', 'two', 'three', np.nan, 'five',
np.nan, 'seven']})
tm.assert_frame_equal(xp.reindex(columns=df.columns), df)
df = self.read_csv(StringIO(data), na_values={'One': [], 'Three': []},
keep_default_na=False)
xp = DataFrame({'One': ['a', 'b', '', 'd', 'e', 'nan', 'g'],
'Two': [1, 2, 3, 4, 5, 6, 7],
'Three': ['one', 'two', 'three', 'nan', 'five',
'', 'seven']})
tm.assert_frame_equal(xp.reindex(columns=df.columns), df)
df = self.read_csv(
StringIO(data), na_values=['a'], keep_default_na=False)
xp = DataFrame({'One': [np.nan, 'b', '', 'd', 'e', 'nan', 'g'],
'Two': [1, 2, 3, 4, 5, 6, 7],
'Three': ['one', 'two', 'three', 'nan', 'five', '',
'seven']})
tm.assert_frame_equal(xp.reindex(columns=df.columns), df)
df = self.read_csv(StringIO(data), na_values={'One': [], 'Three': []})
xp = DataFrame({'One': ['a', 'b', np.nan, 'd', 'e', np.nan, 'g'],
'Two': [1, 2, 3, 4, 5, 6, 7],
'Three': ['one', 'two', 'three', np.nan, 'five',
np.nan, 'seven']})
tm.assert_frame_equal(xp.reindex(columns=df.columns), df)
# GH4318, passing na_values=None and keep_default_na=False yields
# 'None' as a na_value
data = """\
One,Two,Three
a,1,None
b,2,two
,3,None
d,4,nan
e,5,five
nan,6,
g,7,seven
"""
df = self.read_csv(
StringIO(data), keep_default_na=False)
xp = DataFrame({'One': ['a', 'b', '', 'd', 'e', 'nan', 'g'],
'Two': [1, 2, 3, 4, 5, 6, 7],
'Three': ['None', 'two', 'None', 'nan', 'five', '',
'seven']})
tm.assert_frame_equal(xp.reindex(columns=df.columns), df)
def test_read_csv(self):
if not compat.PY3:
if compat.is_platform_windows():
prefix = u("file:///")
else:
prefix = u("file://")
fname = prefix + compat.text_type(self.csv1)
# it works!
read_csv(fname, index_col=0, parse_dates=True)
def test_dialect(self):
data = """\
label1,label2,label3
index1,"a,c,e
index2,b,d,f
"""
dia = csv.excel()
dia.quoting = csv.QUOTE_NONE
df = self.read_csv(StringIO(data), dialect=dia)
data = '''\
label1,label2,label3
index1,a,c,e
index2,b,d,f
'''
exp = self.read_csv(StringIO(data))
exp.replace('a', '"a', inplace=True)
tm.assert_frame_equal(df, exp)
def test_dialect_str(self):
data = """\
fruit:vegetable
apple:brocolli
pear:tomato
"""
exp = DataFrame({
'fruit': ['apple', 'pear'],
'vegetable': ['brocolli', 'tomato']
})
dia = csv.register_dialect('mydialect', delimiter=':') # noqa
df = self.read_csv(StringIO(data), dialect='mydialect')
tm.assert_frame_equal(df, exp)
csv.unregister_dialect('mydialect')
def test_1000_sep(self):
data = """A|B|C
1|2,334|5
10|13|10.
"""
expected = DataFrame({
'A': [1, 10],
'B': [2334, 13],
'C': [5, 10.]
})
df = self.read_csv(StringIO(data), sep='|', thousands=',')
tm.assert_frame_equal(df, expected)
df = self.read_table(StringIO(data), sep='|', thousands=',')
tm.assert_frame_equal(df, expected)
def test_1000_sep_with_decimal(self):
data = """A|B|C
1|2,334.01|5
10|13|10.
"""
expected = DataFrame({
'A': [1, 10],
'B': [2334.01, 13],
'C': [5, 10.]
})
tm.assert_equal(expected.A.dtype, 'int64')
tm.assert_equal(expected.B.dtype, 'float')
tm.assert_equal(expected.C.dtype, 'float')
df = self.read_csv(StringIO(data), sep='|', thousands=',', decimal='.')
tm.assert_frame_equal(df, expected)
df = self.read_table(StringIO(data), sep='|',
thousands=',', decimal='.')
tm.assert_frame_equal(df, expected)
data_with_odd_sep = """A|B|C
1|2.334,01|5
10|13|10,
"""
df = self.read_csv(StringIO(data_with_odd_sep),
sep='|', thousands='.', decimal=',')
tm.assert_frame_equal(df, expected)
df = self.read_table(StringIO(data_with_odd_sep),
sep='|', thousands='.', decimal=',')
tm.assert_frame_equal(df, expected)
def test_separator_date_conflict(self):
# Regression test for issue #4678: make sure thousands separator and
# date parsing do not conflict.
data = '06-02-2013;13:00;1-000.215'
expected = DataFrame(
[[datetime(2013, 6, 2, 13, 0, 0), 1000.215]],
columns=['Date', 2]
)
df = self.read_csv(StringIO(data), sep=';', thousands='-',
parse_dates={'Date': [0, 1]}, header=None)
tm.assert_frame_equal(df, expected)
def test_squeeze(self):
data = """\
a,1
b,2
c,3
"""
idx = Index(['a', 'b', 'c'], name=0)
expected = Series([1, 2, 3], name=1, index=idx)
result = self.read_table(StringIO(data), sep=',', index_col=0,
header=None, squeeze=True)
tm.assertIsInstance(result, Series)
tm.assert_series_equal(result, expected)
def test_squeeze_no_view(self):
# GH 8217
# series should not be a view
data = """time,data\n0,10\n1,11\n2,12\n4,14\n5,15\n3,13"""
result = self.read_csv(StringIO(data), index_col='time', squeeze=True)
self.assertFalse(result._is_view)
def test_inf_parsing(self):
data = """\
,A
a,inf
b,-inf
c,Inf
d,-Inf
e,INF
f,-INF
g,INf
h,-INf
i,inF
j,-inF"""
inf = float('inf')
expected = Series([inf, -inf] * 5)
df = read_csv(StringIO(data), index_col=0)
tm.assert_almost_equal(df['A'].values, expected.values)
df = read_csv(StringIO(data), index_col=0, na_filter=False)
tm.assert_almost_equal(df['A'].values, expected.values)
def test_multiple_date_col(self):
# Can use multiple date parsers
data = """\
KORD,19990127, 19:00:00, 18:56:00, 0.8100, 2.8100, 7.2000, 0.0000, 280.0000
KORD,19990127, 20:00:00, 19:56:00, 0.0100, 2.2100, 7.2000, 0.0000, 260.0000
KORD,19990127, 21:00:00, 20:56:00, -0.5900, 2.2100, 5.7000, 0.0000, 280.0000
KORD,19990127, 21:00:00, 21:18:00, -0.9900, 2.0100, 3.6000, 0.0000, 270.0000
KORD,19990127, 22:00:00, 21:56:00, -0.5900, 1.7100, 5.1000, 0.0000, 290.0000
KORD,19990127, 23:00:00, 22:56:00, -0.5900, 1.7100, 4.6000, 0.0000, 280.0000
"""
def func(*date_cols):
return lib.try_parse_dates(parsers._concat_date_cols(date_cols))
df = self.read_csv(StringIO(data), header=None,
date_parser=func,
prefix='X',
parse_dates={'nominal': [1, 2],
'actual': [1, 3]})
self.assertIn('nominal', df)
self.assertIn('actual', df)
self.assertNotIn('X1', df)
self.assertNotIn('X2', df)
self.assertNotIn('X3', df)
d = datetime(1999, 1, 27, 19, 0)
self.assertEqual(df.ix[0, 'nominal'], d)
df = self.read_csv(StringIO(data), header=None,
date_parser=func,
parse_dates={'nominal': [1, 2],
'actual': [1, 3]},
keep_date_col=True)
self.assertIn('nominal', df)
self.assertIn('actual', df)
self.assertIn(1, df)
self.assertIn(2, df)
self.assertIn(3, df)
data = """\
KORD,19990127, 19:00:00, 18:56:00, 0.8100, 2.8100, 7.2000, 0.0000, 280.0000
KORD,19990127, 20:00:00, 19:56:00, 0.0100, 2.2100, 7.2000, 0.0000, 260.0000
KORD,19990127, 21:00:00, 20:56:00, -0.5900, 2.2100, 5.7000, 0.0000, 280.0000
KORD,19990127, 21:00:00, 21:18:00, -0.9900, 2.0100, 3.6000, 0.0000, 270.0000
KORD,19990127, 22:00:00, 21:56:00, -0.5900, 1.7100, 5.1000, 0.0000, 290.0000
KORD,19990127, 23:00:00, 22:56:00, -0.5900, 1.7100, 4.6000, 0.0000, 280.0000
"""
df = read_csv(StringIO(data), header=None,
prefix='X',
parse_dates=[[1, 2], [1, 3]])
self.assertIn('X1_X2', df)
self.assertIn('X1_X3', df)
self.assertNotIn('X1', df)
self.assertNotIn('X2', df)
self.assertNotIn('X3', df)
d = datetime(1999, 1, 27, 19, 0)
self.assertEqual(df.ix[0, 'X1_X2'], d)
df = read_csv(StringIO(data), header=None,
parse_dates=[[1, 2], [1, 3]], keep_date_col=True)
self.assertIn('1_2', df)
self.assertIn('1_3', df)
self.assertIn(1, df)
self.assertIn(2, df)
self.assertIn(3, df)
data = '''\
KORD,19990127 19:00:00, 18:56:00, 0.8100, 2.8100, 7.2000, 0.0000, 280.0000
KORD,19990127 20:00:00, 19:56:00, 0.0100, 2.2100, 7.2000, 0.0000, 260.0000
KORD,19990127 21:00:00, 20:56:00, -0.5900, 2.2100, 5.7000, 0.0000, 280.0000
KORD,19990127 21:00:00, 21:18:00, -0.9900, 2.0100, 3.6000, 0.0000, 270.0000
KORD,19990127 22:00:00, 21:56:00, -0.5900, 1.7100, 5.1000, 0.0000, 290.0000
'''
df = self.read_csv(StringIO(data), sep=',', header=None,
parse_dates=[1], index_col=1)
d = datetime(1999, 1, 27, 19, 0)
self.assertEqual(df.index[0], d)
def test_multiple_date_cols_int_cast(self):
data = ("KORD,19990127, 19:00:00, 18:56:00, 0.8100\n"
"KORD,19990127, 20:00:00, 19:56:00, 0.0100\n"
"KORD,19990127, 21:00:00, 20:56:00, -0.5900\n"
"KORD,19990127, 21:00:00, 21:18:00, -0.9900\n"
"KORD,19990127, 22:00:00, 21:56:00, -0.5900\n"
"KORD,19990127, 23:00:00, 22:56:00, -0.5900")
date_spec = {'nominal': [1, 2], 'actual': [1, 3]}
import pandas.io.date_converters as conv
# it works!
df = self.read_csv(StringIO(data), header=None, parse_dates=date_spec,
date_parser=conv.parse_date_time)
self.assertIn('nominal', df)
def test_multiple_date_col_timestamp_parse(self):
data = """05/31/2012,15:30:00.029,1306.25,1,E,0,,1306.25
05/31/2012,15:30:00.029,1306.25,8,E,0,,1306.25"""
result = self.read_csv(StringIO(data), sep=',', header=None,
parse_dates=[[0, 1]], date_parser=Timestamp)
ex_val = Timestamp('05/31/2012 15:30:00.029')
self.assertEqual(result['0_1'][0], ex_val)
def test_single_line(self):
# GH 6607
# Test currently only valid with python engine because sep=None and
# delim_whitespace=False. Temporarily copied to TestPythonParser.
# Test for ValueError with other engines:
with tm.assertRaisesRegexp(ValueError,
'sep=None with delim_whitespace=False'):
# sniff separator
buf = StringIO()
sys.stdout = buf
# printing warning message when engine == 'c' for now
try:
# it works!
df = self.read_csv(StringIO('1,2'), names=['a', 'b'],
header=None, sep=None)
tm.assert_frame_equal(DataFrame({'a': [1], 'b': [2]}), df)
finally:
sys.stdout = sys.__stdout__
def test_multiple_date_cols_with_header(self):
data = """\
ID,date,NominalTime,ActualTime,TDew,TAir,Windspeed,Precip,WindDir
KORD,19990127, 19:00:00, 18:56:00, 0.8100, 2.8100, 7.2000, 0.0000, 280.0000
KORD,19990127, 20:00:00, 19:56:00, 0.0100, 2.2100, 7.2000, 0.0000, 260.0000
KORD,19990127, 21:00:00, 20:56:00, -0.5900, 2.2100, 5.7000, 0.0000, 280.0000
KORD,19990127, 21:00:00, 21:18:00, -0.9900, 2.0100, 3.6000, 0.0000, 270.0000
KORD,19990127, 22:00:00, 21:56:00, -0.5900, 1.7100, 5.1000, 0.0000, 290.0000
KORD,19990127, 23:00:00, 22:56:00, -0.5900, 1.7100, 4.6000, 0.0000, 280.0000"""
df = self.read_csv(StringIO(data), parse_dates={'nominal': [1, 2]})
self.assertNotIsInstance(df.nominal[0], compat.string_types)
ts_data = """\
ID,date,nominalTime,actualTime,A,B,C,D,E
KORD,19990127, 19:00:00, 18:56:00, 0.8100, 2.8100, 7.2000, 0.0000, 280.0000
KORD,19990127, 20:00:00, 19:56:00, 0.0100, 2.2100, 7.2000, 0.0000, 260.0000
KORD,19990127, 21:00:00, 20:56:00, -0.5900, 2.2100, 5.7000, 0.0000, 280.0000
KORD,19990127, 21:00:00, 21:18:00, -0.9900, 2.0100, 3.6000, 0.0000, 270.0000
KORD,19990127, 22:00:00, 21:56:00, -0.5900, 1.7100, 5.1000, 0.0000, 290.0000
KORD,19990127, 23:00:00, 22:56:00, -0.5900, 1.7100, 4.6000, 0.0000, 280.0000
"""
def test_multiple_date_col_name_collision(self):
self.assertRaises(ValueError, self.read_csv, StringIO(self.ts_data),
parse_dates={'ID': [1, 2]})
data = """\
date_NominalTime,date,NominalTime,ActualTime,TDew,TAir,Windspeed,Precip,WindDir
KORD1,19990127, 19:00:00, 18:56:00, 0.8100, 2.8100, 7.2000, 0.0000, 280.0000
KORD2,19990127, 20:00:00, 19:56:00, 0.0100, 2.2100, 7.2000, 0.0000, 260.0000
KORD3,19990127, 21:00:00, 20:56:00, -0.5900, 2.2100, 5.7000, 0.0000, 280.0000
KORD4,19990127, 21:00:00, 21:18:00, -0.9900, 2.0100, 3.6000, 0.0000, 270.0000
KORD5,19990127, 22:00:00, 21:56:00, -0.5900, 1.7100, 5.1000, 0.0000, 290.0000
KORD6,19990127, 23:00:00, 22:56:00, -0.5900, 1.7100, 4.6000, 0.0000, 280.0000""" # noqa
self.assertRaises(ValueError, self.read_csv, StringIO(data),
parse_dates=[[1, 2]])
def test_index_col_named(self):
no_header = """\
KORD1,19990127, 19:00:00, 18:56:00, 0.8100, 2.8100, 7.2000, 0.0000, 280.0000
KORD2,19990127, 20:00:00, 19:56:00, 0.0100, 2.2100, 7.2000, 0.0000, 260.0000
KORD3,19990127, 21:00:00, 20:56:00, -0.5900, 2.2100, 5.7000, 0.0000, 280.0000
KORD4,19990127, 21:00:00, 21:18:00, -0.9900, 2.0100, 3.6000, 0.0000, 270.0000
KORD5,19990127, 22:00:00, 21:56:00, -0.5900, 1.7100, 5.1000, 0.0000, 290.0000
KORD6,19990127, 23:00:00, 22:56:00, -0.5900, 1.7100, 4.6000, 0.0000, 280.0000"""
h = "ID,date,NominalTime,ActualTime,TDew,TAir,Windspeed,Precip,WindDir\n"
data = h + no_header
rs = self.read_csv(StringIO(data), index_col='ID')
xp = self.read_csv(StringIO(data), header=0).set_index('ID')
tm.assert_frame_equal(rs, xp)
self.assertRaises(ValueError, self.read_csv, StringIO(no_header),
index_col='ID')
data = """\
1,2,3,4,hello
5,6,7,8,world
9,10,11,12,foo
"""
names = ['a', 'b', 'c', 'd', 'message']
xp = DataFrame({'a': [1, 5, 9], 'b': [2, 6, 10], 'c': [3, 7, 11],
'd': [4, 8, 12]},
index=Index(['hello', 'world', 'foo'], name='message'))
rs = self.read_csv(StringIO(data), names=names, index_col=['message'])
tm.assert_frame_equal(xp, rs)
self.assertEqual(xp.index.name, rs.index.name)
rs = self.read_csv(StringIO(data), names=names, index_col='message')
tm.assert_frame_equal(xp, rs)
self.assertEqual(xp.index.name, rs.index.name)
def test_usecols_index_col_False(self):
# Issue 9082
s = "a,b,c,d\n1,2,3,4\n5,6,7,8"
s_malformed = "a,b,c,d\n1,2,3,4,\n5,6,7,8,"
cols = ['a', 'c', 'd']
expected = DataFrame({'a': [1, 5], 'c': [3, 7], 'd': [4, 8]})
df = self.read_csv(StringIO(s), usecols=cols, index_col=False)
tm.assert_frame_equal(expected, df)
df = self.read_csv(StringIO(s_malformed),
usecols=cols, index_col=False)
tm.assert_frame_equal(expected, df)
def test_index_col_is_True(self):
# Issue 9798
self.assertRaises(ValueError, self.read_csv, StringIO(self.ts_data),
index_col=True)
def test_converter_index_col_bug(self):
# 1835
data = "A;B\n1;2\n3;4"
rs = self.read_csv(StringIO(data), sep=';', index_col='A',
converters={'A': lambda x: x})
xp = DataFrame({'B': [2, 4]}, index=Index([1, 3], name='A'))
tm.assert_frame_equal(rs, xp)
self.assertEqual(rs.index.name, xp.index.name)
def test_date_parser_int_bug(self):
# #3071
log_file = StringIO(
'posix_timestamp,elapsed,sys,user,queries,query_time,rows,'
'accountid,userid,contactid,level,silo,method\n'
'1343103150,0.062353,0,4,6,0.01690,3,'
'12345,1,-1,3,invoice_InvoiceResource,search\n'
)
def f(posix_string):
return datetime.utcfromtimestamp(int(posix_string))
# it works!
read_csv(log_file, index_col=0, parse_dates=0, date_parser=f)
def test_multiple_skts_example(self):
data = "year, month, a, b\n 2001, 01, 0.0, 10.\n 2001, 02, 1.1, 11."
pass
def test_malformed(self):
# all
data = """ignore
A,B,C
1,2,3 # comment
1,2,3,4,5
2,3,4
"""
try:
df = self.read_table(
StringIO(data), sep=',', header=1, comment='#')
self.assertTrue(False)
except Exception as inst:
self.assertIn('Expected 3 fields in line 4, saw 5', str(inst))
# skip_footer
data = """ignore
A,B,C
1,2,3 # comment
1,2,3,4,5
2,3,4
footer
"""
# GH 6607
# Test currently only valid with python engine because
# skip_footer != 0. Temporarily copied to TestPythonParser.
# Test for ValueError with other engines:
try:
with tm.assertRaisesRegexp(ValueError, 'skip_footer'): # XXX
df = self.read_table(
StringIO(data), sep=',', header=1, comment='#',
skip_footer=1)
self.assertTrue(False)
except Exception as inst:
self.assertIn('Expected 3 fields in line 4, saw 5', str(inst))
# first chunk
data = """ignore
A,B,C
skip
1,2,3
3,5,10 # comment
1,2,3,4,5
2,3,4
"""
try:
it = self.read_table(StringIO(data), sep=',',
header=1, comment='#',
iterator=True, chunksize=1,
skiprows=[2])
df = it.read(5)
self.assertTrue(False)
except Exception as inst:
self.assertIn('Expected 3 fields in line 6, saw 5', str(inst))
# middle chunk
data = """ignore
A,B,C
skip
1,2,3
3,5,10 # comment
1,2,3,4,5
2,3,4
"""
try:
it = self.read_table(StringIO(data), sep=',', header=1,
comment='#', iterator=True, chunksize=1,
skiprows=[2])
df = it.read(1)
it.read(2)
self.assertTrue(False)
except Exception as inst:
self.assertIn('Expected 3 fields in line 6, saw 5', str(inst))
# last chunk
data = """ignore
A,B,C
skip
1,2,3
3,5,10 # comment
1,2,3,4,5
2,3,4
"""
try:
it = self.read_table(StringIO(data), sep=',',
header=1, comment='#',
iterator=True, chunksize=1, skiprows=[2])
df = it.read(1)
it.read()
self.assertTrue(False)
except Exception as inst:
self.assertIn('Expected 3 fields in line 6, saw 5', str(inst))
def test_passing_dtype(self):
# GH 6607
# Passing dtype is currently only supported by the C engine.
# Temporarily copied to TestCParser*.
# Test for ValueError with other engines:
with tm.assertRaisesRegexp(ValueError,
"The 'dtype' option is not supported"):
df = DataFrame(np.random.rand(5, 2), columns=list(
'AB'), index=['1A', '1B', '1C', '1D', '1E'])
with tm.ensure_clean('__passing_str_as_dtype__.csv') as path:
df.to_csv(path)
# GH 3795
# passing 'str' as the dtype
result = self.read_csv(path, dtype=str, index_col=0)
tm.assert_series_equal(result.dtypes, Series(
{'A': 'object', 'B': 'object'}))
# we expect all object columns, so need to convert to test for
# equivalence
result = result.astype(float)
tm.assert_frame_equal(result, df)
# invalid dtype
self.assertRaises(TypeError, self.read_csv, path,
dtype={'A': 'foo', 'B': 'float64'},
index_col=0)
# valid but we don't support it (date)
self.assertRaises(TypeError, self.read_csv, path,
dtype={'A': 'datetime64', 'B': 'float64'},
index_col=0)
self.assertRaises(TypeError, self.read_csv, path,
dtype={'A': 'datetime64', 'B': 'float64'},
index_col=0, parse_dates=['B'])
# valid but we don't support it
self.assertRaises(TypeError, self.read_csv, path,
dtype={'A': 'timedelta64', 'B': 'float64'},
index_col=0)
with tm.assertRaisesRegexp(ValueError,
"The 'dtype' option is not supported"):
# empty frame
# GH12048
self.read_csv(StringIO('A,B'), dtype=str)
def test_quoting(self):
bad_line_small = """printer\tresult\tvariant_name
Klosterdruckerei\tKlosterdruckerei <Salem> (1611-1804)\tMuller, Jacob
Klosterdruckerei\tKlosterdruckerei <Salem> (1611-1804)\tMuller, Jakob
Klosterdruckerei\tKlosterdruckerei <Kempten> (1609-1805)\t"Furststiftische Hofdruckerei, <Kempten""
Klosterdruckerei\tKlosterdruckerei <Kempten> (1609-1805)\tGaller, Alois
Klosterdruckerei\tKlosterdruckerei <Kempten> (1609-1805)\tHochfurstliche Buchhandlung <Kempten>"""
self.assertRaises(Exception, self.read_table, StringIO(bad_line_small),
sep='\t')
good_line_small = bad_line_small + '"'
df = self.read_table(StringIO(good_line_small), sep='\t')
self.assertEqual(len(df), 3)
def test_non_string_na_values(self):
# GH3611, na_values that are not a string are an issue
with tm.ensure_clean('__non_string_na_values__.csv') as path:
df = DataFrame({'A': [-999, 2, 3], 'B': [1.2, -999, 4.5]})
df.to_csv(path, sep=' ', index=False)
result1 = read_csv(path, sep=' ', header=0,
na_values=['-999.0', '-999'])
result2 = read_csv(path, sep=' ', header=0,
na_values=[-999, -999.0])
result3 = read_csv(path, sep=' ', header=0,
na_values=[-999.0, -999])
tm.assert_frame_equal(result1, result2)
tm.assert_frame_equal(result2, result3)
result4 = read_csv(path, sep=' ', header=0, na_values=['-999.0'])
result5 = read_csv(path, sep=' ', header=0, na_values=['-999'])
result6 = read_csv(path, sep=' ', header=0, na_values=[-999.0])
result7 = read_csv(path, sep=' ', header=0, na_values=[-999])
tm.assert_frame_equal(result4, result3)
tm.assert_frame_equal(result5, result3)
tm.assert_frame_equal(result6, result3)
tm.assert_frame_equal(result7, result3)
good_compare = result3
# with an odd float format, so we can't match the string 999.0
# exactly, but need float matching
df.to_csv(path, sep=' ', index=False, float_format='%.3f')
result1 = read_csv(path, sep=' ', header=0,
na_values=['-999.0', '-999'])
result2 = read_csv(path, sep=' ', header=0,
na_values=[-999, -999.0])
result3 = read_csv(path, sep=' ', header=0,
na_values=[-999.0, -999])
|
tm.assert_frame_equal(result1, good_compare)
|
pandas.util.testing.assert_frame_equal
|
# *****************************************************************************
# Copyright (c) 2019-2020, Intel Corporation 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.
#
# 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.
# *****************************************************************************
import itertools
import os
import platform
import string
import unittest
from copy import deepcopy
from itertools import product
import numpy as np
import pandas as pd
from numba.core.errors import TypingError
from sdc.hiframes.rolling import supported_rolling_funcs
from sdc.tests.test_base import TestCase
from sdc.tests.test_series import gen_frand_array
from sdc.tests.test_utils import (count_array_REPs, count_parfor_REPs,
skip_numba_jit, skip_sdc_jit,
test_global_input_data_float64)
LONG_TEST = (int(os.environ['SDC_LONG_ROLLING_TEST']) != 0
if 'SDC_LONG_ROLLING_TEST' in os.environ else False)
test_funcs = ('mean', 'max',)
if LONG_TEST:
# all functions except apply, cov, corr
test_funcs = supported_rolling_funcs[:-3]
def rolling_std_usecase(obj, window, min_periods, ddof):
return obj.rolling(window, min_periods).std(ddof)
def rolling_var_usecase(obj, window, min_periods, ddof):
return obj.rolling(window, min_periods).var(ddof)
class TestRolling(TestCase):
@skip_numba_jit
def test_series_rolling1(self):
def test_impl(S):
return S.rolling(3).sum()
hpat_func = self.jit(test_impl)
S = pd.Series([1.0, 2., 3., 4., 5.])
pd.testing.assert_series_equal(hpat_func(S), test_impl(S))
@skip_numba_jit
def test_fixed1(self):
# test sequentially with manually created dfs
wins = (3,)
if LONG_TEST:
wins = (2, 3, 5)
centers = (False, True)
for func_name in test_funcs:
func_text = "def test_impl(df, w, c):\n return df.rolling(w, center=c).{}()\n".format(func_name)
loc_vars = {}
exec(func_text, {}, loc_vars)
test_impl = loc_vars['test_impl']
hpat_func = self.jit(test_impl)
for args in itertools.product(wins, centers):
df = pd.DataFrame({'B': [0, 1, 2, np.nan, 4]})
pd.testing.assert_frame_equal(hpat_func(df, *args), test_impl(df, *args))
df = pd.DataFrame({'B': [0, 1, 2, -2, 4]})
pd.testing.assert_frame_equal(hpat_func(df, *args), test_impl(df, *args))
@skip_numba_jit
def test_fixed2(self):
# test sequentially with generated dfs
sizes = (121,)
wins = (3,)
if LONG_TEST:
sizes = (1, 2, 10, 11, 121, 1000)
wins = (2, 3, 5)
centers = (False, True)
for func_name in test_funcs:
func_text = "def test_impl(df, w, c):\n return df.rolling(w, center=c).{}()\n".format(func_name)
loc_vars = {}
exec(func_text, {}, loc_vars)
test_impl = loc_vars['test_impl']
hpat_func = self.jit(test_impl)
for n, w, c in itertools.product(sizes, wins, centers):
df = pd.DataFrame({'B': np.arange(n)})
pd.testing.assert_frame_equal(hpat_func(df, w, c), test_impl(df, w, c))
@skip_numba_jit
def test_fixed_apply1(self):
# test sequentially with manually created dfs
def test_impl(df, w, c):
return df.rolling(w, center=c).apply(lambda a: a.sum())
hpat_func = self.jit(test_impl)
wins = (3,)
if LONG_TEST:
wins = (2, 3, 5)
centers = (False, True)
for args in itertools.product(wins, centers):
df = pd.DataFrame({'B': [0, 1, 2, np.nan, 4]})
pd.testing.assert_frame_equal(hpat_func(df, *args), test_impl(df, *args))
df = pd.DataFrame({'B': [0, 1, 2, -2, 4]})
pd.testing.assert_frame_equal(hpat_func(df, *args), test_impl(df, *args))
@skip_numba_jit
def test_fixed_apply2(self):
# test sequentially with generated dfs
def test_impl(df, w, c):
return df.rolling(w, center=c).apply(lambda a: a.sum())
hpat_func = self.jit(test_impl)
sizes = (121,)
wins = (3,)
if LONG_TEST:
sizes = (1, 2, 10, 11, 121, 1000)
wins = (2, 3, 5)
centers = (False, True)
for n, w, c in itertools.product(sizes, wins, centers):
df = pd.DataFrame({'B': np.arange(n)})
pd.testing.assert_frame_equal(hpat_func(df, w, c), test_impl(df, w, c))
@skip_numba_jit
def test_fixed_parallel1(self):
def test_impl(n, w, center):
df = pd.DataFrame({'B': np.arange(n)})
R = df.rolling(w, center=center).sum()
return R.B.sum()
hpat_func = self.jit(test_impl)
sizes = (121,)
wins = (5,)
if LONG_TEST:
sizes = (1, 2, 10, 11, 121, 1000)
wins = (2, 4, 5, 10, 11)
centers = (False, True)
for args in itertools.product(sizes, wins, centers):
self.assertEqual(hpat_func(*args), test_impl(*args),
"rolling fixed window with {}".format(args))
self.assertEqual(count_array_REPs(), 0)
self.assertEqual(count_parfor_REPs(), 0)
@skip_numba_jit
def test_fixed_parallel_apply1(self):
def test_impl(n, w, center):
df = pd.DataFrame({'B': np.arange(n)})
R = df.rolling(w, center=center).apply(lambda a: a.sum())
return R.B.sum()
hpat_func = self.jit(test_impl)
sizes = (121,)
wins = (5,)
if LONG_TEST:
sizes = (1, 2, 10, 11, 121, 1000)
wins = (2, 4, 5, 10, 11)
centers = (False, True)
for args in itertools.product(sizes, wins, centers):
self.assertEqual(hpat_func(*args), test_impl(*args),
"rolling fixed window with {}".format(args))
self.assertEqual(count_array_REPs(), 0)
self.assertEqual(count_parfor_REPs(), 0)
@skip_numba_jit
def test_variable1(self):
# test sequentially with manually created dfs
df1 = pd.DataFrame({'B': [0, 1, 2, np.nan, 4],
'time': [pd.Timestamp('20130101 09:00:00'),
pd.Timestamp('20130101 09:00:02'),
pd.Timestamp('20130101 09:00:03'),
pd.Timestamp('20130101 09:00:05'),
pd.Timestamp('20130101 09:00:06')]})
df2 = pd.DataFrame({'B': [0, 1, 2, -2, 4],
'time': [pd.Timestamp('20130101 09:00:01'),
pd.Timestamp('20130101 09:00:02'),
pd.Timestamp('20130101 09:00:03'),
pd.Timestamp('20130101 09:00:04'),
pd.Timestamp('20130101 09:00:09')]})
wins = ('2s',)
if LONG_TEST:
wins = ('1s', '2s', '3s', '4s')
# all functions except apply
for w, func_name in itertools.product(wins, test_funcs):
func_text = "def test_impl(df):\n return df.rolling('{}', on='time').{}()\n".format(w, func_name)
loc_vars = {}
exec(func_text, {}, loc_vars)
test_impl = loc_vars['test_impl']
hpat_func = self.jit(test_impl)
# XXX: skipping min/max for this test since the behavior of Pandas
# is inconsistent: it assigns NaN to last output instead of 4!
if func_name not in ('min', 'max'):
pd.testing.assert_frame_equal(hpat_func(df1), test_impl(df1))
pd.testing.assert_frame_equal(hpat_func(df2), test_impl(df2))
@skip_numba_jit
def test_variable2(self):
# test sequentially with generated dfs
wins = ('2s',)
sizes = (121,)
if LONG_TEST:
wins = ('1s', '2s', '3s', '4s')
sizes = (1, 2, 10, 11, 121, 1000)
# all functions except apply
for w, func_name in itertools.product(wins, test_funcs):
func_text = "def test_impl(df):\n return df.rolling('{}', on='time').{}()\n".format(w, func_name)
loc_vars = {}
exec(func_text, {}, loc_vars)
test_impl = loc_vars['test_impl']
hpat_func = self.jit(test_impl)
for n in sizes:
time = pd.date_range(start='1/1/2018', periods=n, freq='s')
df = pd.DataFrame({'B': np.arange(n), 'time': time})
pd.testing.assert_frame_equal(hpat_func(df), test_impl(df))
@skip_numba_jit
def test_variable_apply1(self):
# test sequentially with manually created dfs
df1 = pd.DataFrame({'B': [0, 1, 2, np.nan, 4],
'time': [pd.Timestamp('20130101 09:00:00'),
pd.Timestamp('20130101 09:00:02'),
pd.Timestamp('20130101 09:00:03'),
pd.Timestamp('20130101 09:00:05'),
pd.Timestamp('20130101 09:00:06')]})
df2 = pd.DataFrame({'B': [0, 1, 2, -2, 4],
'time': [pd.Timestamp('20130101 09:00:01'),
pd.Timestamp('20130101 09:00:02'),
pd.Timestamp('20130101 09:00:03'),
pd.Timestamp('20130101 09:00:04'),
pd.Timestamp('20130101 09:00:09')]})
wins = ('2s',)
if LONG_TEST:
wins = ('1s', '2s', '3s', '4s')
# all functions except apply
for w in wins:
func_text = "def test_impl(df):\n return df.rolling('{}', on='time').apply(lambda a: a.sum())\n".format(w)
loc_vars = {}
exec(func_text, {}, loc_vars)
test_impl = loc_vars['test_impl']
hpat_func = self.jit(test_impl)
pd.testing.assert_frame_equal(hpat_func(df1), test_impl(df1))
pd.testing.assert_frame_equal(hpat_func(df2), test_impl(df2))
@skip_numba_jit
def test_variable_apply2(self):
# test sequentially with generated dfs
wins = ('2s',)
sizes = (121,)
if LONG_TEST:
wins = ('1s', '2s', '3s', '4s')
# TODO: this crashes on Travis (3 process config) with size 1
sizes = (2, 10, 11, 121, 1000)
# all functions except apply
for w in wins:
func_text = "def test_impl(df):\n return df.rolling('{}', on='time').apply(lambda a: a.sum())\n".format(w)
loc_vars = {}
exec(func_text, {}, loc_vars)
test_impl = loc_vars['test_impl']
hpat_func = self.jit(test_impl)
for n in sizes:
time = pd.date_range(start='1/1/2018', periods=n, freq='s')
df = pd.DataFrame({'B': np.arange(n), 'time': time})
pd.testing.assert_frame_equal(hpat_func(df), test_impl(df))
@skip_numba_jit
@unittest.skipIf(platform.system() == 'Windows', "ValueError: time must be monotonic")
def test_variable_parallel1(self):
wins = ('2s',)
sizes = (121,)
if LONG_TEST:
wins = ('1s', '2s', '3s', '4s')
# XXX: Pandas returns time = [np.nan] for size==1 for some reason
sizes = (2, 10, 11, 121, 1000)
# all functions except apply
for w, func_name in itertools.product(wins, test_funcs):
func_text = "def test_impl(n):\n"
func_text += " df = pd.DataFrame({'B': np.arange(n), 'time': "
func_text += " pd.DatetimeIndex(np.arange(n) * 1000000000)})\n"
func_text += " res = df.rolling('{}', on='time').{}()\n".format(w, func_name)
func_text += " return res.B.sum()\n"
loc_vars = {}
exec(func_text, {'pd': pd, 'np': np}, loc_vars)
test_impl = loc_vars['test_impl']
hpat_func = self.jit(test_impl)
for n in sizes:
np.testing.assert_almost_equal(hpat_func(n), test_impl(n))
self.assertEqual(count_array_REPs(), 0)
self.assertEqual(count_parfor_REPs(), 0)
@skip_numba_jit
@unittest.skipIf(platform.system() == 'Windows', "ValueError: time must be monotonic")
def test_variable_apply_parallel1(self):
wins = ('2s',)
sizes = (121,)
if LONG_TEST:
wins = ('1s', '2s', '3s', '4s')
# XXX: Pandas returns time = [np.nan] for size==1 for some reason
sizes = (2, 10, 11, 121, 1000)
# all functions except apply
for w in wins:
func_text = "def test_impl(n):\n"
func_text += " df = pd.DataFrame({'B': np.arange(n), 'time': "
func_text += " pd.DatetimeIndex(np.arange(n) * 1000000000)})\n"
func_text += " res = df.rolling('{}', on='time').apply(lambda a: a.sum())\n".format(w)
func_text += " return res.B.sum()\n"
loc_vars = {}
exec(func_text, {'pd': pd, 'np': np}, loc_vars)
test_impl = loc_vars['test_impl']
hpat_func = self.jit(test_impl)
for n in sizes:
np.testing.assert_almost_equal(hpat_func(n), test_impl(n))
self.assertEqual(count_array_REPs(), 0)
self.assertEqual(count_parfor_REPs(), 0)
@skip_numba_jit
def test_series_fixed1(self):
# test series rolling functions
# all functions except apply
S1 = pd.Series([0, 1, 2, np.nan, 4])
S2 = pd.Series([0, 1, 2, -2, 4])
wins = (3,)
if LONG_TEST:
wins = (2, 3, 5)
centers = (False, True)
for func_name in test_funcs:
func_text = "def test_impl(S, w, c):\n return S.rolling(w, center=c).{}()\n".format(func_name)
loc_vars = {}
exec(func_text, {}, loc_vars)
test_impl = loc_vars['test_impl']
hpat_func = self.jit(test_impl)
for args in itertools.product(wins, centers):
pd.testing.assert_series_equal(hpat_func(S1, *args), test_impl(S1, *args))
pd.testing.assert_series_equal(hpat_func(S2, *args), test_impl(S2, *args))
# test apply
def apply_test_impl(S, w, c):
return S.rolling(w, center=c).apply(lambda a: a.sum())
hpat_func = self.jit(apply_test_impl)
for args in itertools.product(wins, centers):
pd.testing.assert_series_equal(hpat_func(S1, *args), apply_test_impl(S1, *args))
pd.testing.assert_series_equal(hpat_func(S2, *args), apply_test_impl(S2, *args))
@skip_numba_jit
def test_series_cov1(self):
# test series rolling functions
# all functions except apply
S1 = pd.Series([0, 1, 2, np.nan, 4])
S2 = pd.Series([0, 1, 2, -2, 4])
wins = (3,)
if LONG_TEST:
wins = (2, 3, 5)
centers = (False, True)
def test_impl(S, S2, w, c):
return S.rolling(w, center=c).cov(S2)
hpat_func = self.jit(test_impl)
for args in itertools.product([S1, S2], [S1, S2], wins, centers):
pd.testing.assert_series_equal(hpat_func(*args), test_impl(*args))
pd.testing.assert_series_equal(hpat_func(*args), test_impl(*args))
def test_impl2(S, S2, w, c):
return S.rolling(w, center=c).corr(S2)
hpat_func = self.jit(test_impl2)
for args in itertools.product([S1, S2], [S1, S2], wins, centers):
pd.testing.assert_series_equal(hpat_func(*args), test_impl2(*args))
pd.testing.assert_series_equal(hpat_func(*args), test_impl2(*args))
@skip_numba_jit
def test_df_cov1(self):
# test series rolling functions
# all functions except apply
df1 = pd.DataFrame({'A': [0, 1, 2, np.nan, 4], 'B': np.ones(5)})
df2 = pd.DataFrame({'A': [0, 1, 2, -2, 4], 'C': np.ones(5)})
wins = (3,)
if LONG_TEST:
wins = (2, 3, 5)
centers = (False, True)
def test_impl(df, df2, w, c):
return df.rolling(w, center=c).cov(df2)
hpat_func = self.jit(test_impl)
for args in itertools.product([df1, df2], [df1, df2], wins, centers):
pd.testing.assert_frame_equal(hpat_func(*args), test_impl(*args))
pd.testing.assert_frame_equal(hpat_func(*args), test_impl(*args))
def test_impl2(df, df2, w, c):
return df.rolling(w, center=c).corr(df2)
hpat_func = self.jit(test_impl2)
for args in itertools.product([df1, df2], [df1, df2], wins, centers):
pd.testing.assert_frame_equal(hpat_func(*args), test_impl2(*args))
pd.testing.assert_frame_equal(hpat_func(*args), test_impl2(*args))
def _get_assert_equal(self, obj):
if isinstance(obj, pd.Series):
return pd.testing.assert_series_equal
elif isinstance(obj, pd.DataFrame):
return pd.testing.assert_frame_equal
elif isinstance(obj, np.ndarray):
return np.testing.assert_array_equal
return self.assertEqual
def _test_rolling_unsupported_values(self, obj):
def test_impl(obj, window, min_periods, center,
win_type, on, axis, closed):
return obj.rolling(window, min_periods, center,
win_type, on, axis, closed).min()
hpat_func = self.jit(test_impl)
with self.assertRaises(ValueError) as raises:
hpat_func(obj, -1, None, False, None, None, 0, None)
self.assertIn('window must be non-negative', str(raises.exception))
with self.assertRaises(ValueError) as raises:
hpat_func(obj, 1, -1, False, None, None, 0, None)
self.assertIn('min_periods must be >= 0', str(raises.exception))
with self.assertRaises(ValueError) as raises:
hpat_func(obj, 1, 2, False, None, None, 0, None)
self.assertIn('min_periods must be <= window', str(raises.exception))
with self.assertRaises(ValueError) as raises:
hpat_func(obj, 1, 2, False, None, None, 0, None)
self.assertIn('min_periods must be <= window', str(raises.exception))
msg_tmpl = 'Method rolling(). The object {}\n expected: {}'
with self.assertRaises(ValueError) as raises:
hpat_func(obj, 1, None, True, None, None, 0, None)
msg = msg_tmpl.format('center', 'False')
self.assertIn(msg, str(raises.exception))
with self.assertRaises(ValueError) as raises:
hpat_func(obj, 1, None, False, 'None', None, 0, None)
msg = msg_tmpl.format('win_type', 'None')
self.assertIn(msg, str(raises.exception))
with self.assertRaises(ValueError) as raises:
hpat_func(obj, 1, None, False, None, 'None', 0, None)
msg = msg_tmpl.format('on', 'None')
self.assertIn(msg, str(raises.exception))
with self.assertRaises(ValueError) as raises:
hpat_func(obj, 1, None, False, None, None, 1, None)
msg = msg_tmpl.format('axis', '0')
self.assertIn(msg, str(raises.exception))
with self.assertRaises(ValueError) as raises:
hpat_func(obj, 1, None, False, None, None, 0, 'None')
msg = msg_tmpl.format('closed', 'None')
self.assertIn(msg, str(raises.exception))
def _test_rolling_unsupported_types(self, obj):
def test_impl(obj, window, min_periods, center,
win_type, on, axis, closed):
return obj.rolling(window, min_periods, center,
win_type, on, axis, closed).min()
hpat_func = self.jit(test_impl)
msg_tmpl = 'Method rolling(). The object {}\n given: {}\n expected: {}'
with self.assertRaises(TypingError) as raises:
hpat_func(obj, '1', None, False, None, None, 0, None)
msg = msg_tmpl.format('window', 'unicode_type', 'int')
self.assertIn(msg, str(raises.exception))
with self.assertRaises(TypingError) as raises:
hpat_func(obj, 1, '1', False, None, None, 0, None)
msg = msg_tmpl.format('min_periods', 'unicode_type', 'None, int')
self.assertIn(msg, str(raises.exception))
with self.assertRaises(TypingError) as raises:
hpat_func(obj, 1, None, 0, None, None, 0, None)
msg = msg_tmpl.format('center', 'int64', 'bool')
self.assertIn(msg, str(raises.exception))
with self.assertRaises(TypingError) as raises:
hpat_func(obj, 1, None, False, -1, None, 0, None)
msg = msg_tmpl.format('win_type', 'int64', 'str')
self.assertIn(msg, str(raises.exception))
with self.assertRaises(TypingError) as raises:
hpat_func(obj, 1, None, False, None, -1, 0, None)
msg = msg_tmpl.format('on', 'int64', 'str')
self.assertIn(msg, str(raises.exception))
with self.assertRaises(TypingError) as raises:
hpat_func(obj, 1, None, False, None, None, None, None)
msg = msg_tmpl.format('axis', 'none', 'int, str')
self.assertIn(msg, str(raises.exception))
with self.assertRaises(TypingError) as raises:
hpat_func(obj, 1, None, False, None, None, 0, -1)
msg = msg_tmpl.format('closed', 'int64', 'str')
self.assertIn(msg, str(raises.exception))
def _test_rolling_apply_mean(self, obj):
def test_impl(obj, window, min_periods):
def func(x):
if len(x) == 0:
return np.nan
return x.mean()
return obj.rolling(window, min_periods).apply(func)
hpat_func = self.jit(test_impl)
assert_equal = self._get_assert_equal(obj)
for window in range(0, len(obj) + 3, 2):
for min_periods in range(0, window + 1, 2):
with self.subTest(obj=obj, window=window,
min_periods=min_periods):
jit_result = hpat_func(obj, window, min_periods)
ref_result = test_impl(obj, window, min_periods)
assert_equal(jit_result, ref_result)
def _test_rolling_apply_unsupported_types(self, obj):
def test_impl(obj, raw):
def func(x):
if len(x) == 0:
return np.nan
return np.median(x)
return obj.rolling(3).apply(func, raw=raw)
hpat_func = self.jit(test_impl)
with self.assertRaises(TypingError) as raises:
hpat_func(obj, 1)
msg = 'Method rolling.apply(). The object raw\n given: int64\n expected: bool'
self.assertIn(msg, str(raises.exception))
def _test_rolling_apply_args(self, obj):
def test_impl(obj, window, min_periods, q):
def func(x, q):
if len(x) == 0:
return np.nan
return np.quantile(x, q)
return obj.rolling(window, min_periods).apply(func, raw=None, args=(q,))
hpat_func = self.jit(test_impl)
assert_equal = self._get_assert_equal(obj)
for window in range(0, len(obj) + 3, 2):
for min_periods in range(0, window + 1, 2):
for q in [0.25, 0.5, 0.75]:
with self.subTest(obj=obj, window=window,
min_periods=min_periods, q=q):
jit_result = hpat_func(obj, window, min_periods, q)
ref_result = test_impl(obj, window, min_periods, q)
assert_equal(jit_result, ref_result)
def _test_rolling_corr(self, obj, other):
def test_impl(obj, window, min_periods, other):
return obj.rolling(window, min_periods).corr(other)
hpat_func = self.jit(test_impl)
assert_equal = self._get_assert_equal(obj)
for window in range(0, len(obj) + 3, 2):
for min_periods in range(0, window, 2):
with self.subTest(obj=obj, other=other,
window=window, min_periods=min_periods):
jit_result = hpat_func(obj, window, min_periods, other)
ref_result = test_impl(obj, window, min_periods, other)
assert_equal(jit_result, ref_result)
def _test_rolling_corr_with_no_other(self, obj):
def test_impl(obj, window, min_periods):
return obj.rolling(window, min_periods).corr(pairwise=False)
hpat_func = self.jit(test_impl)
assert_equal = self._get_assert_equal(obj)
for window in range(0, len(obj) + 3, 2):
for min_periods in range(0, window, 2):
with self.subTest(obj=obj, window=window,
min_periods=min_periods):
jit_result = hpat_func(obj, window, min_periods)
ref_result = test_impl(obj, window, min_periods)
assert_equal(jit_result, ref_result)
def _test_rolling_corr_unsupported_types(self, obj):
def test_impl(obj, pairwise):
return obj.rolling(3, 3).corr(pairwise=pairwise)
hpat_func = self.jit(test_impl)
with self.assertRaises(TypingError) as raises:
hpat_func(obj, 1)
msg = 'Method rolling.corr(). The object pairwise\n given: int64\n expected: bool'
self.assertIn(msg, str(raises.exception))
def _test_rolling_count(self, obj):
def test_impl(obj, window, min_periods):
return obj.rolling(window, min_periods).count()
hpat_func = self.jit(test_impl)
assert_equal = self._get_assert_equal(obj)
for window in range(0, len(obj) + 3, 2):
for min_periods in range(0, window + 1, 2):
with self.subTest(obj=obj, window=window,
min_periods=min_periods):
jit_result = hpat_func(obj, window, min_periods)
ref_result = test_impl(obj, window, min_periods)
assert_equal(jit_result, ref_result)
def _test_rolling_cov(self, obj, other):
def test_impl(obj, window, min_periods, other, ddof):
return obj.rolling(window, min_periods).cov(other, ddof=ddof)
hpat_func = self.jit(test_impl)
assert_equal = self._get_assert_equal(obj)
for window in range(0, len(obj) + 3, 2):
for min_periods, ddof in product(range(0, window, 2), [0, 1]):
with self.subTest(obj=obj, other=other, window=window,
min_periods=min_periods, ddof=ddof):
jit_result = hpat_func(obj, window, min_periods, other, ddof)
ref_result = test_impl(obj, window, min_periods, other, ddof)
assert_equal(jit_result, ref_result)
def _test_rolling_cov_with_no_other(self, obj):
def test_impl(obj, window, min_periods):
return obj.rolling(window, min_periods).cov(pairwise=False)
hpat_func = self.jit(test_impl)
assert_equal = self._get_assert_equal(obj)
for window in range(0, len(obj) + 3, 2):
for min_periods in range(0, window, 2):
with self.subTest(obj=obj, window=window,
min_periods=min_periods):
jit_result = hpat_func(obj, window, min_periods)
ref_result = test_impl(obj, window, min_periods)
assert_equal(jit_result, ref_result)
def _test_rolling_cov_unsupported_types(self, obj):
def test_impl(obj, pairwise, ddof):
return obj.rolling(3, 3).cov(pairwise=pairwise, ddof=ddof)
hpat_func = self.jit(test_impl)
msg_tmpl = 'Method rolling.cov(). The object {}\n given: {}\n expected: {}'
with self.assertRaises(TypingError) as raises:
hpat_func(obj, 1, 1)
msg = msg_tmpl.format('pairwise', 'int64', 'bool')
self.assertIn(msg, str(raises.exception))
with self.assertRaises(TypingError) as raises:
hpat_func(obj, None, '1')
msg = msg_tmpl.format('ddof', 'unicode_type', 'int')
self.assertIn(msg, str(raises.exception))
def _test_rolling_kurt(self, obj):
def test_impl(obj, window, min_periods):
return obj.rolling(window, min_periods).kurt()
hpat_func = self.jit(test_impl)
assert_equal = self._get_assert_equal(obj)
for window in range(4, len(obj) + 1):
for min_periods in range(window + 1):
with self.subTest(obj=obj, window=window,
min_periods=min_periods):
ref_result = test_impl(obj, window, min_periods)
jit_result = hpat_func(obj, window, min_periods)
assert_equal(jit_result, ref_result)
def _test_rolling_max(self, obj):
def test_impl(obj, window, min_periods):
return obj.rolling(window, min_periods).max()
hpat_func = self.jit(test_impl)
assert_equal = self._get_assert_equal(obj)
# python implementation crashes if window = 0, jit works correctly
for window in range(1, len(obj) + 2):
for min_periods in range(window + 1):
with self.subTest(obj=obj, window=window,
min_periods=min_periods):
jit_result = hpat_func(obj, window, min_periods)
ref_result = test_impl(obj, window, min_periods)
assert_equal(jit_result, ref_result)
def _test_rolling_mean(self, obj):
def test_impl(obj, window, min_periods):
return obj.rolling(window, min_periods).mean()
hpat_func = self.jit(test_impl)
assert_equal = self._get_assert_equal(obj)
for window in range(len(obj) + 2):
for min_periods in range(window):
with self.subTest(obj=obj, window=window,
min_periods=min_periods):
jit_result = hpat_func(obj, window, min_periods)
ref_result = test_impl(obj, window, min_periods)
assert_equal(jit_result, ref_result)
def _test_rolling_median(self, obj):
def test_impl(obj, window, min_periods):
return obj.rolling(window, min_periods).median()
hpat_func = self.jit(test_impl)
assert_equal = self._get_assert_equal(obj)
for window in range(0, len(obj) + 3, 2):
for min_periods in range(0, window + 1, 2):
with self.subTest(obj=obj, window=window,
min_periods=min_periods):
jit_result = hpat_func(obj, window, min_periods)
ref_result = test_impl(obj, window, min_periods)
assert_equal(jit_result, ref_result)
def _test_rolling_min(self, obj):
def test_impl(obj, window, min_periods):
return obj.rolling(window, min_periods).min()
hpat_func = self.jit(test_impl)
assert_equal = self._get_assert_equal(obj)
# python implementation crashes if window = 0, jit works correctly
for window in range(1, len(obj) + 2):
for min_periods in range(window + 1):
with self.subTest(obj=obj, window=window,
min_periods=min_periods):
jit_result = hpat_func(obj, window, min_periods)
ref_result = test_impl(obj, window, min_periods)
assert_equal(jit_result, ref_result)
def _test_rolling_quantile(self, obj):
def test_impl(obj, window, min_periods, quantile):
return obj.rolling(window, min_periods).quantile(quantile)
hpat_func = self.jit(test_impl)
assert_equal = self._get_assert_equal(obj)
quantiles = [0, 0.25, 0.5, 0.75, 1]
for window in range(0, len(obj) + 3, 2):
for min_periods, q in product(range(0, window, 2), quantiles):
with self.subTest(obj=obj, window=window,
min_periods=min_periods, quantiles=q):
jit_result = hpat_func(obj, window, min_periods, q)
ref_result = test_impl(obj, window, min_periods, q)
assert_equal(jit_result, ref_result)
def _test_rolling_quantile_exception_unsupported_types(self, obj):
def test_impl(obj, quantile, interpolation):
return obj.rolling(3, 2).quantile(quantile, interpolation)
hpat_func = self.jit(test_impl)
msg_tmpl = 'Method rolling.quantile(). The object {}\n given: {}\n expected: {}'
with self.assertRaises(TypingError) as raises:
hpat_func(obj, '0.5', 'linear')
msg = msg_tmpl.format('quantile', 'unicode_type', 'float')
self.assertIn(msg, str(raises.exception))
with self.assertRaises(TypingError) as raises:
hpat_func(obj, 0.5, None)
msg = msg_tmpl.format('interpolation', 'none', 'str')
self.assertIn(msg, str(raises.exception))
def _test_rolling_quantile_exception_unsupported_values(self, obj):
def test_impl(obj, quantile, interpolation):
return obj.rolling(3, 2).quantile(quantile, interpolation)
hpat_func = self.jit(test_impl)
with self.assertRaises(ValueError) as raises:
hpat_func(obj, 2, 'linear')
self.assertIn('quantile value not in [0, 1]', str(raises.exception))
with self.assertRaises(ValueError) as raises:
hpat_func(obj, 0.5, 'lower')
self.assertIn('interpolation value not "linear"', str(raises.exception))
def _test_rolling_skew(self, obj):
def test_impl(obj, window, min_periods):
return obj.rolling(window, min_periods).skew()
hpat_func = self.jit(test_impl)
assert_equal = self._get_assert_equal(obj)
for window in range(3, len(obj) + 1):
for min_periods in range(window + 1):
with self.subTest(obj=obj, window=window,
min_periods=min_periods):
ref_result = test_impl(obj, window, min_periods)
jit_result = hpat_func(obj, window, min_periods)
assert_equal(jit_result, ref_result)
def _test_rolling_std(self, obj):
test_impl = rolling_std_usecase
hpat_func = self.jit(test_impl)
assert_equal = self._get_assert_equal(obj)
for window in range(0, len(obj) + 3, 2):
for min_periods, ddof in product(range(0, window, 2), [0, 1]):
with self.subTest(obj=obj, window=window,
min_periods=min_periods, ddof=ddof):
jit_result = hpat_func(obj, window, min_periods, ddof)
ref_result = test_impl(obj, window, min_periods, ddof)
assert_equal(jit_result, ref_result)
def _test_rolling_std_exception_unsupported_ddof(self, obj):
test_impl = rolling_std_usecase
hpat_func = self.jit(test_impl)
window, min_periods, invalid_ddof = 3, 2, '1'
with self.assertRaises(TypingError) as raises:
hpat_func(obj, window, min_periods, invalid_ddof)
msg = 'Method rolling.std(). The object ddof\n given: unicode_type\n expected: int'
self.assertIn(msg, str(raises.exception))
def _test_rolling_sum(self, obj):
def test_impl(obj, window, min_periods):
return obj.rolling(window, min_periods).sum()
hpat_func = self.jit(test_impl)
assert_equal = self._get_assert_equal(obj)
for window in range(len(obj) + 2):
for min_periods in range(window):
with self.subTest(obj=obj, window=window,
min_periods=min_periods):
jit_result = hpat_func(obj, window, min_periods)
ref_result = test_impl(obj, window, min_periods)
assert_equal(jit_result, ref_result)
def _test_rolling_var(self, obj):
test_impl = rolling_var_usecase
hpat_func = self.jit(test_impl)
assert_equal = self._get_assert_equal(obj)
for window in range(0, len(obj) + 3, 2):
for min_periods, ddof in product(range(0, window, 2), [0, 1]):
with self.subTest(obj=obj, window=window,
min_periods=min_periods, ddof=ddof):
jit_result = hpat_func(obj, window, min_periods, ddof)
ref_result = test_impl(obj, window, min_periods, ddof)
assert_equal(jit_result, ref_result)
def _test_rolling_var_exception_unsupported_ddof(self, obj):
test_impl = rolling_var_usecase
hpat_func = self.jit(test_impl)
window, min_periods, invalid_ddof = 3, 2, '1'
with self.assertRaises(TypingError) as raises:
hpat_func(obj, window, min_periods, invalid_ddof)
msg = 'Method rolling.var(). The object ddof\n given: unicode_type\n expected: int'
self.assertIn(msg, str(raises.exception))
@skip_sdc_jit('DataFrame.rolling.min() unsupported exceptions')
def test_df_rolling_unsupported_values(self):
all_data = test_global_input_data_float64
length = min(len(d) for d in all_data)
data = {n: d[:length] for n, d in zip(string.ascii_uppercase, all_data)}
df = pd.DataFrame(data)
self._test_rolling_unsupported_values(df)
@skip_sdc_jit('DataFrame.rolling.min() unsupported exceptions')
def test_df_rolling_unsupported_types(self):
all_data = test_global_input_data_float64
length = min(len(d) for d in all_data)
data = {n: d[:length] for n, d in zip(string.ascii_uppercase, all_data)}
df = pd.DataFrame(data)
self._test_rolling_unsupported_types(df)
@skip_sdc_jit('DataFrame.rolling.apply() unsupported')
def test_df_rolling_apply_mean(self):
all_data = [
list(range(10)), [1., -1., 0., 0.1, -0.1],
[1., np.inf, np.inf, -1., 0., np.inf, np.NINF, np.NINF],
[np.nan, np.inf, np.inf, np.nan, np.nan, np.nan, np.NINF, np.NZERO]
]
length = min(len(d) for d in all_data)
data = {n: d[:length] for n, d in zip(string.ascii_uppercase, all_data)}
df = pd.DataFrame(data)
self._test_rolling_apply_mean(df)
@skip_sdc_jit('DataFrame.rolling.apply() unsupported exceptions')
def test_df_rolling_apply_unsupported_types(self):
all_data = [[1., -1., 0., 0.1, -0.1], [-1., 1., 0., -0.1, 0.1]]
length = min(len(d) for d in all_data)
data = {n: d[:length] for n, d in zip(string.ascii_uppercase, all_data)}
df = pd.DataFrame(data)
self._test_rolling_apply_unsupported_types(df)
@unittest.skip('DataFrame.rolling.apply() unsupported args')
def test_df_rolling_apply_args(self):
all_data = [
list(range(10)), [1., -1., 0., 0.1, -0.1],
[1., np.inf, np.inf, -1., 0., np.inf, np.NINF, np.NINF],
[np.nan, np.inf, np.inf, np.nan, np.nan, np.nan, np.NINF, np.NZERO]
]
length = min(len(d) for d in all_data)
data = {n: d[:length] for n, d in zip(string.ascii_uppercase, all_data)}
df = pd.DataFrame(data)
self._test_rolling_apply_args(df)
@skip_sdc_jit('DataFrame.rolling.corr() unsupported')
def test_df_rolling_corr(self):
all_data = [
list(range(10)), [1., -1., 0., 0.1, -0.1],
[1., np.inf, np.inf, -1., 0., np.inf, np.NINF, np.NINF],
[np.nan, np.inf, np.inf, np.nan, np.nan, np.nan, np.NINF, np.NZERO]
]
length = min(len(d) for d in all_data)
data = {n: d[:length] for n, d in zip(string.ascii_uppercase, all_data)}
df = pd.DataFrame(data)
for d in all_data:
other = pd.Series(d)
self._test_rolling_corr(df, other)
other_all_data = deepcopy(all_data) + [list(range(10))[::-1]]
other_all_data[1] = [-1., 1., 0., -0.1, 0.1, 0.]
other_length = min(len(d) for d in other_all_data)
other_data = {n: d[:other_length] for n, d in zip(string.ascii_uppercase, other_all_data)}
other = pd.DataFrame(other_data)
self._test_rolling_corr(df, other)
@skip_sdc_jit('DataFrame.rolling.corr() unsupported')
def test_df_rolling_corr_no_other(self):
all_data = [
list(range(10)), [1., -1., 0., 0.1, -0.1],
[1., np.inf, np.inf, -1., 0., np.inf, np.NINF, np.NINF],
[np.nan, np.inf, np.inf, np.nan, np.nan, np.nan, np.NINF, np.NZERO]
]
length = min(len(d) for d in all_data)
data = {n: d[:length] for n, d in zip(string.ascii_uppercase, all_data)}
df = pd.DataFrame(data)
self._test_rolling_corr_with_no_other(df)
@skip_sdc_jit('DataFrame.rolling.corr() unsupported exceptions')
def test_df_rolling_corr_unsupported_types(self):
all_data = [[1., -1., 0., 0.1, -0.1], [-1., 1., 0., -0.1, 0.1]]
length = min(len(d) for d in all_data)
data = {n: d[:length] for n, d in zip(string.ascii_uppercase, all_data)}
df = pd.DataFrame(data)
self._test_rolling_corr_unsupported_types(df)
@skip_sdc_jit('DataFrame.rolling.corr() unsupported exceptions')
def test_df_rolling_corr_unsupported_values(self):
def test_impl(df, other, pairwise):
return df.rolling(3, 3).corr(other=other, pairwise=pairwise)
hpat_func = self.jit(test_impl)
msg_tmpl = 'Method rolling.corr(). The object pairwise\n expected: {}'
df = pd.DataFrame({'A': [1., -1., 0., 0.1, -0.1],
'B': [-1., 1., 0., -0.1, 0.1]})
for pairwise in [None, True]:
with self.assertRaises(ValueError) as raises:
hpat_func(df, None, pairwise)
self.assertIn(msg_tmpl.format('False'), str(raises.exception))
other = pd.DataFrame({'A': [-1., 1., 0., -0.1, 0.1],
'C': [1., -1., 0., 0.1, -0.1]})
with self.assertRaises(ValueError) as raises:
hpat_func(df, other, True)
self.assertIn(msg_tmpl.format('False, None'), str(raises.exception))
@skip_sdc_jit('DataFrame.rolling.count() unsupported')
def test_df_rolling_count(self):
all_data = test_global_input_data_float64
length = min(len(d) for d in all_data)
data = {n: d[:length] for n, d in zip(string.ascii_uppercase, all_data)}
df = pd.DataFrame(data)
self._test_rolling_count(df)
@skip_sdc_jit('DataFrame.rolling.cov() unsupported')
def test_df_rolling_cov(self):
all_data = [
list(range(10)), [1., -1., 0., 0.1, -0.1],
[1., np.inf, np.inf, -1., 0., np.inf, np.NINF, np.NINF],
[np.nan, np.inf, np.inf, np.nan, np.nan, np.nan, np.NINF, np.NZERO]
]
length = min(len(d) for d in all_data)
data = {n: d[:length] for n, d in zip(string.ascii_uppercase, all_data)}
df = pd.DataFrame(data)
for d in all_data:
other = pd.Series(d)
self._test_rolling_cov(df, other)
other_all_data = deepcopy(all_data) + [list(range(10))[::-1]]
other_all_data[1] = [-1., 1., 0., -0.1, 0.1]
other_length = min(len(d) for d in other_all_data)
other_data = {n: d[:other_length] for n, d in zip(string.ascii_uppercase, other_all_data)}
other = pd.DataFrame(other_data)
self._test_rolling_cov(df, other)
@skip_sdc_jit('DataFrame.rolling.cov() unsupported')
def test_df_rolling_cov_no_other(self):
all_data = [
list(range(10)), [1., -1., 0., 0.1, -0.1],
[1., np.inf, np.inf, -1., 0., np.inf, np.NINF, np.NINF],
[np.nan, np.inf, np.inf, np.nan, np.nan, np.nan, np.NINF, np.NZERO]
]
length = min(len(d) for d in all_data)
data = {n: d[:length] for n, d in zip(string.ascii_uppercase, all_data)}
df = pd.DataFrame(data)
self._test_rolling_cov_with_no_other(df)
@skip_sdc_jit('DataFrame.rolling.cov() unsupported exceptions')
def test_df_rolling_cov_unsupported_types(self):
all_data = [[1., -1., 0., 0.1, -0.1], [-1., 1., 0., -0.1, 0.1]]
length = min(len(d) for d in all_data)
data = {n: d[:length] for n, d in zip(string.ascii_uppercase, all_data)}
df = pd.DataFrame(data)
self._test_rolling_cov_unsupported_types(df)
@skip_sdc_jit('DataFrame.rolling.cov() unsupported exceptions')
def test_df_rolling_cov_unsupported_values(self):
def test_impl(df, other, pairwise):
return df.rolling(3, 3).cov(other=other, pairwise=pairwise)
hpat_func = self.jit(test_impl)
msg_tmpl = 'Method rolling.cov(). The object pairwise\n expected: {}'
df = pd.DataFrame({'A': [1., -1., 0., 0.1, -0.1],
'B': [-1., 1., 0., -0.1, 0.1]})
for pairwise in [None, True]:
with self.assertRaises(ValueError) as raises:
hpat_func(df, None, pairwise)
self.assertIn(msg_tmpl.format('False'), str(raises.exception))
other = pd.DataFrame({'A': [-1., 1., 0., -0.1, 0.1],
'C': [1., -1., 0., 0.1, -0.1]})
with self.assertRaises(ValueError) as raises:
hpat_func(df, other, True)
self.assertIn(msg_tmpl.format('False, None'), str(raises.exception))
@skip_sdc_jit('Series.rolling.cov() unsupported Series index')
@unittest.expectedFailure
def test_df_rolling_cov_issue_floating_point_rounding(self):
"""
Cover issue of different float rounding in Python and SDC/Numba:
s = np.Series([1., -1., 0., 0.1, -0.1])
s.rolling(2, 0).mean()
Python: SDC/Numba:
0 1.000000e+00 0 1.00
1 0.000000e+00 1 0.00
2 -5.000000e-01 2 -0.50
3 5.000000e-02 3 0.05
4 -1.387779e-17 4 0.00
dtype: float64 dtype: float64
BTW: cov uses mean inside itself
"""
def test_impl(df, window, min_periods, other, ddof):
return df.rolling(window, min_periods).cov(other, ddof=ddof)
hpat_func = self.jit(test_impl)
df = pd.DataFrame({'A': [1., -1., 0., 0.1, -0.1]})
other = pd.DataFrame({'A': [-1., 1., 0., -0.1, 0.1, 0.]})
jit_result = hpat_func(df, 2, 0, other, 1)
ref_result = test_impl(df, 2, 0, other, 1)
pd.testing.assert_frame_equal(jit_result, ref_result)
@skip_sdc_jit('DataFrame.rolling.kurt() unsupported')
def test_df_rolling_kurt(self):
all_data = test_global_input_data_float64
length = min(len(d) for d in all_data)
data = {n: d[:length] for n, d in zip(string.ascii_uppercase, all_data)}
df = pd.DataFrame(data)
self._test_rolling_kurt(df)
@skip_sdc_jit('DataFrame.rolling.max() unsupported')
def test_df_rolling_max(self):
all_data = test_global_input_data_float64
length = min(len(d) for d in all_data)
data = {n: d[:length] for n, d in zip(string.ascii_uppercase, all_data)}
df = pd.DataFrame(data)
self._test_rolling_max(df)
@skip_sdc_jit('DataFrame.rolling.mean() unsupported')
def test_df_rolling_mean(self):
all_data = [
list(range(10)), [1., -1., 0., 0.1, -0.1],
[1., np.inf, np.inf, -1., 0., np.inf, np.NINF, np.NINF],
[np.nan, np.inf, np.inf, np.nan, np.nan, np.nan, np.NINF, np.NZERO]
]
length = min(len(d) for d in all_data)
data = {n: d[:length] for n, d in zip(string.ascii_uppercase, all_data)}
df = pd.DataFrame(data)
self._test_rolling_mean(df)
@skip_sdc_jit('DataFrame.rolling.median() unsupported')
def test_df_rolling_median(self):
all_data = test_global_input_data_float64
length = min(len(d) for d in all_data)
data = {n: d[:length] for n, d in zip(string.ascii_uppercase, all_data)}
df = pd.DataFrame(data)
self._test_rolling_median(df)
@skip_sdc_jit('DataFrame.rolling.min() unsupported')
def test_df_rolling_min(self):
all_data = test_global_input_data_float64
length = min(len(d) for d in all_data)
data = {n: d[:length] for n, d in zip(string.ascii_uppercase, all_data)}
df = pd.DataFrame(data)
self._test_rolling_min(df)
@unittest.expectedFailure
@unittest.skipIf(platform.system() == 'Darwin', 'Segmentation fault on Mac')
@skip_sdc_jit('DataFrame.rolling.min() unsupported')
def test_df_rolling_min_exception_many_columns(self):
def test_impl(df):
return df.rolling(3).min()
hpat_func = self.jit(test_impl)
# more than 19 columns raise SystemError: CPUDispatcher() returned a result with an error set
all_data = test_global_input_data_float64 * 5
length = min(len(d) for d in all_data)
data = {n: d[:length] for n, d in zip(string.ascii_uppercase, all_data)}
df = pd.DataFrame(data)
pd.testing.assert_frame_equal(hpat_func(df), test_impl(df))
@skip_sdc_jit('DataFrame.rolling.quantile() unsupported')
def test_df_rolling_quantile(self):
all_data = [
list(range(10)), [1., -1., 0., 0.1, -0.1],
[1., np.inf, np.inf, -1., 0., np.inf, np.NINF, np.NINF],
[np.nan, np.inf, np.inf, np.nan, np.nan, np.nan, np.NINF, np.NZERO]
]
length = min(len(d) for d in all_data)
data = {n: d[:length] for n, d in zip(string.ascii_uppercase, all_data)}
df = pd.DataFrame(data)
self._test_rolling_quantile(df)
@skip_sdc_jit('DataFrame.rolling.quantile() unsupported exceptions')
def test_df_rolling_quantile_exception_unsupported_types(self):
all_data = [[1., -1., 0., 0.1, -0.1], [-1., 1., 0., -0.1, 0.1]]
length = min(len(d) for d in all_data)
data = {n: d[:length] for n, d in zip(string.ascii_uppercase, all_data)}
df = pd.DataFrame(data)
self._test_rolling_quantile_exception_unsupported_types(df)
@skip_sdc_jit('DataFrame.rolling.quantile() unsupported exceptions')
def test_df_rolling_quantile_exception_unsupported_values(self):
all_data = [[1., -1., 0., 0.1, -0.1], [-1., 1., 0., -0.1, 0.1]]
length = min(len(d) for d in all_data)
data = {n: d[:length] for n, d in zip(string.ascii_uppercase, all_data)}
df = pd.DataFrame(data)
self._test_rolling_quantile_exception_unsupported_values(df)
@skip_sdc_jit('DataFrame.rolling.skew() unsupported')
def test_df_rolling_skew(self):
all_data = test_global_input_data_float64
length = min(len(d) for d in all_data)
data = {n: d[:length] for n, d in zip(string.ascii_uppercase, all_data)}
df = pd.DataFrame(data)
self._test_rolling_skew(df)
@skip_sdc_jit('DataFrame.rolling.std() unsupported')
def test_df_rolling_std(self):
all_data = [
list(range(10)), [1., -1., 0., 0.1, -0.1],
[1., np.inf, np.inf, -1., 0., np.inf, np.NINF, np.NINF],
[np.nan, np.inf, np.inf, np.nan, np.nan, np.nan, np.NINF, np.NZERO]
]
length = min(len(d) for d in all_data)
data = {n: d[:length] for n, d in zip(string.ascii_uppercase, all_data)}
df = pd.DataFrame(data)
self._test_rolling_std(df)
@skip_sdc_jit('DataFrame.rolling.std() unsupported exceptions')
def test_df_rolling_std_exception_unsupported_ddof(self):
all_data = [[1., -1., 0., 0.1, -0.1], [-1., 1., 0., -0.1, 0.1]]
length = min(len(d) for d in all_data)
data = {n: d[:length] for n, d in zip(string.ascii_uppercase, all_data)}
df = pd.DataFrame(data)
self._test_rolling_std_exception_unsupported_ddof(df)
@skip_sdc_jit('DataFrame.rolling.sum() unsupported')
def test_df_rolling_sum(self):
all_data = [
list(range(10)), [1., -1., 0., 0.1, -0.1],
[1., np.inf, np.inf, -1., 0., np.inf, np.NINF, np.NINF],
[np.nan, np.inf, np.inf, np.nan, np.nan, np.nan, np.NINF, np.NZERO]
]
length = min(len(d) for d in all_data)
data = {n: d[:length] for n, d in zip(string.ascii_uppercase, all_data)}
df = pd.DataFrame(data)
self._test_rolling_sum(df)
@skip_sdc_jit('DataFrame.rolling.var() unsupported')
def test_df_rolling_var(self):
all_data = [
list(range(10)), [1., -1., 0., 0.1, -0.1],
[1., np.inf, np.inf, -1., 0., np.inf, np.NINF, np.NINF],
[np.nan, np.inf, np.inf, np.nan, np.nan, np.nan, np.NINF, np.NZERO]
]
length = min(len(d) for d in all_data)
data = {n: d[:length] for n, d in zip(string.ascii_uppercase, all_data)}
df = pd.DataFrame(data)
self._test_rolling_var(df)
@skip_sdc_jit('DataFrame.rolling.var() unsupported exceptions')
def test_df_rolling_var_exception_unsupported_ddof(self):
all_data = [[1., -1., 0., 0.1, -0.1], [-1., 1., 0., -0.1, 0.1]]
length = min(len(d) for d in all_data)
data = {n: d[:length] for n, d in zip(string.ascii_uppercase, all_data)}
df = pd.DataFrame(data)
self._test_rolling_var_exception_unsupported_ddof(df)
@skip_sdc_jit('Series.rolling.min() unsupported exceptions')
def test_series_rolling_unsupported_values(self):
series = pd.Series(test_global_input_data_float64[0])
self._test_rolling_unsupported_values(series)
@skip_sdc_jit('Series.rolling.min() unsupported exceptions')
def test_series_rolling_unsupported_types(self):
series = pd.Series(test_global_input_data_float64[0])
self._test_rolling_unsupported_types(series)
@skip_sdc_jit('Series.rolling.apply() unsupported Series index')
def test_series_rolling_apply_mean(self):
all_data = [
list(range(10)), [1., -1., 0., 0.1, -0.1],
[1., np.inf, np.inf, -1., 0., np.inf, np.NINF, np.NINF],
[np.nan, np.inf, np.inf, np.nan, np.nan, np.nan, np.NINF, np.NZERO]
]
indices = [list(range(len(data)))[::-1] for data in all_data]
for data, index in zip(all_data, indices):
series = pd.Series(data, index, name='A')
self._test_rolling_apply_mean(series)
@skip_sdc_jit('Series.rolling.apply() unsupported exceptions')
def test_series_rolling_apply_unsupported_types(self):
series = pd.Series([1., -1., 0., 0.1, -0.1])
self._test_rolling_apply_unsupported_types(series)
@unittest.skip('Series.rolling.apply() unsupported args')
def test_series_rolling_apply_args(self):
all_data = [
list(range(10)), [1., -1., 0., 0.1, -0.1],
[1., np.inf, np.inf, -1., 0., np.inf, np.NINF, np.NINF],
[np.nan, np.inf, np.inf, np.nan, np.nan, np.nan, np.NINF, np.NZERO]
]
indices = [list(range(len(data)))[::-1] for data in all_data]
for data, index in zip(all_data, indices):
series = pd.Series(data, index, name='A')
self._test_rolling_apply_args(series)
@skip_sdc_jit('Series.rolling.corr() unsupported Series index')
def test_series_rolling_corr(self):
all_data = [
list(range(10)), [1., -1., 0., 0.1, -0.1],
[-1., 1., 0., -0.1, 0.1, 0.],
[1., np.inf, np.inf, -1., 0., np.inf, np.NINF, np.NINF],
[np.nan, np.inf, np.inf, np.nan, np.nan, np.nan, np.NINF, np.NZERO]
]
for main_data, other_data in product(all_data, all_data):
series = pd.Series(main_data)
other = pd.Series(other_data)
self._test_rolling_corr(series, other)
@skip_sdc_jit('Series.rolling.corr() unsupported Series index')
def test_series_rolling_corr_diff_length(self):
def test_impl(series, window, other):
return series.rolling(window).corr(other)
hpat_func = self.jit(test_impl)
series = pd.Series([1., -1., 0., 0.1, -0.1])
other = pd.Series(gen_frand_array(40))
window = 5
jit_result = hpat_func(series, window, other)
ref_result = test_impl(series, window, other)
pd.testing.assert_series_equal(jit_result, ref_result)
@skip_sdc_jit('Series.rolling.corr() unsupported Series index')
def test_series_rolling_corr_with_no_other(self):
all_data = [
list(range(10)), [1., -1., 0., 0.1, -0.1],
[1., np.inf, np.inf, -1., 0., np.inf, np.NINF, np.NINF],
[np.nan, np.inf, np.inf, np.nan, np.nan, np.nan, np.NINF, np.NZERO]
]
for data in all_data:
series = pd.Series(data)
self._test_rolling_corr_with_no_other(series)
@skip_sdc_jit('Series.rolling.corr() unsupported exceptions')
def test_series_rolling_corr_unsupported_types(self):
series = pd.Series([1., -1., 0., 0.1, -0.1])
self._test_rolling_corr_unsupported_types(series)
@skip_sdc_jit('Series.rolling.corr() unsupported Series index')
@unittest.expectedFailure # https://jira.devtools.intel.com/browse/SAT-2377
def test_series_rolling_corr_index(self):
def test_impl(S1, S2):
return S1.rolling(window=3).corr(S2)
hpat_func = self.jit(test_impl)
n = 11
np.random.seed(0)
index_values = np.arange(n)
np.random.shuffle(index_values)
S1 = pd.Series(np.arange(n), index=index_values, name='A')
np.random.shuffle(index_values)
S2 = pd.Series(2 * np.arange(n) - 5, index=index_values, name='B')
result = hpat_func(S1, S2)
result_ref = test_impl(S1, S2)
pd.testing.assert_series_equal(result, result_ref)
@skip_sdc_jit('Series.rolling.count() unsupported Series index')
def test_series_rolling_count(self):
all_data = test_global_input_data_float64
indices = [list(range(len(data)))[::-1] for data in all_data]
for data, index in zip(all_data, indices):
series = pd.Series(data, index, name='A')
self._test_rolling_count(series)
@skip_sdc_jit('Series.rolling.cov() unsupported Series index')
def test_series_rolling_cov(self):
all_data = [
list(range(5)), [1., -1., 0., 0.1, -0.1],
[1., np.inf, np.inf, -1., 0., np.inf, np.NINF, np.NINF],
[np.nan, np.inf, np.inf, np.nan, np.nan, np.nan, np.NINF, np.NZERO]
]
for main_data, other_data in product(all_data, all_data):
series = pd.Series(main_data)
other = pd.Series(other_data)
self._test_rolling_cov(series, other)
@skip_sdc_jit('Series.rolling.cov() unsupported Series index')
def test_series_rolling_cov_diff_length(self):
def test_impl(series, window, other):
return series.rolling(window).cov(other)
hpat_func = self.jit(test_impl)
series = pd.Series([1., -1., 0., 0.1, -0.1])
other = pd.Series(gen_frand_array(40))
window = 5
jit_result = hpat_func(series, window, other)
ref_result = test_impl(series, window, other)
pd.testing.assert_series_equal(jit_result, ref_result)
@skip_sdc_jit('Series.rolling.cov() unsupported Series index')
def test_series_rolling_cov_no_other(self):
all_data = [
list(range(5)), [1., -1., 0., 0.1, -0.1],
[1., np.inf, np.inf, -1., 0., np.inf, np.NINF, np.NINF],
[np.nan, np.inf, np.inf, np.nan, np.nan, np.nan, np.NINF, np.NZERO]
]
for data in all_data:
series =
|
pd.Series(data)
|
pandas.Series
|
#!/usr/bin/env python3
import RPi.GPIO as GPIO
import time
import threading
import logging
import pandas as pd
import numpy as np
from tzlocal import get_localzone
from flask import Flask, render_template, url_for, request
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(threadName)s - %(name)s - %(levelname)s - %(message)s')
GPIO.setmode(GPIO.BCM)
logger = logging.getLogger(__name__)
from rpiweather import temphumid
from rpiweather import temppressure
from rpiweather import data
from rpiweather import outside_weather
from rpiweather import dust
temppressure.start_recording()
temphumid.start_recording()
outside_weather.start_recording()
dust.start_recording()
app = Flask("rpiweather")
def format_timestamps(series):
local_tz = get_localzone()
return list(
str(dt.tz_localize("UTC").tz_convert(local_tz)) for dt in series
)
@app.route("/")
def index():
lookbehind = int(request.args.get('lookbehind', 24))
bigarray = data.get_recent_datapoints(lookbehind)
logger.info("Total datapoint count: %d" % len(bigarray))
df =
|
pd.DataFrame(bigarray, columns=['time', 'type', 'value'])
|
pandas.DataFrame
|
############################################################################################
#Copyright 2021 Google LLC
#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
#
# https://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 pdb
from sklearn.metrics import balanced_accuracy_score, classification_report
from sklearn.metrics import confusion_matrix, roc_auc_score, accuracy_score
from sklearn.metrics import roc_auc_score, mean_squared_error, mean_absolute_error
from collections import defaultdict
import pandas as pd
import numpy as np
pd.set_option('display.max_columns',500)
import matplotlib.pyplot as plt
import copy
import warnings
warnings.filterwarnings(action='ignore')
import functools
# Make numpy values easier to read.
np.set_printoptions(precision=3, suppress=True)
################################################################################
import tensorflow as tf
np.random.seed(42)
tf.random.set_seed(42)
from tensorflow.keras import layers
from tensorflow import keras
from tensorflow.keras.layers.experimental.preprocessing import Normalization, StringLookup
from tensorflow.keras.layers.experimental.preprocessing import IntegerLookup, CategoryEncoding
from tensorflow.keras.layers.experimental.preprocessing import TextVectorization
from tensorflow.keras.optimizers import SGD, Adam, RMSprop
from tensorflow.keras import layers
from tensorflow.keras import optimizers
from tensorflow.keras.models import Model, load_model
from tensorflow.keras import callbacks
from tensorflow.keras import backend as K
from tensorflow.keras import utils
from tensorflow.keras.layers import BatchNormalization
from tensorflow.keras.optimizers import SGD
from tensorflow.keras import regularizers
from tensorflow.keras import layers
from tensorflow.keras.models import Model, load_model
################################################################################
from deep_autoviml.modeling.one_cycle import OneCycleScheduler
##### Suppress all TF2 and TF1.x warnings ###################
tf2logger = tf.get_logger()
tf2logger.warning('Silencing TF2.x warnings')
tf2logger.root.removeHandler(tf2logger.root.handlers)
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
################################################################################
import os
def check_if_GPU_exists(verbose=0):
GPU_exists = False
gpus = tf.config.list_physical_devices('GPU')
logical_gpus = tf.config.list_logical_devices('GPU')
tpus = tf.config.list_logical_devices('TPU')
#### In some cases like Kaggle kernels, the GPU is not enabled. Hence this check.
if logical_gpus:
# Restrict TensorFlow to only use the first GPU
if verbose:
print("GPUs found in this device...: ")
print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPU")
if len(logical_gpus) > 1:
device = "gpus"
else:
device = "gpu"
try:
tf.config.experimental.set_visible_devices(gpus[0], 'GPU')
except RuntimeError as e:
# Visible devices must be set before GPUs have been initialized
print(e)
try:
# Currently, memory growth needs to be the same across GPUs
for gpu in gpus:
tf.config.experimental.set_memory_growth(gpu, True)
print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPUs")
except RuntimeError as e:
# Memory growth must be set before GPUs have been initialized
print(e)
elif tpus:
device = "tpu"
print("GPUs found in this device...: ")
if verbose:
print("Listing all TPU devices: ")
for tpu in tpus:
print(tpu)
else:
print('Only CPU found on this device')
device = "cpu"
#### Set Strategy ##########
if device == "tpu":
try:
resolver = tf.distribute.cluster_resolver.TPUClusterResolver(tpu='')
tf.config.experimental_connect_to_cluster(resolver)
# This is the TPU initialization code that has to be at the beginning.
tf.tpu.experimental.initialize_tpu_system(resolver)
strategy = tf.distribute.TPUStrategy(resolver)
if verbose:
print('Setting TPU strategy using %d devices' %strategy.num_replicas_in_sync)
except:
if verbose:
print('Setting TPU strategy using Colab...')
resolver = tf.distribute.cluster_resolver.TPUClusterResolver(tpu='grpc://' + os.environ['COLAB_TPU_ADDR'])
tf.config.experimental_connect_to_cluster(resolver)
# This is the TPU initialization code that has to be at the beginning.
tf.tpu.experimental.initialize_tpu_system(resolver)
strategy = tf.distribute.TPUStrategy(resolver)
elif device == "gpu":
strategy = tf.distribute.MirroredStrategy()
if verbose:
print('Setting Mirrored GPU strategy using %d devices' %strategy.num_replicas_in_sync)
elif device == "gpus":
strategy = tf.distribute.MultiWorkerMirroredStrategy()
if verbose:
print('Setting Multiworker GPU strategy using %d devices' %strategy.num_replicas_in_sync)
else:
strategy = tf.distribute.OneDeviceStrategy(device='/device:CPU:0')
if verbose:
print('Setting CPU strategy using %d devices' %strategy.num_replicas_in_sync)
return strategy
######################################################################################
def print_one_row_from_tf_dataset(test_ds):
"""
No matter how big a dataset or batch size, this handy function will print the first row.
This way you can test what's in each row of a tensorflow dataset that you sent in as input
You need to provide at least one column in the dataset for it to check if it should print it.
Inputs:
-------
test_ds: tf.data.DataSet - this must be batched and num_epochs must be an integer.
- otherwise it won't print!
"""
try:
if isinstance(test_ds, tuple):
dict_row = list(test_ds.as_numpy_iterator())[0]
else:
dict_row = test_ds
print("Printing one batch from the dataset:")
preds = list(dict_row.element_spec[0].keys())
if dict_row.element_spec[0][preds[0]].shape[0] is None or isinstance(
dict_row.element_spec[0][preds[0]].shape[0], int):
for batch, head in dict_row.take(1):
for labels, value in batch.items():
print("{:40s}: {}".format(labels, value.numpy()[:4]))
except:
print(' Error printing. Continuing...')
#########################################################################################
def print_one_row_from_tf_label(test_label):
"""
No matter how big a dataset or batch size, this handy function will print the first row.
This way you can test what's in each row of a tensorflow dataset that you sent in as input
You need to provide at least one column in the dataset for it to check if it should print it.
Inputs:
-------
test_label: tf.data.DataSet - this must be batched and num_epochs must be an integer.
- otherwise it won't print!
"""
if isinstance(test_label, tuple):
dict_row = list(test_label.as_numpy_iterator())[0]
else:
dict_row = test_label
preds = list(dict_row.element_spec[0].keys())
try:
### This is for multilabel problems only ####
if len(dict_row.element_spec[1]) >= 1:
labels = list(dict_row.element_spec[1].keys())
for feats, labs in dict_row.take(1):
for each_label in labels:
print(' label = %s, samples: %s' %(each_label, labs[each_label]))
except:
### This is for single problems only ####
if dict_row.element_spec[0][preds[0]].shape[0] is None or isinstance(
dict_row.element_spec[0][preds[0]].shape[0], int):
for feats, labs in dict_row.take(1):
print(" samples from label: %s" %(labs.numpy().tolist()[:10]))
##########################################################################################
from sklearn.base import TransformerMixin
from collections import defaultdict
import pandas as pd
import numpy as np
class My_LabelEncoder(TransformerMixin):
"""
################################################################################################
###### This Label Encoder class works just like sklearn's Label Encoder! #####################
##### You can label encode any column in a data frame using this new class. But unlike sklearn,
the beauty of this function is that it can take care of NaN's and unknown (future) values.
It uses the same fit() and fit_transform() methods of sklearn's LabelEncoder class.
################################################################################################
Usage:
MLB = My_LabelEncoder()
train[column] = MLB.fit_transform(train[column])
test[column] = MLB.transform(test[column])
"""
def __init__(self):
self.transformer = defaultdict(str)
self.inverse_transformer = defaultdict(str)
def fit(self,testx):
if isinstance(testx, pd.Series):
pass
elif isinstance(testx, np.ndarray):
testx = pd.Series(testx)
else:
return testx
outs = np.unique(testx.factorize()[0])
ins = np.unique(testx.factorize()[1]).tolist()
if -1 in outs:
ins.insert(0,np.nan)
self.transformer = dict(zip(ins,outs.tolist()))
self.inverse_transformer = dict(zip(outs.tolist(),ins))
return self
def transform(self, testx):
if isinstance(testx, pd.Series):
pass
elif isinstance(testx, np.ndarray):
testx = pd.Series(testx)
else:
return testx
ins = np.unique(testx.factorize()[1]).tolist()
missing = [x for x in ins if x not in self.transformer.keys()]
if len(missing) > 0:
for each_missing in missing:
max_val = np.max(list(self.transformer.values())) + 1
self.transformer[each_missing] = max_val
self.inverse_transformer[max_val] = each_missing
### now convert the input to transformer dictionary values
outs = testx.map(self.transformer).values
return outs
def inverse_transform(self, testx):
### now convert the input to transformer dictionary values
if isinstance(testx, pd.Series):
outs = testx.map(self.inverse_transformer).values
elif isinstance(testx, np.ndarray):
outs = pd.Series(testx).map(self.inverse_transformer).values
else:
outs = testx[:]
return outs
#################################################################################
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score, balanced_accuracy_score
#################################################################################
def plot_history(history, metric, targets):
if isinstance(targets, str):
#### This is for single label problems
fig = plt.figure(figsize=(15,6))
#### first metric is always the loss - just plot it!
hist =
|
pd.DataFrame(history.history)
|
pandas.DataFrame
|
#! /usr/bin/env python
"""Check design."""
import os
import sys
import luigi
import shutil
from luigi import LocalTarget
from luigi.util import inherits, requires
import pandas as pd
import gffutils
import glob
DIR = os.path.dirname(os.path.realpath(__file__))
script_dir = os.path.abspath(os.path.join(DIR, "../../scripts"))
os.environ["PATH"] += ":" + script_dir
sys.path.insert(0, script_dir)
import logging
import json
from Bio.Seq import Seq
from Bio.Alphabet import generic_dna
import re
from functools import reduce
from piret.miscs import RefFile
class conversions(luigi.Task):
"""Convert gene count, RPKM, fold change table to GeneID or locus tag
and also to ones that have EC# or KO# when available."""
gff_file = luigi.Parameter()
gene_count_table = luigi.Parameter()
gene_RPKM_table = luigi.Parameter()
gene_CPM_table = luigi.Parameter()
gene_fc_table = luigi.Parameter()
def output(self):
"""Expected output of DGE using edgeR."""
edger_dir = os.path.join(self.workdir, "edgeR", self.kingdom)
out_filepath = os.path.join(edger_dir, "summary_updown.csv")
return LocalTarget(out_filepath)
def run(self):
"""Run edgeR."""
fcount_dir = os.path.join(self.workdir, "featureCounts", self.kingdom)
edger_dir = os.path.join(self.workdir, "edgeR", self.kingdom)
if not os.path.exists(edger_dir):
os.makedirs(edger_dir)
for file in os.listdir(fcount_dir):
if file.endswith("tsv"):
name = file.split("_")[-2]
edger_list = ["-r", os.path.join(fcount_dir, file),
"-e", self.exp_design,
"-p", self.p_value,
"-n", name,
"-o", edger_dir]
# TODO: get the output that has locus tag
edger_cmd = EdgeR[edger_list]
logger = logging.getLogger('luigi-interface')
logger.info(edger_cmd)
edger_cmd()
if file == "gene_count.tsv":
# TODO:convert the first column to locus tag
if self.pathway is True:
path_list = ["-d", edger_dir,
"-m", "edgeR", "-c",
self.org_code] # get pathway information
path_cmd = plot_pathway[path_list]
logger.info(path_cmd)
path_cmd()
if self.GAGE is True:
gage_list = ["-d", edger_dir, "-m",
"edgeR", "-c", self.org_code]
gage_cmd = gage_analysis[gage_list]
logger.info(gage_cmd)
gage_cmd()
self.summ_summ()
class conver2json(luigi.Task):
""" Summarizes and converts all the results to one big JSON file."""
gff_file = luigi.Parameter()
fasta_file = luigi.Parameter()
pathway = luigi.BoolParameter()
kingdom = luigi.Parameter()
workdir = luigi.Parameter()
method = luigi.ListParameter()
NovelRegions = luigi.BoolParameter()
def requires(self):
flist = []
if "edgeR" in self.method:
cpm_file = os.path.join(self.workdir, "processes", "edgeR",
self.kingdom, "gene",
"gene" + "_count_CPM.csv")
flist.append(cpm_file)
elif "DESeq2" in self.method:
fpm_file = os.path.join(self.workdir, "processes", "DESeq2",
self.kingdom, "gene",
"gene" + "_count_FPKM.csv")
flist.append(fpm_file)
return [RefFile(f) for f in flist]
def output(self):
"""Expected output JSON."""
if self.kingdom == "prokarya":
jfile = os.path.join(self.workdir, "prokarya_out.json")
return LocalTarget(jfile)
elif self.kingdom == "eukarya":
jfile = os.path.join(self.workdir, "eukarya_out.json")
return LocalTarget(jfile)
def run(self):
""" Create JSON files."""
if self.kingdom == "prokarya":
jfile = os.path.join(self.workdir, "prokarya_out.json")
elif self.kingdom == "eukarya":
jfile = os.path.join(self.workdir, "eukarya_out.json")
self.gff2json(jfile)
def gff2json(self, out_json):
"""A function that converts a gff file to JSON file."""
# read in the gff file to a database
if os.path.exists(os.path.join(self.workdir, "processes",
"databases")) is False:
os.makedirs(os.path.join(self.workdir, "processes",
"databases"))
db_out = os.path.join(self.workdir, "processes", "databases",
self.kingdom,
"piret.db")
if os.path.exists(db_out) is False:
# create db if not already present
db = gffutils.create_db(self.gff_file, dbfn=db_out, force=True,
keep_order=True,
merge_strategy="create_unique")
else:
# read db if its already present
db = gffutils.FeatureDB(db_out, keep_order=True)
if "edgeR" in self.method:
edger_summ_cds = self.pm_summary("CDS", "edgeR")
edger_summ_genes = self.pm_summary("gene", "edgeR")
dge_edger_cds = self.dge_summary("CDS", "edgeR")
dge_edger_gene = self.dge_summary("gene", "edgeR")
else:
edger_summ_cds = ({}, {})
edger_summ_genes = ({}, {})
dge_edger_cds = {}
dge_edger_gene = {}
if "DESeq2" in self.method:
deseq_summ_cds = self.pm_summary("CDS", "DESeq2")
deseq_summ_genes = self.pm_summary("gene", "DESeq2")
dge_deseq_cds = self.dge_summary("CDS", "DESeq2")
dge_deseq_gene = self.dge_summary("gene", "DESeq2")
else:
deseq_summ_cds = ({}, {})
deseq_summ_genes = ({}, {})
dge_deseq_cds = {}
dge_deseq_gene = {}
if "ballgown" in self.method:
ballgown_gene_pm = self.pm_summary_ballgown()
else:
ballgown_gene_pm = {}
stringtie_tpms = self.stringtie_tpm()
read_summ_cds = self.read_summary("CDS")
read_summ_gene = self.read_summary("gene")
read_summ_rRNA = self.read_summary("rRNA")
read_summ_tRNA = self.read_summary("tRNA")
read_summ_exon = self.read_summary("exon")
if self.NovelRegions is True:
read_summ_NovelRegion = self.read_summary("NovelRegion")
emaps = self.get_emapper()
with open(out_json, "w") as json_file:
json_list = []
for feat_obj in db.all_features():
feat_dic = {} # an empty dictionary to append features
feat_dic['seqid'] = feat_obj.seqid
feat_dic['id'] = feat_obj.id
feat_dic['source'] = feat_obj.source
feat_type = feat_obj.featuretype
feat_dic['featuretype'] = feat_type
feat_dic['start'] = feat_obj.start
feat_dic['end'] = feat_obj.end
feat_dic["length"] = abs(feat_obj.end - feat_obj.start) + 1
feat_dic['strand'] = feat_obj.strand
feat_dic['frame'] = feat_obj.frame
try:
feat_dic['locus_tag'] = feat_obj.attributes['locus_tag'][0]
except KeyError:
pass
try:
feat_dic['Note'] = feat_obj.attributes['Note']
except KeyError:
pass
feat_dic['extra'] = feat_obj.extra
if feat_type != "region":
try:
nt_seqs = feat_obj.sequence(self.fasta_file)
nt_obj = Seq(nt_seqs, generic_dna)
feat_dic['nt_seq'] = nt_seqs
except KeyError:
pass
# ============================================================================#
if feat_type == "CDS":
# translate the CDS
feat_dic['aa_seqs'] = self.translate(nt_obj, "CDS")
# assign FPKMs and FPMs
self.assign_scores(feat_dic=feat_dic,
edger_sdic=edger_summ_cds,
deseq_sdic=deseq_summ_cds,
feat_id=feat_obj.id)
# assign read numbers
try:
feat_dic["read_count"] = read_summ_cds[feat_obj.id]
except KeyError:
feat_dic["read_count"] = None
# assign dge information
self.assign_dges(feat_type="CDS", feat_dic=feat_dic,
feat_id=feat_obj.id,
method="edgeR", dge_dict=dge_edger_cds)
self.assign_dges(feat_type="CDS", feat_dic=feat_dic,
feat_id=feat_obj.id,
method="DESeq2", dge_dict=dge_deseq_cds)
# assign EC#s, KOs, etc.
try:
feat_dic["emapper"] = emaps[feat_obj.id]
except KeyError:
feat_dic["emapper"] = None
# ============================================================================#
elif feat_type == "NovelRegion":
try:
feat_dic["read_count"] = read_summ_NovelRegion[feat_obj.id]
except KeyError:
feat_dic["read_count"] = None
# ============================================================================#
elif feat_type == 'rRNA':
try:
feat_dic["read_count"] = read_summ_rRNA[feat_obj.id]
except KeyError:
feat_dic["read_count"] = None
# ============================================================================#
elif feat_type == 'tRNA':
try:
feat_dic["read_count"] = read_summ_tRNA[feat_obj.id]
except KeyError:
feat_dic["read_count"] = None
# ============================================================================#
elif feat_type == 'exon':
try:
feat_dic["read_count"] = read_summ_exon[feat_obj.id]
except KeyError:
feat_dic["read_count"] = None
# ============================================================================#
elif feat_type == "gene":
# assign scores
self.assign_scores(feat_dic=feat_dic,
edger_sdic=edger_summ_genes,
deseq_sdic=deseq_summ_genes,
feat_id=feat_obj.id)
# assign read numbers
try:
feat_dic["read_count"] = read_summ_gene[feat_obj.id]
except KeyError:
feat_dic["read_count"] = None
# assign ballgown info
try:
feat_dic["ballgown_values"] = ballgown_gene_pm[feat_obj.id]
except KeyError:
feat_dic["ballgown_values"] = None
# assign stringtie
try:
feat_dic["stringtie_values"] = stringtie_tpms[feat_obj.id]
except KeyError:
feat_dic["stringtie_values"] = None
# assign dge information
self.assign_dges(feat_type="gene", feat_dic=feat_dic,
feat_id=feat_obj.id,
method="edgeR", dge_dict=dge_edger_gene)
self.assign_dges(feat_type="gene", feat_dic=feat_dic,
feat_id=feat_obj.id,
method="DESeq2", dge_dict=dge_deseq_gene)
else:
pass
# just to make sure that keys are strings, else json dump fails
feat_dic_str = {}
for key, value in feat_dic.items():
feat_dic_str[str(key)] = value
json_list.append(feat_dic_str)
json.dump(json_list, json_file, indent=4)
# meta_list = ["seqid", "id", "source", "featuretype", "start",
# "end", "length", "strand", "frame", "locus_tag",
# "extra"]
# df = pd.io.json.json_normalize(json_list, errors="ignore")
def assign_scores(self, feat_dic, edger_sdic, deseq_sdic, feat_id):
"""Assign scores from edger and deseq to summary dic."""
try:
feat_dic["edger_cpm"] = edger_sdic[0][feat_id]
except KeyError:
feat_dic["edger_cpm"] = None
try:
feat_dic["deseq_fpm"] = deseq_sdic[0][feat_id]
except KeyError:
feat_dic["deseq_fpm"] = None
try:
feat_dic["edger_rpkm"] = edger_sdic[1][feat_id]
except KeyError:
feat_dic["edger_rpkm"] = None
try:
feat_dic["deseq_fpkm"] = deseq_sdic[1][feat_id]
except KeyError:
feat_dic["deseq_fpkm"] = None
def get_emapper(self):
"""get emapper result as a dataframe."""
emapper_files = os.path.join(self.workdir, "processes", "emapper",
self.kingdom,
"emapper.emapper.annotations")
if os.path.exists(emapper_files) is True:
emap = pd.read_csv(emapper_files, sep='\t', skiprows=[0,1,2],
skipinitialspace=True, skipfooter=3,
header=None, engine='python')
emap1 = emap.reset_index()
emap1.columns = emap1.iloc[0]
emap2 = emap1.drop(0).drop([0], axis=1).set_index('#query_name').to_dict(orient="index")
return emap2
else:
return None
def read_summary(self, feat_type):
"""Get read values as a dictionary."""
read_file = os.path.join(self.workdir, "processes", "featureCounts",
self.kingdom, feat_type + "_count_sorted.csv")
if os.path.exists(read_file) is True:
read_data = pd.read_csv(read_file, sep=",",
index_col="Geneid")
read_dict = read_data.drop(["Unnamed: 0", "Chr", "Start", "End",
"Strand", "Length"], axis=1).to_dict(orient="index")
else:
read_dict = {}
for feat, count_dic in read_dict.items():
int_read = {}
feat_read = {}
for samp, count in count_dic.items():
int_read[samp] = int(count)
feat_read[feat] = int_read
# print(feat_read)
read_dict.update(feat_read)
# print(read_dict)
return read_dict
def dge_summary(self, feat_type, method):
"""summarize SGE results from edgeR of DESeq2"""
dge_dir = os.path.join(self.workdir, "processes", method,
self.kingdom, feat_type)
dge_files = [f for f in glob.glob(dge_dir + "**/*et.csv", recursive=True)]
dge_dicts = {}
for file in dge_files:
dge_df =
|
pd.read_csv(file, sep=",", index_col=0)
|
pandas.read_csv
|
#For the computation of average temperatures using GHCN data
import ulmo, pandas as pd, matplotlib.pyplot as plt, numpy as np, csv, pickle
#Grab weather stations that meet criteria (from previous work) and assign lists
st = ulmo.ncdc.ghcn_daily.get_stations(country ='US',elements=['TMAX'],end_year=1950, as_dataframe = True)
ids = pd.read_csv('IDfile.csv')
idnames = [ids.id[x] for x in range(0, len(ids))]
Longitude= []
Latitude = []
ID = []
Elev = []
Name = []
Tmaxavgresult = []
Tminavgresult = []
Tmaxavg = []
Tminavg = []
Tmaxstd = []
Tminstd = []
Tmaxz = []
Tminz = []
Tmaxanom = []
Tminanom = []
maxset = []
minset = []
#
#
#begin loop to isolate values of interest
#
#test loop to verify if works
#rando = np.random.random_integers(len(idnames), size = (10,))
#for x in rando:
for q in range(0,len(ids)-1):
# Grab data and transform to K
a = st.id[idnames[q]]
data = ulmo.ncdc.ghcn_daily.get_data(a, as_dataframe=True)
tmax = data['TMAX'].copy()
tmin = data['TMIN'].copy()
tmax.value = (tmax.value/10.0) + 273.15
tmin.value = (tmin.value/10.0) + 273.15
# Name and save parameters
b = st.longitude[idnames[q]]
c = st.latitude[idnames[q]]
d = st.elevation[idnames[q]]
e = st.name[idnames[q]]
#average only data on a monthly basis and generate x and y coordinates for the years in which El Nino data exists (probably a way more efficient way to do this)
filedatasmax = []
filedatasmin = []
for y in range(1951,2016):
filedatamax = {}
filedatamin = {}
datejan = ''.join([str(y),"-01"])
datefeb = ''.join([str(y),"-02"])
datemar = ''.join([str(y),"-03"])
dateapr = ''.join([str(y),"-04"])
datemay = ''.join([str(y),"-05"])
datejun = ''.join([str(y),"-06"])
datejul = ''.join([str(y),"-07"])
dateaug = ''.join([str(y),"-08"])
datesep = ''.join([str(y),"-09"])
dateoct = ''.join([str(y),"-10"])
datenov = ''.join([str(y),"-11"])
datedec = ''.join([str(y),"-12"])
nanmaxjan = tmax['value'][datejan]
nanminjan = tmin['value'][datejan]
nanmaxfeb = tmax['value'][datefeb]
nanminfeb = tmin['value'][datefeb]
nanmaxmar = tmax['value'][datemar]
nanminmar = tmin['value'][datemar]
nanmaxapr = tmax['value'][dateapr]
nanminapr = tmin['value'][dateapr]
nanmaxmay = tmax['value'][datemay]
nanminmay = tmin['value'][datemay]
nanmaxjun = tmax['value'][datejun]
nanminjun = tmin['value'][datejun]
nanmaxjul = tmax['value'][datejul]
nanminjul = tmin['value'][datejul]
nanmaxaug = tmax['value'][dateaug]
nanminaug = tmin['value'][dateaug]
nanmaxsep = tmax['value'][datesep]
nanminsep = tmin['value'][datesep]
nanmaxoct = tmax['value'][dateoct]
nanminoct = tmin['value'][dateoct]
nanmaxnov = tmax['value'][datenov]
nanminnov = tmin['value'][datenov]
nanmaxdec = tmax['value'][datedec]
nanmindec = tmin['value'][datedec]
#We now concatenate everything
filedatamax = [y, nanmaxjan[~pd.isnull(nanmaxjan)].mean(), nanmaxfeb[~pd.isnull(nanmaxfeb)].mean(),nanmaxmar[~pd.isnull(nanmaxmar)].mean(),nanmaxapr[~pd.isnull(nanmaxapr)].mean(),nanmaxmay[~pd.isnull(nanmaxmay)].mean(),nanmaxjun[~
|
pd.isnull(nanmaxjun)
|
pandas.isnull
|
import pandas as pd
import sys
import matplotlib.pyplot as plt
from pandas_profiling import ProfileReport
sys.path.append("../")
import xfinai_config
def load_data_raw(future_index):
df_raw =
|
pd.read_pickle(f'{xfinai_config.raw_data_path}/{future_index}_{xfinai_config.time_freq}.pkl')
|
pandas.read_pickle
|
import pandas as pd
from argparse import ArgumentParser
from pathlib import Path
from .logger import logger
import sqlite3
import random
import csv
import json
from tqdm import tqdm
DATA_DIR = Path('data')
FOLD = 5
NELA_DIR = DATA_DIR / 'NELA'
Path(NELA_DIR).mkdir(parents=True, exist_ok=True)
NELA_FNAME = '{mode}_{fold}.tsv'
RESAMPLE_LIMIT = 100
def read_constraint_splits():
train_fpath = DATA_DIR / 'train.tsv'
val_fpath = DATA_DIR / 'val.tsv'
test_fpath = DATA_DIR / 'test.tsv'
train = pd.read_csv(train_fpath, quoting=csv.QUOTE_NONE, error_bad_lines=False, sep='\t')
val = pd.read_csv(val_fpath, quoting=csv.QUOTE_NONE, error_bad_lines=False, sep='\t')
test = pd.read_csv(test_fpath, quoting=csv.QUOTE_NONE, error_bad_lines=False, sep='\t')
return {
'train': train,
'val': val,
'test': test
}
def normalize(domain):
domain = domain.strip()
domain = domain.replace(' ', '')
domain = domain.lower()
return domain
def read_simplewiki(path: str):
wiki = pd.read_csv(path, sep='\t')[['title', 'text']]
title = wiki.title.map(lambda x: normalize(x)).to_list()
text = wiki.text.map(lambda x: x.lower()).to_list()
return dict(zip(title, text))
def normalize_source(source: str):
source = source.lower()
source = source.strip()
source = source.replace(" ", "")
return source
def read_nela_assessments(nela_2019_path):
nela_2019_dir = Path(nela_2019_path)
labels_path = nela_2019_dir / 'labels.csv'
labels = pd.read_csv(labels_path)
reliable_sources = labels[labels['aggregated_label'] == 0.0]['source'].unique()
reliable_sources =
|
pd.DataFrame(reliable_sources, columns=['source'])
|
pandas.DataFrame
|
import pandas
import matplotlib.pyplot as plt
import pickle
import numpy as np
import warnings
warnings.filterwarnings("ignore")
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.linear_model import Ridge, Lasso
from sklearn.ensemble import RandomForestRegressor
class MovingTimeRegression:
def __init__(self, cleanedRoute, modelsRoute, scalerRoute, paramsRoute, cleanedFileName): # define data routes and csv names!
self.cleanedRoute = cleanedRoute
self.modelsRoute = modelsRoute
self.scalerRoute = scalerRoute
self.paramsRoute = paramsRoute
self.dataset = pandas.read_csv(cleanedRoute+cleanedFileName, sep="|")
self.allTrainX = None
self.allTestX = None
self.allTrainy = None
self.allTesty = None
self.reducedTrainX = None
self.reducedTestX = None
self.reducedTrainy = None
self.reducedTesty = None
self.baseTrainX = None
self.baseTestX = None
self.baseTrainy = None
self.baseTesty = None
self.allRidgeModel = None
self.reducedRidgeModel = None
self.baseRidgeModel = None
self.allLassoModel = None
self.reducedLassoModel = None
self.baseLassoModel = None
self.allRandomForestModel = None
self.reducedRandomForestModel = None
self.baseRandomForestModel = None
self.allStandardScaler = None
self.reducedStandardScaler = None
self.baseStandardScaler = None
self.CatCols8 = ['#003f5c', '#2f4b7c', '#665191', '#a05195', '#d45087', '#f95d6a', '#ff7c43', '#ffa600']
self.CatCols5 = ['#003f5c', '#3d61f4', '#bc5090', '#ff6361', '#ffa600']
self.CatCols3 = ['#003f5c', '#bc5090', '#ffa600']
print('call .dataset to see the cleaned dataset')
def prepareData(self):
# all data
X = self.dataset.copy()
Y = X['moving_time'].copy()
X.drop(columns=['moving_time', 'elapsed_time', 'average_speed'], inplace=True)
names = X.columns
self.allStandardScaler = StandardScaler()
scaledX = self.allStandardScaler.fit_transform(X)
scaledX = pandas.DataFrame(scaledX, columns=names)
self.allTrainX, self.allTestX, self.allTrainy, self.allTesty = train_test_split(scaledX, Y, random_state=42)
# reduced data
X = self.dataset[['age_0.0', 'age_1.0', 'age_2.0', 'distance', 'elev_high', 'elev_low', 'hashed_id',
'total_elevation_gain', 'trainer_onehot', 'workout_type_11.0', 'workout_type_10.0', 'workout_type_12.0']].copy()
Y = self.dataset['moving_time'].copy()
names = X.columns
self.reducedStandardScaler = StandardScaler()
scaledX = self.reducedStandardScaler.fit_transform(X)
scaledX = pandas.DataFrame(scaledX, columns=names)
self.reducedTrainX, self.reducedTestX, self.reducedTrainy, self.reducedTesty = train_test_split(scaledX, Y,
random_state=42)
# base data
X = self.dataset[['distance', 'elev_high', 'elev_low', 'total_elevation_gain', 'trainer_onehot']].copy()
Y = self.dataset['moving_time'].copy()
names = X.columns
self.baseStandardScaler = StandardScaler()
scaledX = self.baseStandardScaler.fit_transform(X)
scaledX = pandas.DataFrame(scaledX, columns=names)
self.baseTrainX, self.baseTestX, self.baseTrainy, self.baseTesty = train_test_split(scaledX, Y, random_state=42)
# TODO: print info about the 3 dataset and the train-test pars
def trainModels(self, verbose=False, writeToFile=False):
# fitting models on all data
print('-- Fitting models on all data -- ')
if verbose:
print('Calculating best params for Ridge...')
ridgeParams = getBestParamsForRidge(self.allTrainX, self.allTestX, self.allTrainy, self.allTesty)
self.allRidgeModel = Ridge(alpha=ridgeParams['alpha'], solver=ridgeParams['solver'])
self.allRidgeModel.fit(self.allTrainX, self.allTrainy)
if verbose:
print('Done. Params: ')
print(ridgeParams)
print('')
if verbose:
print('Calculating best params for Lasso...')
lassoParams = getBestParamsForLasso(self.allTrainX, self.allTestX, self.allTrainy, self.allTesty)
self.allLassoModel = Lasso(alpha=lassoParams['alpha'])
self.allLassoModel.fit(self.allTrainX, self.allTrainy)
if verbose:
print('Done. Params: ')
print(lassoParams)
print('')
# TODO: calc best params for Random Forest
if verbose:
print('Loading best params for RandomForest...')
forestParams = pickle.load(open(self.paramsRoute+'moving_time_all_random_forest_params.p', 'rb'))
self.allRandomForestModel = RandomForestRegressor(n_estimators=forestParams['n_estimators'],
max_features=forestParams['max_features'],
min_samples_leaf=forestParams['min_samples_leaf'] )
self.allRandomForestModel.fit(self.allTrainX, self.allTrainy)
if verbose:
print('Done. Params: ')
print(forestParams)
print('')
print('Scores on allTesty data: ')
print(' - Ridge: '+str(self.allRidgeModel.score(self.allTestX, self.allTesty)))
print(' - Lasso: '+str(self.allLassoModel.score(self.allTestX, self.allTesty)))
print(' - RandomForest: '+str(self.allRandomForestModel.score(self.allTestX, self.allTesty)))
print('')
# fitting models on reduced data
print('-- Fitting models on reduced data --')
if verbose:
print('Calculating best params for Ridge...')
ridgeParams = getBestParamsForRidge(self.reducedTrainX, self.reducedTestX, self.reducedTrainy, self.reducedTesty)
self.reducedRidgeModel = Ridge(alpha=ridgeParams['alpha'], solver=ridgeParams['solver'])
self.reducedRidgeModel.fit(self.reducedTrainX, self.reducedTrainy)
if verbose:
print('Done. Params: ')
print(ridgeParams)
print('')
if verbose:
print('Calculating best params for Lasso...')
lassoParams = getBestParamsForLasso(self.reducedTrainX, self.reducedTestX, self.reducedTrainy, self.reducedTesty)
self.reducedLassoModel = Lasso(alpha=lassoParams['alpha'])
self.reducedLassoModel.fit(self.reducedTrainX, self.reducedTrainy)
if verbose:
print('Done. Params: ')
print(lassoParams)
print('')
# TODO: calc best params for Random Forest
if verbose:
print('Loading best params for RandomForest...')
forestParams = pickle.load(open(self.paramsRoute + 'moving_time_reduced_random_forest_params.p', 'rb'))
self.reducedRandomForestModel = RandomForestRegressor(n_estimators=forestParams['n_estimators'],
max_features=forestParams['max_features'],
min_samples_leaf=forestParams['min_samples_leaf'])
self.reducedRandomForestModel.fit(self.reducedTrainX, self.reducedTrainy)
if verbose:
print('Done. Params: ')
print(forestParams)
print('')
print('Scores on reudcedTesty data: ')
print(' - Ridge: ' + str(self.reducedRidgeModel.score(self.reducedTestX, self.reducedTesty)))
print(' - Lasso: ' + str(self.reducedLassoModel.score(self.reducedTestX, self.reducedTesty)))
print(' - RandomForest: ' + str(self.reducedRandomForestModel.score(self.reducedTestX, self.reducedTesty)))
print('')
# fitting models on base data
print('-- Fitting models on base data --')
if verbose:
print('Calculating best params for Ridge...')
ridgeParams = getBestParamsForRidge(self.baseTrainX, self.baseTestX, self.baseTrainy,
self.baseTesty)
self.baseRidgeModel = Ridge(alpha=ridgeParams['alpha'], solver=ridgeParams['solver'])
self.baseRidgeModel.fit(self.baseTrainX, self.baseTrainy)
if verbose:
print('Done. Params: ')
print(ridgeParams)
print('')
if verbose:
print('Calculating best params for Lasso...')
lassoParams = getBestParamsForLasso(self.baseTrainX, self.baseTestX, self.baseTrainy,
self.baseTesty)
self.baseLassoModel = Lasso(alpha=lassoParams['alpha'])
self.baseLassoModel.fit(self.baseTrainX, self.baseTrainy)
if verbose:
print('Done. Params: ')
print(lassoParams)
print('')
if verbose:
print('Loading best params for RandomForest...')
forestParams = pickle.load(open(self.paramsRoute + 'moving_time_base_random_forest_params.p', 'rb'))
self.baseRandomForestModel = RandomForestRegressor(n_estimators=forestParams['n_estimators'],
max_features=forestParams['max_features'],
min_samples_leaf=forestParams['min_samples_leaf'])
self.baseRandomForestModel.fit(self.baseTrainX, self.baseTrainy)
if verbose:
print('Done. Params: ')
print(forestParams)
print('')
print('Scores on baseTesty data: ')
print(' - Ridge: ' + str(self.baseRidgeModel.score(self.baseTestX, self.baseTesty)))
print(' - Lasso: ' + str(self.baseLassoModel.score(self.baseTestX, self.baseTesty)))
print(' - RandomForest: ' + str(self.baseRandomForestModel.score(self.baseTestX, self.baseTesty)))
print('')
if writeToFile:
writeRegressionModels(self.allRidgeModel, self.allLassoModel, self.allRandomForestModel, 'all', 'moving',
self.modelsRoute)
writeRegressionModels(self.reducedRidgeModel, self.reducedLassoModel, self.reducedRandomForestModel, 'reduced',
'moving', self.modelsRoute)
writeRegressionModels(self.baseRidgeModel, self.baseLassoModel, self.baseRandomForestModel, 'base', 'moving',
self.modelsRoute)
writeScalerModel(self.allStandardScaler, 'all', 'moving', self.scalerRoute)
writeScalerModel(self.reducedStandardScaler, 'reduced', 'moving', self.scalerRoute)
writeScalerModel(self.baseStandardScaler, 'base', 'moving', self.scalerRoute)
print('Get predictions: ')
print(' - based on all data: call getPredictionWithAllModels(list) func., where list has 27 elements ')
print(' - based on reduced data: call getPredictionWithReducedModels(list) func., where list has 9 elements ')
print(' - based on all data: call getPredictionWithBaseModels(list) func., where list has 5 elements ')
def calulateBestParamsForRandomForest(self):
print('Warning: this function will take several hours: the results already available in the ./results/params folder')
print('Consider interrupting the kernel')
GridSearchForRandomForest(pandas.concat([self.allTrainX, self.allTestX]),
pandas.concat([self.allTrainy, self.allTesty]), 'moving', 'all')
GridSearchForRandomForest(pandas.concat([self.reducedTrainX, self.reducedTestX]),
pandas.concat([self.reducedTrainy, self.reducedTesty]), 'moving', 'reduced')
GridSearchForRandomForest(pandas.concat([self.baseTrainX, self.baseTestX]),
pandas.concat([self.baseTrainy, self.baseTesty]), 'moving', 'base')
def getPredictionWithAllModels(self, X):
if len(X) != 26:
print('Shape mismatch: X should contains 26 values like the allTrainX dataset')
return
#X.append(0.0)
scaled = self.allStandardScaler.transform(np.reshape(X, (1,-1)))
# TODO: scale X before calling predict func
ridgeResult = self.allRidgeModel.predict(scaled)
lassoResult = self.allLassoModel.predict(scaled)
forestResult = self.allRandomForestModel.predict(scaled)
print(' - ridge: '+ str(ridgeResult))
print(' - lasso: '+ str(lassoResult))
print(' - random forest: '+ str(forestResult))
# TODO: create graph
def getPredictionWithReducedModels(self, X):
if len(X) != 9:
print('Shape mismatch: X should contains 9 values like the reducedTrainX dataset')
return
# TODO: scale X before calling predict func
scaled = self.reducedStandardScaler.transform(np.reshape(X, (1,-1)))
ridgeResult = self.reducedRidgeModel.predict(scaled)
lassoResult = self.reducedLassoModel.predict(scaled)
forestResult = self.reducedRandomForestModel.predict(scaled)
print(' - ridge: ' + str(ridgeResult))
print(' - lasso: ' + str(lassoResult))
print(' - random forest: ' + str(forestResult))
# TODO: create graph
def getPredictionWithBaseModels(self, X):
if len(X) != 5:
print('Shape mismatch: X should contains 5 values like the baseTrainX dataset')
return
# TODO: scale X before calling predict func
scaled = self.baseStandardScaler.transform(np.reshape(X, (1,-1)))
ridgeResult = self.baseRidgeModel.predict(scaled)
lassoResult = self.baseLassoModel.predict(scaled)
forestResult = self.baseRandomForestModel.predict(scaled)
print(' - ridge: ' + str(ridgeResult))
print(' - lasso: ' + str(lassoResult))
print(' - random forest: ' + str(forestResult))
# TODO: create graph
def loadTrainedModelsAndScalers(self):
self.loadRegressionModels()
self.loadScalers()
print('Regression models and scalers are loaded')
print('Use the following functions to get predictions:')
print(' - getPredictionWithAllModels')
print(' - getPredictionWithReducedModels')
print(' - getPredictionWithBaseModels')
def loadRegressionModels(self):
# loading models based on all dataset
self.allRidgeModel = pickle.load(
open(self.modelsRoute + 'moving_time_' + 'all' + '_' + 'ridge.p', 'rb'))
self.allLassoModel = pickle.load(
open(self.modelsRoute + 'moving_time_' + 'all' + '_' + 'lasso.p', 'rb'))
self.allRandomForestModel = pickle.load(
open(self.modelsRoute + 'moving_time_' + 'all' + '_' + 'random_forest.p', 'rb'))
# loading models based on reduced dataset
self.reducedRidgeModel = pickle.load(
open(self.modelsRoute + 'moving_time_' + 'reduced' + '_' + 'ridge.p', 'rb'))
self.reducedLassoModel = pickle.load(
open(self.modelsRoute + 'moving_time_' + 'reduced' + '_' + 'lasso.p', 'rb'))
self.reducedRandomForestModel = pickle.load(
open(self.modelsRoute + 'moving_time_' + 'reduced' + '_' + 'random_forest.p', 'rb'))
# loading models based on base dataset
self.baseRidgeModel = pickle.load(
open(self.modelsRoute + 'moving_time_' + 'base' + '_' + 'ridge.p', 'rb'))
self.baseLassoModel = pickle.load(
open(self.modelsRoute + 'moving_time_' + 'base' + '_' + 'lasso.p', 'rb'))
self.baseRandomForestModel = pickle.load(
open(self.modelsRoute + 'moving_time_' + 'base' + '_' + 'random_forest.p', 'rb'))
def loadScalers(self):
# load fitted scaler models
self.allStandardScaler = pickle.load(open(self.scalerRoute + 'moving_time_all_scaler.p', 'rb'))
self.reducedStandardScaler = pickle.load(open(self.scalerRoute + 'moving_time_reduced_scaler.p', 'rb'))
self.baseStandardScaler = pickle.load(open(self.scalerRoute + 'moving_time_base_scaler.p', 'rb'))
def mps_to_kmph(self, m_per_s):
return m_per_s * 3.6
def kmph_to_mps(self, km_h):
return km_h / 3.6
## END OF MOVING TIME CLASS
## ELAPSED TIME
class ElapsedTimeRegression():
def __init__(self, cleanedRoute, modelsRoute, scalerRoute, paramsRoute, cleanedFileName): # define data routes and csv names!
self.cleanedRoute = cleanedRoute
self.modelsRoute = modelsRoute
self.scalerRoute = scalerRoute
self.paramsRoute = paramsRoute
self.dataset = pandas.read_csv(cleanedRoute + cleanedFileName, sep="|")
# all data
self.allTrainX = None
self.allTestX = None
self.allTrainy = None
self.allTesty = None
# reduced data
self.reducedTrainX = None
self.reducedTestX = None
self.reducedTrainy = None
self.reducedTesty = None
# age group null data
self.ageNullTrainX = None
self.ageNullTestX = None
self.ageNullTrainy = None
self.ageNullTesty = None
# age group one data
self.ageOneTrainX = None
self.ageOneTestX = None
self.ageOneTrainy = None
self.ageOneTesty = None
# age group two data
self.ageTwoTrainX = None
self.ageTwoTestX = None
self.ageTwoTrainy = None
self.ageTwoTesty = None
# distance small data
self.distanceSmallTrainX = None
self.distanceSmallTestX = None
self.distanceSmallTrainy = None
self.distanceSmallTesty = None
# distance big data
self.distanceBigTrainX = None
self.distanceBigTestX = None
self.distanceBigTrainy = None
self.distanceBigTesty = None
# user data
self.userTrainX = None
self.userTestX = None
self.userTrainy = None
self.userTesty = None
# regression model initialization
# ridge
self.allRidgeModel = None
self.reducedRidgeModel = None
self.ageNullRidgeModel = None
self.ageOneRidgeModel = None
self.ageTwoRidgeModel = None
self.distanceSmallRidgeModel = None
self.distanceBigRidgeModel = None
self.userRidgeModel = None
# lasso
self.allLassoModel = None
self.reducedLassoModel = None
self.ageNullLassoModel = None
self.ageOneLassoModel = None
self.ageTwoLassoModel = None
self.distanceSmallLassoModel = None
self.distanceBigLassoModel = None
self.userLassoModel = None
# random forest
self.allForestModel = None
self.reducedForestModel = None
self.ageNullForestModel = None
self.ageOneForestModel = None
self.ageTwoForestModel = None
self.distanceSmallForestModel = None
self.distanceBigForestModel = None
self.userForestModel = None
self.allStandardScaler = None
self.reducedStandardScaler = None
self.ageNullStandardScaler = None
self.ageOneStandardScaler = None
self.ageTwoStandardScaler = None
self.distanceSmallStandardScaler = None
self.distanceBigStandardScaler = None
self.userStandardScaler = None
self.CatCols8 = ['#003f5c', '#2f4b7c', '#665191', '#a05195', '#d45087', '#f95d6a', '#ff7c43', '#ffa600']
self.CatCols5 = ['#003f5c', '#3d61f4', '#bc5090', '#ff6361', '#ffa600']
self.CatCols3 = ['#003f5c', '#bc5090', '#ffa600']
print('call .dataset to see the cleaned dataset')
def prepareData(self):
# all data
X = self.dataset.copy()
Y = X['elapsed_time'].copy()
X.drop(columns=['elapsed_time', 'average_speed'], inplace=True)
names = X.columns
self.allStandardScaler = StandardScaler()
scaledX = self.allStandardScaler.fit_transform(X)
scaledX = pandas.DataFrame(scaledX, columns=names)
self.allTrainX, self.allTestX, self.allTrainy, self.allTesty = train_test_split(scaledX, Y, random_state=42)
# reduced data
X = self.dataset[['age_0.0', 'age_1.0', 'age_2.0', 'distance', 'elev_high', 'elev_low', 'hashed_id',
'total_elevation_gain', 'moving_time', 'trainer_onehot', 'workout_type_11.0', 'workout_type_10.0', 'workout_type_12.0']].copy()
Y = self.dataset['elapsed_time'].copy()
names = X.columns
self.reducedStandardScaler = StandardScaler()
scaledX = self.reducedStandardScaler.fit_transform(X)
scaledX = pandas.DataFrame(scaledX, columns=names)
self.reducedTrainX, self.reducedTestX, self.reducedTrainy, self.reducedTesty = train_test_split(scaledX, Y,
random_state=42)
# age group: null data
ageNull = self.dataset[self.dataset['age_0.0'] == 1].copy()
Y = ageNull['elapsed_time'].copy()
ageNull.drop(columns=['age_0.0', 'age_1.0', 'age_2.0', 'elapsed_time', 'average_speed'], inplace=True)
names = ageNull.columns
self.ageNullStandardScaler = StandardScaler()
scaledX = self.ageNullStandardScaler.fit_transform(ageNull)
scaledX = pandas.DataFrame(scaledX, columns=names)
self.ageNullTrainX, self.ageNullTestX, self.ageNullTrainy, self.ageNullTesty = train_test_split(scaledX, Y,
random_state=42)
# age group: one data
ageOne = self.dataset[self.dataset['age_1.0'] == 1].copy()
Y = ageOne['elapsed_time'].copy()
ageOne.drop(columns=['age_0.0', 'age_1.0', 'age_2.0', 'elapsed_time', 'average_speed'], inplace=True)
names = ageOne.columns
self.ageOneStandardScaler = StandardScaler()
scaledX = self.ageNullStandardScaler.fit_transform(ageOne)
scaledX = pandas.DataFrame(scaledX, columns=names)
self.ageOneTrainX, self.ageOneTestX, self.ageOneTrainy, self.ageOneTesty = train_test_split(scaledX, Y,
random_state=42)
# age group: two data
ageTwo = self.dataset[self.dataset['age_2.0'] == 1].copy()
Y = ageTwo['elapsed_time'].copy()
ageTwo.drop(columns=['age_0.0', 'age_1.0', 'age_2.0', 'elapsed_time', 'average_speed'], inplace=True)
names = ageTwo.columns
self.ageTwoStandardScaler = StandardScaler()
scaledX = self.ageTwoStandardScaler.fit_transform(ageTwo)
scaledX = pandas.DataFrame(scaledX, columns=names)
self.ageTwoTrainX, self.ageTwoTestX, self.ageTwoTrainy, self.ageTwoTesty = train_test_split(scaledX, Y,
random_state=42)
# distance small data
distanceSmall = self.dataset[self.dataset['distance'] < 50000].copy()
Y = distanceSmall['elapsed_time'].copy()
distanceSmall.drop(columns=['elapsed_time', 'average_speed'], inplace=True)
distanceSmall.reset_index(drop=True, inplace=True)
names = distanceSmall.columns
self.distanceSmallStandardScaler = StandardScaler()
scaledX = self.distanceSmallStandardScaler.fit_transform(distanceSmall)
scaledX = pandas.DataFrame(scaledX, columns=names)
self.distanceSmallTrainX, self.distanceSmallTestX, self.distanceSmallTrainy, self.distanceSmallTesty = train_test_split(scaledX, Y,
random_state=42)
# distance big data
distanceBig = self.dataset[self.dataset['distance'] >= 50000].copy()
Y = distanceBig['elapsed_time'].copy()
distanceBig.drop(columns=['elapsed_time', 'average_speed'], inplace=True)
distanceBig.reset_index(drop=True, inplace=True)
names = distanceBig.columns
self.distanceBigStandardScaler = StandardScaler()
scaledX = self.distanceBigStandardScaler.fit_transform(distanceBig)
scaledX = pandas.DataFrame(scaledX, columns=names)
self.distanceBigTrainX, self.distanceBigTestX, self.distanceBigTrainy, self.distanceBigTesty = train_test_split(
scaledX, Y,
random_state=42)
# user with the most activities
userData = self.dataset[self.dataset['hashed_id'] == self.dataset['hashed_id'].value_counts().idxmax()]
Y = userData['elapsed_time'].copy()
userData.drop(columns=['age_0.0', 'age_1.0', 'age_2.0', 'elapsed_time', 'average_speed'], inplace=True)
names = userData.columns
self.userStandardScaler = StandardScaler()
scaledX = self.userStandardScaler.fit_transform(userData)
scaledX = pandas.DataFrame(scaledX, columns=names)
self.userTrainX, self.userTestX, self.userTrainy, self.userTesty = train_test_split(scaledX, Y, random_state=42)
# TODO: user based dataset
# TODO: print info about the 3 dataset and the train-test pars
def trainModels(self, verbose=False, writeToFile=False):
# fitting models on all data
print('-- Fitting models on all data -- ')
if verbose:
print('Calculating best params for Ridge...')
ridgeParams = getBestParamsForRidge(self.allTrainX, self.allTestX, self.allTrainy, self.allTesty)
self.allRidgeModel = Ridge(alpha=ridgeParams['alpha'], solver=ridgeParams['solver'])
self.allRidgeModel.fit(self.allTrainX, self.allTrainy)
if verbose:
print('Done. Params: ')
print(ridgeParams)
print('')
if verbose:
print('Calculating best params for Lasso...')
lassoParams = getBestParamsForLasso(self.allTrainX, self.allTestX, self.allTrainy, self.allTesty)
self.allLassoModel = Lasso(alpha=lassoParams['alpha'])
self.allLassoModel.fit(self.allTrainX, self.allTrainy)
if verbose:
print('Done. Params: ')
print(lassoParams)
print('')
if verbose:
print('Loading best params for RandomForest...')
forestParams = pickle.load(open(self.paramsRoute + 'elapsed_time_all_random_forest_params.p', 'rb'))
self.allForestModel = RandomForestRegressor(n_estimators=forestParams['n_estimators'],
max_features=forestParams['max_features'],
min_samples_leaf=forestParams['min_samples_leaf'])
self.allForestModel.fit(self.allTrainX, self.allTrainy)
if verbose:
print('Done. Params: ')
print(forestParams)
print('')
print('Scores on allTesty data: ')
print(' - Ridge: ' + str(self.allRidgeModel.score(self.allTestX, self.allTesty)))
print(' - Lasso: ' + str(self.allLassoModel.score(self.allTestX, self.allTesty)))
print(' - Random Forest: ' + str(self.allForestModel.score(self.allTestX, self.allTesty)))
print('')
# fitting models on reduced data
print('-- Fitting models on reduced data --')
if verbose:
print('Calculating best params for Ridge...')
ridgeParams = getBestParamsForRidge(self.reducedTrainX, self.reducedTestX, self.reducedTrainy,
self.reducedTesty)
self.reducedRidgeModel = Ridge(alpha=ridgeParams['alpha'], solver=ridgeParams['solver'])
self.reducedRidgeModel.fit(self.reducedTrainX, self.reducedTrainy)
if verbose:
print('Done. Params: ')
print(ridgeParams)
print('')
if verbose:
print('Calculating best params for Lasso...')
lassoParams = getBestParamsForLasso(self.reducedTrainX, self.reducedTestX, self.reducedTrainy,
self.reducedTesty)
self.reducedLassoModel = Lasso(alpha=lassoParams['alpha'])
self.reducedLassoModel.fit(self.reducedTrainX, self.reducedTrainy)
if verbose:
print('Done. Params: ')
print(lassoParams)
print('')
if verbose:
print('Loading best params for RandomForest...')
forestParams = pickle.load(open(self.paramsRoute + 'elapsed_time_reduced_random_forest_params.p', 'rb'))
self.reducedForestModel = RandomForestRegressor(n_estimators=forestParams['n_estimators'],
max_features=forestParams['max_features'],
min_samples_leaf=forestParams['min_samples_leaf'])
self.reducedForestModel.fit(self.reducedTrainX, self.reducedTrainy)
if verbose:
print('Done. Params: ')
print(forestParams)
print('')
print('Scores on reducedTesty data: ')
print(' - Ridge: ' + str(self.reducedRidgeModel.score(self.reducedTestX, self.reducedTesty)))
print(' - Lasso: ' + str(self.reducedLassoModel.score(self.reducedTestX, self.reducedTesty)))
print(' - Random Forest: ' + str(self.reducedForestModel.score(self.reducedTestX, self.reducedTesty)))
print('')
# fitting models on age group NULL data
print('-- Fitting models on age group null data --')
if verbose:
print('Calculating best params for Ridge...')
ridgeParams = getBestParamsForRidge(self.ageNullTrainX, self.ageNullTestX, self.ageNullTrainy,
self.ageNullTesty)
self.ageNullRidgeModel = Ridge(alpha=ridgeParams['alpha'], solver=ridgeParams['solver'])
self.ageNullRidgeModel.fit(self.ageNullTrainX, self.ageNullTrainy)
if verbose:
print('Done. Params: ')
print(ridgeParams)
print('')
if verbose:
print('Calculating best params for Lasso...')
lassoParams = getBestParamsForLasso(self.ageNullTrainX, self.ageNullTestX, self.ageNullTrainy,
self.ageNullTesty)
self.ageNullLassoModel = Lasso(alpha=lassoParams['alpha'])
self.ageNullLassoModel.fit(self.ageNullTrainX, self.ageNullTrainy)
if verbose:
print('Done. Params: ')
print(lassoParams)
print('')
if verbose:
print('Loading best params for RandomForest...')
forestParams = pickle.load(open(self.paramsRoute + 'elapsed_time_age_null_random_forest_params.p', 'rb'))
self.ageNullForestModel = RandomForestRegressor(n_estimators=forestParams['n_estimators'],
max_features=forestParams['max_features'],
min_samples_leaf=forestParams['min_samples_leaf'])
self.ageNullForestModel.fit(self.ageNullTrainX, self.ageNullTrainy)
if verbose:
print('Done. Params: ')
print(forestParams)
print('')
print('Scores on age group null data: ')
print(' - Ridge: ' + str(self.ageNullRidgeModel.score(self.ageNullTestX, self.ageNullTesty)))
print(' - Lasso: ' + str(self.ageNullLassoModel.score(self.ageNullTestX, self.ageNullTesty)))
print(' - Random Forest: ' + str(self.ageNullForestModel.score(self.ageNullTestX, self.ageNullTesty)))
print('')
# fitting models on age group ONE data
print('-- Fitting models on age group one data --')
if verbose:
print('Calculating best params for Ridge...')
ridgeParams = getBestParamsForRidge(self.ageOneTrainX, self.ageOneTestX, self.ageOneTrainy,
self.ageOneTesty)
self.ageOneRidgeModel = Ridge(alpha=ridgeParams['alpha'], solver=ridgeParams['solver'])
self.ageOneRidgeModel.fit(self.ageOneTrainX, self.ageOneTrainy)
if verbose:
print('Done. Params: ')
print(ridgeParams)
print('')
if verbose:
print('Calculating best params for Lasso...')
lassoParams = getBestParamsForLasso(self.ageOneTrainX, self.ageOneTestX, self.ageOneTrainy,
self.ageOneTesty)
self.ageOneLassoModel = Lasso(alpha=lassoParams['alpha'])
self.ageOneLassoModel.fit(self.ageOneTrainX, self.ageOneTrainy)
if verbose:
print('Done. Params: ')
print(lassoParams)
print('')
if verbose:
print('Loading best params for RandomForest...')
forestParams = pickle.load(open(self.paramsRoute + 'elapsed_time_age_one_random_forest_params.p', 'rb'))
self.ageOneForestModel = RandomForestRegressor(n_estimators=forestParams['n_estimators'],
max_features=forestParams['max_features'],
min_samples_leaf=forestParams['min_samples_leaf'])
self.ageOneForestModel.fit(self.ageOneTrainX, self.ageOneTrainy)
if verbose:
print('Done. Params: ')
print(forestParams)
print('')
print('Scores on age group one data: ')
print(' - Ridge: ' + str(self.ageOneRidgeModel.score(self.ageOneTestX, self.ageOneTesty)))
print(' - Lasso: ' + str(self.ageOneLassoModel.score(self.ageOneTestX, self.ageOneTesty)))
print(' - Random Forest: ' + str(self.ageOneLassoModel.score(self.ageOneTestX, self.ageOneTesty)))
print('')
# fitting models on age group TWO data
print('-- Fitting models on age group two data --')
if verbose:
print('Calculating best params for Ridge...')
ridgeParams = getBestParamsForRidge(self.ageTwoTrainX, self.ageTwoTestX, self.ageTwoTrainy,
self.ageTwoTesty)
self.ageTwoRidgeModel = Ridge(alpha=ridgeParams['alpha'], solver=ridgeParams['solver'])
self.ageTwoRidgeModel.fit(self.ageTwoTrainX, self.ageTwoTrainy)
if verbose:
print('Done. Params: ')
print(ridgeParams)
print('')
if verbose:
print('Calculating best params for Lasso...')
lassoParams = getBestParamsForLasso(self.ageTwoTrainX, self.ageTwoTestX, self.ageTwoTrainy,
self.ageTwoTesty)
self.ageTwoLassoModel = Lasso(alpha=lassoParams['alpha'])
self.ageTwoLassoModel.fit(self.ageTwoTrainX, self.ageTwoTrainy)
if verbose:
print('Done. Params: ')
print(lassoParams)
print('')
if verbose:
print('Loading best params for RandomForest...')
forestParams = pickle.load(open(self.paramsRoute + 'elapsed_time_age_two_random_forest_params.p', 'rb'))
self.ageTwoForestModel = RandomForestRegressor(n_estimators=forestParams['n_estimators'],
max_features=forestParams['max_features'],
min_samples_leaf=forestParams['min_samples_leaf'])
self.ageTwoForestModel.fit(self.ageTwoTrainX, self.ageTwoTrainy)
if verbose:
print('Done. Params: ')
print(forestParams)
print('')
print('Scores on age group two data: ')
print(' - Ridge: ' + str(self.ageTwoRidgeModel.score(self.ageTwoTestX, self.ageTwoTesty)))
print(' - Lasso: ' + str(self.ageTwoLassoModel.score(self.ageTwoTestX, self.ageTwoTesty)))
print(' - Random Forest: ' + str(self.ageTwoForestModel.score(self.ageTwoTestX, self.ageTwoTesty)))
print('')
# fitting models on distance small data
print('-- Fitting models on distance small data --')
if verbose:
print('Calculating best params for Ridge...')
ridgeParams = getBestParamsForRidge(self.distanceSmallTrainX, self.distanceSmallTestX, self.distanceSmallTrainy,
self.distanceSmallTesty)
self.distanceSmallRidgeModel = Ridge(alpha=ridgeParams['alpha'], solver=ridgeParams['solver'])
self.distanceSmallRidgeModel.fit(self.distanceSmallTrainX, self.distanceSmallTrainy)
if verbose:
print('Done. Params: ')
print(ridgeParams)
print('')
if verbose:
print('Calculating best params for Lasso...')
lassoParams = getBestParamsForLasso(self.distanceSmallTrainX, self.distanceSmallTestX, self.distanceSmallTrainy,
self.distanceSmallTesty)
self.distanceSmallLassoModel = Lasso(alpha=lassoParams['alpha'])
self.distanceSmallLassoModel.fit(self.distanceSmallTrainX, self.distanceSmallTrainy)
if verbose:
print('Done. Params: ')
print(lassoParams)
print('')
if verbose:
print('Loading best params for RandomForest...')
forestParams = pickle.load(open(self.paramsRoute + 'elapsed_time_distance_small_random_forest_params.p', 'rb'))
self.distanceSmallForestModel = RandomForestRegressor(n_estimators=forestParams['n_estimators'],
max_features=forestParams['max_features'],
min_samples_leaf=forestParams['min_samples_leaf'])
self.distanceSmallForestModel.fit(self.distanceSmallTrainX, self.distanceSmallTrainy)
if verbose:
print('Done. Params: ')
print(forestParams)
print('')
print('Scores on distanceSmall data: ')
print(' - Ridge: ' + str(self.distanceSmallRidgeModel.score(self.distanceSmallTestX, self.distanceSmallTesty)))
print(' - Lasso: ' + str(self.distanceSmallLassoModel.score(self.distanceSmallTestX, self.distanceSmallTesty)))
print(' - Random Forest: ' + str(self.distanceSmallForestModel.score(self.distanceSmallTestX, self.distanceSmallTesty)))
print('')
# fitting models on distance big data
print('-- Fitting models on distance big data --')
if verbose:
print('Calculating best params for Ridge...')
ridgeParams = getBestParamsForRidge(self.distanceBigTrainX, self.distanceBigTestX, self.distanceBigTrainy,
self.distanceBigTesty)
self.distanceBigRidgeModel = Ridge(alpha=ridgeParams['alpha'], solver=ridgeParams['solver'])
self.distanceBigRidgeModel.fit(self.distanceBigTrainX, self.distanceBigTrainy)
if verbose:
print('Done. Params: ')
print(ridgeParams)
print('')
if verbose:
print('Calculating best params for Lasso...')
lassoParams = getBestParamsForLasso(self.distanceBigTrainX, self.distanceBigTestX, self.distanceBigTrainy,
self.distanceBigTesty)
self.distanceBigLassoModel = Lasso(alpha=lassoParams['alpha'])
self.distanceBigLassoModel.fit(self.distanceBigTrainX, self.distanceBigTrainy)
if verbose:
print('Done. Params: ')
print(lassoParams)
print('')
if verbose:
print('Loading best params for RandomForest...')
forestParams = pickle.load(open(self.paramsRoute + 'elapsed_time_distance_big_random_forest_params.p', 'rb'))
self.distanceBigForestModel = RandomForestRegressor(n_estimators=forestParams['n_estimators'],
max_features=forestParams['max_features'],
min_samples_leaf=forestParams['min_samples_leaf'])
self.distanceBigForestModel.fit(self.distanceBigTrainX, self.distanceBigTrainy)
if verbose:
print('Done. Params: ')
print(forestParams)
print('')
print('Scores on distanceBig data: ')
print(' - Ridge: ' + str(self.distanceBigRidgeModel.score(self.distanceBigTestX, self.distanceBigTesty)))
print(' - Lasso: ' + str(self.distanceBigLassoModel.score(self.distanceBigTestX, self.distanceBigTesty)))
print(' - Random Forest: ' + str(self.distanceBigForestModel.score(self.distanceBigTestX, self.distanceBigTesty)))
print('')
# fitting models on user data
print('-- Fitting models on user data (with the most activities -'+str(len(self.userTestX) + len(self.userTrainX))+') --')
if verbose:
print('Calculating best params for Ridge...')
ridgeParams = getBestParamsForRidge(self.userTrainX, self.userTestX, self.userTrainy, self.userTesty)
self.userRidgeModel = Ridge(alpha=ridgeParams['alpha'], solver=ridgeParams['solver'])
self.userRidgeModel.fit(self.userTrainX, self.userTrainy)
if verbose:
print('Done. Params: ')
print(ridgeParams)
print('')
if verbose:
print('Calculating best params for Lasso...')
lassoParams = getBestParamsForLasso(self.userTrainX, self.userTestX, self.userTrainy, self.userTesty)
self.userLassoModel = Lasso(alpha=lassoParams['alpha'])
self.userLassoModel.fit(self.userTrainX, self.userTrainy)
if verbose:
print('Done. Params: ')
print(lassoParams)
print('')
if verbose:
print('Loading best params for RandomForest...')
forestParams = pickle.load(open(self.paramsRoute + 'elapsed_time_user_random_forest_params.p', 'rb'))
self.userForestModel = RandomForestRegressor(n_estimators=forestParams['n_estimators'],
max_features=forestParams['max_features'],
min_samples_leaf=forestParams['min_samples_leaf'])
self.userForestModel.fit(self.userTrainX, self.userTrainy)
if verbose:
print('Done. Params: ')
print(forestParams)
print('')
print('Scores on user data: ')
print(' - Ridge: ' + str(self.userRidgeModel.score(self.userTestX, self.userTesty)))
print(' - Lasso: ' + str(self.userLassoModel.score(self.userTestX, self.userTesty)))
print(' - Random Forest: ' + str(self.userForestModel.score(self.userTestX, self.userTesty)))
print('')
# write models and scalers to pickle file
if writeToFile:
# write regression models
writeRegressionModels(self.allRidgeModel, self.allLassoModel, None, 'all',
'elapsed', self.modelsRoute, hasRandomForest=False)
writeRegressionModels(self.reducedRidgeModel, self.reducedLassoModel, None, 'reduced',
'elapsed', self.modelsRoute, hasRandomForest=False)
writeRegressionModels(self.ageNullRidgeModel, self.ageNullLassoModel, None, 'ageNull',
'elapsed', self.modelsRoute, hasRandomForest=False)
writeRegressionModels(self.ageOneRidgeModel, self.ageOneLassoModel, None, 'ageOne',
'elapsed', self.modelsRoute, hasRandomForest=False)
writeRegressionModels(self.ageTwoRidgeModel, self.ageTwoLassoModel, None, 'ageTwo',
'elapsed', self.modelsRoute, hasRandomForest=False)
writeRegressionModels(self.distanceSmallRidgeModel, self.distanceSmallLassoModel, None, 'distanceSmall',
'elapsed', self.modelsRoute, hasRandomForest=False)
writeRegressionModels(self.distanceBigRidgeModel, self.distanceBigLassoModel, None, 'distanceBig',
'elapsed', self.modelsRoute, hasRandomForest=False)
writeRegressionModels(self.userRidgeModel, self.userLassoModel, None, 'user',
'elapsed', self.modelsRoute, hasRandomForest=False)
# write scalers
writeScalerModel(self.allStandardScaler, 'all', 'elapsed', self.scalerRoute)
writeScalerModel(self.reducedStandardScaler, 'reduced', 'elapsed', self.scalerRoute)
writeScalerModel(self.ageNullStandardScaler, 'ageNull', 'elapsed', self.scalerRoute)
writeScalerModel(self.ageOneStandardScaler, 'ageOne', 'elapsed', self.scalerRoute)
writeScalerModel(self.ageTwoStandardScaler, 'ageTwo', 'elapsed', self.scalerRoute)
writeScalerModel(self.distanceSmallStandardScaler, 'distanceSmall', 'elapsed', self.scalerRoute)
writeScalerModel(self.distanceBigStandardScaler, 'distanceBig', 'elapsed', self.scalerRoute)
writeScalerModel(self.userStandardScaler, 'user', 'elapsed', self.scalerRoute)
print('Get predictions: ')
print(' - based on all data: call getPredictionWithAllModels(list) func., where list has 27 elements ')
print(' - based on reduced data: call getPredictionWithReducedModels(list) func., where list has 9 elements ')
# print(' - based on base data: call getPredictionWithBaseModels(list) func., where list has 5 elements ')
def getPredictionWithAllModels(self, X):
if len(X) != 27:
print('Shape mismatch: X should contains 27 values like the allTrainX dataset')
return
scaled = self.allStandardScaler.transform(np.reshape(X, (1,-1)))
ridgeResult = self.allRidgeModel.predict(scaled)
lassoResult = self.allLassoModel.predict(scaled)
#forestResult = self.baseRandomForestModel.predict(scaled)
print(' - ridge: ' + str(ridgeResult))
print(' - lasso: ' + str(lassoResult))
#print(' - random forest: ' + str(forestResult))
# TODO: create graph
def getPredictionWithReducedModels(self, X):
if len(X) != 10:
print('Shape mismatch: X should contains 10 values like the reducedTrainX dataset')
return
scaled = self.reducedStandardScaler.transform(np.reshape(X, (1,-1)))
ridgeResult = self.reducedRidgeModel.predict(scaled)
lassoResult = self.reducedLassoModel.predict(scaled)
# forestResult = self.baseRandomForestModel.predict(scaled)
print(' - ridge: ' + str(ridgeResult))
print(' - lasso: ' + str(lassoResult))
# print(' - random forest: ' + str(forestResult))
# TODO: create graph
def getPredictionWithAgeNullModels(self, X):
if len(X) != 24:
print('Shape mismatch: X should contains 24 values like the ageNullTrainX dataset')
return
scaled = self.ageNullStandardScaler.transform(np.reshape(X, (1,-1)))
ridgeResult = self.ageNullRidgeModel.predict(scaled)
lassoResult = self.ageNullLassoModel.predict(scaled)
# forestResult = self.baseRandomForestModel.predict(scaled)
print(' - ridge: ' + str(ridgeResult))
print(' - lasso: ' + str(lassoResult))
# print(' - random forest: ' + str(forestResult))
# TODO: create graph
def getPredictionWithAgeOneModels(self, X):
if len(X) != 24:
print('Shape mismatch: X should contains 24 values like the ageOneTrainX dataset')
return
# TODO: scale X before calling predict func
scaled = self.ageOneStandardScaler.transform(np.reshape(X, (1,-1)))
ridgeResult = self.ageOneRidgeModel.predict(scaled)
lassoResult = self.ageOneLassoModel.predict(scaled)
# forestResult = self.ageOneRandomForestModel.predict(scaled)
print(' - ridge: ' + str(ridgeResult))
print(' - lasso: ' + str(lassoResult))
# print(' - random forest: ' + str(forestResult))
# TODO: create graph
def getPredictionWithAgeTwoModels(self, X):
if len(X) != 24:
print('Shape mismatch: X should contains 24 values like the ageTwoTrainX dataset')
return
# TODO: scale X before calling predict func
scaled = self.ageTwoStandardScaler.transform(np.reshape(X, (1,-1)))
ridgeResult = self.ageTwoRidgeModel.predict(scaled)
lassoResult = self.ageTwoLassoModel.predict(scaled)
# forestResult = self.baseRandomForestModel.predict(scaled)
print(' - ridge: ' + str(ridgeResult))
print(' - lasso: ' + str(lassoResult))
# print(' - random forest: ' + str(forestResult))
# TODO: create graph
def getPredictionWithDistanceSmallModels(self, X):
if len(X) != 27:
print('Shape mismatch: X should contains 27 values like the distanceSmallTrainX dataset')
return
# TODO: scale X before calling predict func
scaled = self.distanceSmallStandardScaler.transform(np.reshape(X, (1,-1)))
ridgeResult = self.distanceSmallRidgeModel.predict(scaled)
lassoResult = self.distanceSmallLassoModel.predict(scaled)
# forestResult = self.baseRandomForestModel.predict(scaled)
print(' - ridge: ' + str(ridgeResult))
print(' - lasso: ' + str(lassoResult))
# print(' - random forest: ' + str(forestResult))
# TODO: create graph
def getPredictionWithDistanceBigModels(self, X):
if len(X) != 27:
print('Shape mismatch: X should contains 27 values like the distanceBigTrainX dataset')
return
scaled = self.distanceBigStandardScaler.transform(np.reshape(X, (1,-1)))
ridgeResult = self.distanceBigRidgeModel.predict(scaled)
lassoResult = self.distanceBigLassoModel.predict(scaled)
# forestResult = self.baseRandomForestModel.predict(scaled)
print(' - ridge: ' + str(ridgeResult))
print(' - lasso: ' + str(lassoResult))
# print(' - random forest: ' + str(forestResult))
# TODO: create graph
def getPredictionWithUserModels(self, X):
if len(X) != 24:
print('Shape mismatch: X should contains 24 values like the userTrainX dataset')
return
scaled = self.userStandardScaler.transform(np.reshape(X, (1,-1)))
ridgeResult = self.userRidgeModel.predict(scaled)
lassoResult = self.userLassoModel.predict(scaled)
# forestResult = self.baseRandomForestModel.predict(scaled)
print(' - ridge: ' + str(ridgeResult))
print(' - lasso: ' + str(lassoResult))
# print(' - random forest: ' + str(forestResult))
# TODO: create graph
def calulateBestParamsForRandomForest(self):
print('Warning: this function will take several hours: the results already available in the ./data/results/params folder')
print('Consider interrupting the kernel')
GridSearchForRandomForest(pandas.concat([self.allTrainX, self.allTestX]),
pandas.concat([self.allTrainy, self.allTesty]), 'elapsed', 'all')
GridSearchForRandomForest(pandas.concat([self.reducedTrainX, self.reducedTestX]),
pandas.concat([self.reducedTrainy, self.reducedTesty]), 'elapsed', 'reduced')
GridSearchForRandomForest(pandas.concat([self.ageNullTrainX, self.ageNullTestX]),
pandas.concat([self.ageNullTrainy, self.ageNullTesty]), 'elapsed', 'age_null')
GridSearchForRandomForest(pandas.concat([self.ageOneTrainX, self.ageOneTestX]),
pandas.concat([self.ageOneTrainy, self.ageOneTesty]), 'elapsed', 'age_one')
GridSearchForRandomForest(
|
pandas.concat([self.ageTwoTrainX, self.ageTwoTestX])
|
pandas.concat
|
import pprint
import requests
import pickle
import pandas as pd
import spacy
from sklearn.neighbors import NearestNeighbors
from tqdm import tqdm
from sklearn.cluster import DBSCAN
from sklearn.datasets.samples_generator import make_blobs
import numpy as np
from matplotlib import pyplot as plt
import seaborn as sns
sns.set()
def show_blobs():
X, y = make_blobs(n_samples=300, centers=4, cluster_std=0.60, random_state=0)
plt.scatter(X[:, 0], X[:, 1])
def load_web():
secret = 'xxx'
url = 'https://newsapi.org/v2/everything?'
parameters = {
'q': 'big data', # query phrase
'pageSize': 20, # maximum is 100
'apiKey': secret # your own API key
}
# Make the request
response = requests.get(url, params=parameters)
# Convert the response to JSON format and pretty print it
data = response.json()
with open('output.pickle', 'wb') as w:
pickle.dump(data, w)
def load_file():
with open('output.pickle', 'rb') as r:
articles = pickle.load(r)
return articles
def make_df():
titles = []
dates = []
descriptions = []
for line in load_file()['articles']:
titles.append(line['title'])
dates.append(line['publishedAt'])
descriptions.append(line['description'])
# print({'titles':titles,'desc':descriptions, 'dates':dates})
df =
|
pd.DataFrame(data={'titles': titles, 'desc': descriptions, 'dates': dates})
|
pandas.DataFrame
|
import numpy as np
import pandas as pd
from pytest import test_comparer_df
from popmon.analysis.apply_func import ApplyFunc, apply_func, apply_func_array
from popmon.analysis.functions import pull
from popmon.analysis.profiling.pull_calculator import (
ExpandingPullCalculator,
ReferencePullCalculator,
RefMedianMadPullCalculator,
RollingPullCalculator,
)
from popmon.base import Pipeline
def get_test_data():
df =
|
pd.DataFrame()
|
pandas.DataFrame
|
#!/usr/bin/env python3
import pandas as pd
def main():
excel_file = 'movies.xls'
movies0 = pd.read_excel(excel_file, sheet_name=0, index_col=0)
movies1 = pd.read_excel(excel_file, sheet_name=1, index_col=0)
movies2 =
|
pd.read_excel(excel_file, sheet_name=2, index_col=0)
|
pandas.read_excel
|
# https://github.com/chrisconlan/algorithmic-trading-with-python/blob/master/src/pypm/metrics.py
import pandas as pd
import numpy as np
import numpy_financial as npf
from sklearn.linear_model import LinearRegression
from scipy.stats import norm
from scipy.optimize import root_scalar
import warnings
import datetime
import matplotlib.pyplot as plt
# https://stackoverflow.com/questions/16004076/python-importing-a-module-that-imports-a-module
from . import dates as dt
def compute_irr(T=10, S0=1000, monthly_s=100, F=20000, verbose=False):
"""
compute required IRR to match investment expectation
:param T: int or float, in 1/12 of month (es 10.5 for 10y6m). Time period in year
:param S0: initial invested amount
:param monthly_s: monthly investment
:param F: final amount
:return: required IRR to meet investment expectation
"""
# number of periods
M = 12 # frequency, monthly
n_periods = round(T * M) - 1
IRR = npf.irr([-(S0 + monthly_s), *[-monthly_s for _ in range(n_periods - 1)], F])
IRR_yearly = (1 + IRR) ** M - 1
if verbose:
print(f"Total investment: {S0 + n_periods * monthly_s:,.2f}, "
f"required annual rate of return to get {F:,.2f}: {IRR_yearly:.2%}")
return IRR_yearly
def rebase_ts(prices, V0=100):
"""
rebases prices time series to V0
:param prices: pd.Series or pd.DataFrame
:param V0: rebase to level V0
"""
if not isinstance(prices, (pd.Series, pd.DataFrame)):
raise TypeError("`prices` must be either pd.Series or pd.DataFrame")
if isinstance(prices, pd.Series):
if np.isnan(prices.iloc[0]):
# se la prima osservazione è NaN
ts = prices.dropna()
else:
ts = prices
ts_rebased = ts / ts.iloc[0] * V0
else:
# case 2: isinstance(prices, pd.DataFrame)
if any(prices.iloc[0].isna()):
# se vi è almeno un NaN nella prima osservazione delle serie storiche
ts_rebased = list()
for col in prices.columns:
ts = prices[col].dropna()
ts_rebased.append(ts / ts.iloc[0] * V0)
ts_rebased = pd.concat(ts_rebased, axis=1)
else:
ts_rebased = prices / prices.iloc[0] * V0
# nel caso in cui ci siano NaN, la serie storica in output potrebbe avere un indice diverso rispetto a prices
ts_rebased = ts_rebased.reindex(prices.index)
return ts_rebased
def yield_to_ts(yields, V0=100):
"""
Computes timeseries starting from yield values. Uses ACT/360.
:param yields:
:param V0:
:return:
"""
elapsed_days = yields.index.to_series().diff().dt.days.fillna(0)
returns = (1 + yields / 100).pow(elapsed_days / 360, axis=0) - 1
ts = compute_ts(returns, V0=V0)
return ts
def compute_returns(prices, method="simple"):
"""
compute simple or log returns given a pd.Series or a pd.Dataframe
compute returns of `price_series`.
:param prices: pd.Series or pd.DataFrame
:param method: "simple" or "log"
"""
if method == "simple":
ret_fun = lambda x: x / x.shift(1, fill_value=x[0]) - 1
elif method == "log":
ret_fun = lambda x: np.log(x / x.shift(1, fill_value=x[0]))
else:
raise ValueError("`method` must be either 'simple' or 'log'")
if isinstance(prices, pd.Series):
returns = ret_fun(prices)
elif isinstance(prices, pd.DataFrame):
returns = prices.apply(ret_fun, axis=0)
else:
raise TypeError("prices must be either pd.Series or pd.DataFrame")
return returns
def compute_ts(returns, method="simple", V0=100):
"""
compute time series given a pd.Series or a pd.Dataframe containing returns (simple or log)
compute prices time series of `returns`.
NB: first row of `returns` is assumed to be 0.
:param returns: pd.Series or pd.DataFrame
:param method: "simple" or "log"
:param V0: int, starting value
:return: prices time series
"""
if method == "simple":
ts_fun = lambda x: V0 * np.cumprod(1 + x)
elif method == "log":
ts_fun = lambda x: V0 * np.exp(np.cumsum(returns))
else:
raise ValueError("`method` must be either 'simple' or 'log'")
if isinstance(returns, pd.Series):
prices = ts_fun(returns)
elif isinstance(returns, pd.DataFrame):
prices = returns.apply(ts_fun, axis=0)
else:
raise TypeError("`prices` must be either pd.Series or pd.DataFrame")
return prices
def change_freq_ts(prices, freq="monthly"):
"""
subsets of prices timeseries with desired frequency
:param prices: pd.Series or pd.DataFrame
:param freq: str: weekly, monthly, yearly (or: w, m, y)
:return: subset of prices with end of week/month/year obs
"""
if not isinstance(prices, (pd.Series, pd.DataFrame)):
raise TypeError("`prices` must be either pd.Series or pd.DataFrame")
if not isinstance(prices.index, pd.core.indexes.datetimes.DatetimeIndex):
raise TypeError("`prices.index` must contains dates")
if isinstance(freq, str):
freq = freq.lower()
if freq not in ["weekly", "w", "monthly", "m", "yearly", "y"]:
raise ValueError("`freq` can be: 'weekly', 'monthly', 'yearly' (or 'w', 'm', 'y')")
else:
raise TypeError("`freq` must be str")
if freq in ["weekly", "w"]:
idx = dt.get_end_of_weeks(dates=prices.index)
elif freq in ["monthly", "m"]:
idx = dt.get_end_of_months(dates=prices.index)
elif freq in ["yearly", "y"]:
idx = dt.get_end_of_years(dates=prices.index)
# subset prices
prices = prices.loc[idx]
return prices
def bootstrap_ts(ret, samples, index_dates=None):
"""
:param ret: pd.Series containing returns
:param samples: int, tuple or np.array. if 2d np.array, then each col contains different bootstrap.
if 1d np.array, then single bootstrap. if int, then perform bootstrap of lenght samples.
if tuple of lenght 2, then use it as the size of np.random.choice
:param index_dates: None or list/pd.Index of dates of length the number of extractions in each bootstrap
:return: pd.Series or pd.DataFrame with bootstrapped returns. pd.DataFrame if samples is 2d np.array
"""
assert isinstance(ret, pd.Series)
if isinstance(samples, np.ndarray):
if samples.ndim == 1:
# 1d array
sim_ret = ret.iloc[samples].reset_index(drop=True)
else:
# 2d array
sim_ret = []
for i in range(samples.shape[1]):
sim_ret_i = ret.iloc[samples[:, i]].reset_index(drop=True)
sim_ret.append(sim_ret_i)
sim_ret = pd.concat(sim_ret, axis=1)
elif isinstance(samples, (int, float)):
samples = np.random.choice(range(len(ret)), size=samples)
return bootstrap_ts(ret, samples=samples, index_dates=index_dates)
elif isinstance(samples, tuple):
# nel caso in cui venga passata una tupla più lunga di due, prendi solo i primi due elementi
samples = np.random.choice(range(len(ret)), size=samples[:2])
return bootstrap_ts(ret, samples=samples, index_dates=index_dates)
else:
raise Exception(f"samples must be int, tuple or np.array")
# add zeros as first obs to compute prices time series easily later
if isinstance(sim_ret, pd.Series):
sim_ret = pd.concat([pd.Series(0), sim_ret])
elif isinstance(sim_ret, pd.DataFrame):
sim_ret = pd.concat([pd.DataFrame(0, index=[0], columns=sim_ret.columns), sim_ret], axis=0)
else:
print("something went wrong")
if index_dates is not None:
if isinstance(index_dates, (list, pd.DatetimeIndex)):
if len(index_dates) == len(sim_ret):
sim_ret.index = index_dates
else:
print(f"`index_dates` must be of lenght {len(sim_ret)}")
print(f"Dates not added as index")
else:
print(f"`index_dates` must be `list` or `pd.DatetimeIndex`, got {type(index_dates)} instead")
print(f"Dates not added as index")
return sim_ret
def bootstrap_plot(ret, T=30, I=500, init_investm=1000, monthly_investm=None, oneoff_investm=None, seed=None):
"""
:param ret: pd.Series with returns
:param T: years to simulate
:param I: number of simulations
:param init_investm: int, initial investment
:param monthly_investm: int, monthly investment
:param oneoff_investm: int, one-off investment
:return: plot
"""
assert isinstance(ret, pd.Series), "ret must be pd.Series"
assert isinstance(init_investm, (int, float)), "init_investm must be int"
if seed is not None:
np.random.seed(seed)
# number of periods in each year
M = 12
# dates to simulate
sim_dates = pd.bdate_range(ret.index.max(), "2100-12-31", freq="M")
# select only the needed simulation dates
sim_dates = sim_dates[:(T * M)]
# sample length
K = len(sim_dates) - 1
# bootstrap
ret_bs = bootstrap_ts(ret, samples=(K, I), index_dates=sim_dates)
# compute time-series from bootstrapped returns
ts_bs = compute_ts(ret_bs, V0=init_investm)
# compute mean
mean_ts = ts_bs.mean(axis=1)
# compute std
std_ts = ts_bs.std(axis=1)
cagr = compute_cagr(mean_ts)
all_period_ret = compute_allperiod_returns(mean_ts)
tot_investm = init_investm
final_value = mean_ts.iloc[-1]
if oneoff_investm is not None:
# oneoff_ts_bs = compute_ts(ret_bs, V0=oneoff_investm)
# mean_oneoff = oneoff_ts_bs.mean(axis=1)
# mean_oneoff = rebase_ts(mean_ts, V0=oneoff_investm)
oneoff_ts = rebase_ts(ts_bs, V0=oneoff_investm)
oneoff_ts = ts_bs.add(oneoff_ts, fill_value=0)
mean_oneoff = oneoff_ts.mean(axis=1)
std_oneoff = oneoff_ts.std(axis=1)
cagr = compute_cagr(mean_oneoff)
all_period_ret = compute_allperiod_returns(mean_oneoff)
tot_investm += oneoff_investm
final_value = mean_oneoff.iloc[-1]
if monthly_investm is not None:
for dd in sim_dates[:-1]: # non considerare l'ultima data
# m_ts_bs = compute_ts(ret_bs.loc[ret_bs.index >= dd], V0=monthly_investm)
# mean_tmp = rebase_ts(mean_ts.loc[mean_ts.index >= dd], V0=monthly_investm)
mean_tmp = rebase_ts(ts_bs.loc[mean_ts.index >= dd], V0=monthly_investm)
try:
monthly_ts = monthly_ts.add(mean_tmp, fill_value=0)
except:
monthly_ts = mean_tmp.copy()
# mean_monthly = monthly_ts.mean(axis=1)
monthly_ts = ts_bs.add(monthly_ts, fill_value=0)
std_monthly = monthly_ts.std(axis=1)
mean_monthly = monthly_ts.mean(axis=1)
# per il calcolo del CAGR bisogna tenere in considerazione tutti gli investimenti
final_value = mean_monthly.iloc[-1]
cagr = compute_irr(T=T, S0=tot_investm, monthly_s=monthly_investm, F=final_value)
# cagr = compute_cagr(mean_monthly)
all_period_ret = (1 + cagr) ** T - 1
tot_investm += monthly_investm * (len(sim_dates) - 1)
# plot
fig, ax = plt.subplots()
ax.plot(mean_ts.index, mean_ts, label=f"Investment: {init_investm:,.0f}")
if oneoff_investm is not None:
ax.plot(mean_oneoff.index, mean_oneoff, "r", label=f"Adding one-off investment: {oneoff_investm:,.0f}")
ax.fill_between(mean_oneoff.index, mean_oneoff - .2 * std_oneoff, mean_oneoff + .2 * std_oneoff, alpha=.5)
ax.fill_between(mean_oneoff.index, mean_oneoff - .5 * std_oneoff, mean_oneoff + .5 * std_oneoff, alpha=.3)
ax.fill_between(mean_oneoff.index, mean_oneoff - std_oneoff, mean_oneoff + std_oneoff, alpha=.1)
elif monthly_investm is not None:
ax.plot(mean_monthly.index, mean_monthly, "r", label=f"With monthly investment: {monthly_investm:,.0f}")
ax.fill_between(mean_monthly.index, mean_monthly - .2 * std_monthly, mean_monthly + .2 * std_monthly, alpha=.5)
ax.fill_between(mean_monthly.index, mean_monthly - .5 * std_monthly, mean_monthly + .5 * std_monthly, alpha=.3)
ax.fill_between(mean_monthly.index, mean_monthly - std_monthly, mean_monthly + std_monthly, alpha=.1)
else:
ax.fill_between(mean_ts.index, mean_ts - 0.2 * std_ts, mean_ts + 0.2 * std_ts, alpha=0.5)
ax.fill_between(mean_ts.index, mean_ts - 0.5 * std_ts, mean_ts + 0.5 * std_ts, alpha=0.3)
ax.fill_between(mean_ts.index, mean_ts - std_ts, mean_ts + std_ts, alpha=0.1)
plt.title(f"{ret.name} {T} years Projection.\n"
f"CAGR: {cagr:.2%}, overall return: {all_period_ret:.2%}.\n"
f"Total investment: {tot_investm:,.0f}, Final value: {final_value:,.0f}")
ax.legend()
return fig
def compute_excess_return(ts, bmk_ts):
"""
compute excess return. ts and bmk_ts should have the same dates, otherwise inner join
:param ts: pd.Series or pd.DataFrame containing returns (portfolio or generic stock)
:param bmk_ts: pd.Series containg benchmark returns
:return pd.Series with excess return
"""
if not isinstance(ts, (pd.Series, pd.DataFrame)):
print("`ts` must be pd.Series or pd.DataFrame")
return
if not isinstance(bmk_ts, pd.Series):
print("`bmk_ts` must be pd.Series")
return
if isinstance(ts, pd.Series):
excess_return = ts.subtract(bmk_ts.loc[ts.index])
elif isinstance(ts, pd.DataFrame):
excess_return = ts.apply(lambda x: x.subtract(bmk_ts.loc[ts.index]), axis=0)
excess_return = excess_return.dropna()
return excess_return
def compute_tracking_error_vol(ts, bmk_ts):
"""
compute tracking error volatility wrt a benchmark timeseries
input MUST be returns time-series
:param ts: pd.Series or pd.DataFrame (returns)
:param bmk_ts: pd.Series or pd.DataFrame with benchmark(s) returns
"""
if not isinstance(ts, (pd.Series, pd.DataFrame)):
print("`ts` must be pd.Series or pd.DataFrame")
return
if not isinstance(bmk_ts, (pd.Series, pd.DataFrame)):
print("`bmk_ts` must be pd.Series or pd.DataFrame")
return
if isinstance(bmk_ts, pd.Series):
excess_return = compute_excess_return(ts=ts, bmk_ts=bmk_ts)
tev = compute_annualized_volatility(excess_return)
if isinstance(ts, pd.DataFrame):
tev.name = "tev"
elif isinstance(bmk_ts, pd.DataFrame):
tev = list()
for i in range(len(bmk_ts.columns)):
excess_return = compute_excess_return(ts=ts, bmk_ts=bmk_ts[bmk_ts.columns[i]])
pair_tev = compute_annualized_volatility(excess_return)
pair_tev.name = bmk_ts.columns[i]
tev.append(pair_tev)
tev = pd.concat(tev, axis=1)
return tev
def get_years_past(series):
"""
Calculate the years past according to the index of the series for use with
functions that require annualization
"""
start_date = series.index[0]
end_date = series.index[-1]
return ((end_date - start_date).days + 1) / 365.25
def compute_cagr(prices):
"""
Calculate compounded annual growth rate
:param prices: pd.Series or pd.DataFrame containing prices
"""
assert isinstance(prices, (pd.Series, pd.DataFrame))
start_price = prices.iloc[0]
end_price = prices.iloc[-1]
value_factor = end_price / start_price
year_past = get_years_past(prices)
return (value_factor ** (1 / year_past)) - 1
def compute_active_return(prices, bmk_prices):
"""
active return = (cagr(prices) - cagr(bmk_prices))
:param prices:
:param bmk_prices:
:return:
"""
# mantieni solo le date in comune
common_dates = set(prices.index).intersection(set(bmk_prices.index))
# cagr
ptf_cagr = compute_cagr(prices[prices.index.isin(common_dates)])
bmk_cagr = compute_cagr(bmk_prices[bmk_prices.index.isin(common_dates)])
if isinstance(bmk_prices, pd.DataFrame):
output = pd.DataFrame(np.zeros((len(ptf_cagr), len(bmk_prices.columns))),
index=ptf_cagr.index, columns=bmk_prices.columns)
for col in bmk_prices.columns:
output[col] = ptf_cagr - bmk_cagr[col]
else:
output = ptf_cagr - bmk_cagr
return output
def compute_allperiod_returns(ts, method="simple"):
"""
Compute NON-annualized return between first and last available obs
:param ts: pd.Series or pd.DataFrame containing prices timeseries
:param method: str, "simple" or "log"
:return:
"""
assert isinstance(ts, (pd.Series, pd.DataFrame))
if method == "simple":
return ts.iloc[-1] / ts.iloc[0] - 1
elif method == "log":
return np.log(ts.iloc[-1] / ts.iloc[0])
else:
raise ValueError("method should be either simple or log")
def compute_annualized_volatility(returns):
"""
Calculates annualized volatility for a date-indexed return series.
Works for any interval of date-indexed prices and returns.
"""
years_past = get_years_past(returns)
entries_per_year = returns.shape[0] / years_past
return returns.std() * np.sqrt(entries_per_year)
def compute_rolling_volatility(returns, window=252):
"""
Wrapper for compute_annualized_volatility. it computes rolling annualized volatility
:param returns:
:param window:
:return:
"""
roll_vol = returns.rolling(window=window).apply(lambda x: compute_annualized_volatility(x))
return roll_vol
def compute_sharpe_ratio(returns, benchmark_rate=0):
"""
Calculates the sharpe ratio given a price series. Defaults to benchmark_rate
of zero.
"""
prices = compute_ts(returns)
cagr = compute_cagr(prices)
# returns = compute_returns(prices)
volatility = compute_annualized_volatility(returns)
return (cagr - benchmark_rate) / volatility
def compute_information_ratio(returns, bmk_returns):
"""
Compute the Information ratio wrt a benchmark
IR = (ptf_returns - bmk_returns) / tracking_error_vol
:param returns: portfolio returns. pd.Series or pd.DataFrame
:param bmk_returns: benchmark returns. pd.Series or pd.DataFrame
:return:
"""
prices = compute_ts(returns)
bmk_prices = compute_ts(bmk_returns)
# compute active return
active_ret = compute_active_return(prices, bmk_prices)
# compute TEV
tev = compute_tracking_error_vol(returns, bmk_returns)
return active_ret / tev
def compute_rolling_sharpe_ratio(prices, window=20, method="simple"):
"""
Compute an *approximation* of the sharpe ratio on a rolling basis.
Intended for use as a preference value.
"""
rolling_return_series = compute_returns(prices, method=method).rolling(window)
return rolling_return_series.mean() / rolling_return_series.std()
def compute_beta(ret, bmk_ret, use_linear_reg=False):
"""
Computes single-regression beta. ret = alpha + beta * bmk_ret
If ret is pd.Series or pd.DataFrame with 1 column:
If bmk_ret is pd.Series or pd.DataFrame with 1 column:
output: scalar
Elif bmk_ret is pd.DataFrame with >1 column:
output: pd.DataFrame with 1 row (ret.name) and len(bmk_ret.columns) cols
Elif ret is pd.DataFrame with >1 columns:
If bmk_ret is pd.Series or pd.DataFrame with 1 column:
output: pd.DataFrame with 1 col (bmk_ret.name) and len(ret.columns) rows
Elif bmk_ret is pd.DataFrame with >1 column:
output: pd.DataFrame with len(ret.columns) rows and len(bmk_ret.columns) cols
https://corporatefinanceinstitute.com/resources/knowledge/finance/beta-coefficient/
:param ret: stock/portfolio returns. works with multiple timeseries as well
:param bmk_ret: benchmark returns. works with multiple benckmarks
:param use_linear_reg: boolean -> compute beta using linear regression?
:return:
"""
if not isinstance(ret, (pd.Series, pd.DataFrame)):
raise TypeError("`ret` must be pd.Series or pd.DataFrame containing returns")
if not isinstance(bmk_ret, (pd.Series, pd.DataFrame)):
raise TypeError("`bmk_ret` must be pd.Series or pd.DataFrame containing benchmark returns")
if isinstance(ret, pd.Series):
ret = ret.to_frame(ret.name)
if isinstance(bmk_ret, pd.Series):
bmk_series = True
bmk_ret = bmk_ret.to_frame(bmk_ret.name)
else:
bmk_series = False
# bisogna fare in modo che le date (.index) coincidano
if len(set(ret.index).symmetric_difference(bmk_ret.index)):
# merge per allineare le date
tmp = pd.concat([ret, bmk_ret], axis=1)
# inserisci zero al posto degli NA
# tmp = tmp.fillna(0)
# rimuovi gli NA
tmp = tmp.dropna()
ret = tmp[ret.columns]
bmk_ret = tmp[bmk_ret.columns]
# inizializza un pd.DataFrame dove verranno salvati i beta
beta = np.zeros((len(ret.columns), len(bmk_ret.columns)))
beta = pd.DataFrame(beta, index=ret.columns, columns=bmk_ret.columns)
if use_linear_reg:
# use linear regression to compute beta
m = LinearRegression(fit_intercept=True)
for icol in range(len(ret.columns)):
for jcol in range(len(bmk_ret.columns)):
# reg: ret = alpha + beta * bmk_ret
# bmk_ret è il ritorno del mercato nel CAPM
m.fit(bmk_ret.iloc[:, [jcol]], ret.iloc[:, [icol]])
beta.iloc[icol, jcol] = m.coef_[0][0]
else:
# use variance - covariance
# variance and covariance
for jcol in bmk_ret.columns:
# serve lavorare su un unico pd.DataFrame
tmp = pd.concat([ret, bmk_ret[[jcol]]], axis=1)
# inserisci zero al posto degli NA
# tmp = tmp.fillna(0)
# rimuovi gli NA
tmp = tmp.dropna()
# calcola beta
m = np.cov(tmp, rowvar=False)
variance = m[(m.shape[0] - 1), (m.shape[1] - 1)]
# non considerare la covarianza con il benchmark
covariance = m[:-1, (m.shape[1] - 1)]
# salva beta
beta[jcol] = covariance / variance
if bmk_series:
# output pd.Series, not pd.DataFrame
beta = beta[bmk_ret.columns[0]]
if sum(beta.shape) == 1:
# ritorna scalare
beta = beta[0]
elif sum(beta.shape) == 2 and not bmk_series:
# ritorna scalare
beta = beta.iloc[0, 0]
return beta
def compute_multiple_beta(y, xs):
"""
Computes multiple linear regression y = a + b_1 * xs_1 + b_2 * xs_2 + .. + b_n * xs_n
:param y: stock/portfolio returns. must be pd.Series or pd.DataFrame with one column
:param xs: benchmark returns. must be pd.Series or pd.DataFrame
:return:
"""
if not isinstance(y, (pd.Series, pd.DataFrame)):
raise TypeError("`y` must be pd.Series or pd.DataFrame containing independent variable returns")
if not isinstance(xs, (pd.Series, pd.DataFrame)):
raise TypeError("`xs` must be pd.Series or pd.DataFrame containing dependent variables returns")
if isinstance(y, pd.Series):
y = y.to_frame(y.name)
elif isinstance(y, pd.DataFrame):
if y.shape[1] > 1:
print("`y` must contains only one column. subsetting `y` to obtain a 1col df")
if isinstance(xs, pd.Series):
xs = xs.to_frame(xs.name)
# bisogna fare in modo che le date (.index) coincidano
if len(set(y.index).symmetric_difference(xs.index)):
# merge per allineare le date
tmp = pd.concat([y, xs], axis=1)
# inserisci zero al posto degli NA
tmp = tmp.fillna(0)
y = tmp[y.columns]
xs = tmp[xs.columns]
# inizializza un pd.DataFrame dove verranno salvati i beta
beta = np.zeros((len(xs.columns), len(y.columns)))
beta = pd.DataFrame(beta, index=xs.columns, columns=y.columns)
# multiple regression
m = LinearRegression(fit_intercept=True)
m.fit(xs, y)
beta[y.columns[0]] = m.coef_.transpose()
return beta
def compute_rolling_beta(ret, bmk_ret, window=252):
"""
Computes single-regression beta over a rolling window. ret = alpha + beta * bmk_ret
Works with:
(ret is pd.Series or 1 col pd.DataFrame) and (bmk_ret is pd.Series or 1 col pd.DataFrame)
ret is pd.DataFrame and (bmk_ret is pd.Series or 1 col pd.DataFrame)
(ret is pd.Series or 1 col pd.DataFrame) and bmk_ret is pd.DataFrame
https://corporatefinanceinstitute.com/resources/knowledge/finance/beta-coefficient/
:param ret: stock/portfolio returns. works with multiple timeseries as well
:param bmk_ret: benchmark returns. works with multiple benckmarks
:param window: int, lenght of rolling window
:return:
"""
if not isinstance(ret, (pd.Series, pd.DataFrame)):
raise TypeError("`ret` must be pd.Series or pd.DataFrame containing returns")
if not isinstance(bmk_ret, (pd.Series, pd.DataFrame)):
raise TypeError("`bmk_ret` must be pd.Series or pd.DataFrame containing benchmark returns")
if isinstance(ret, pd.DataFrame) and isinstance(bmk_ret, pd.DataFrame):
if len(ret.columns) > 1 and len(bmk_ret.columns) > 1:
raise NotImplementedError("Function cannot process results with `ret` and `bmk_ret` with >1 cols each")
# inizializza beta come lista
beta = list()
for i in range(window, ret.shape[0]):
y = ret.iloc[(i - window):i]
x = bmk_ret.iloc[(i - window):i]
b = compute_beta(y, x)
if isinstance(b, float):
# case y is pd.Series and x is pd.Series
b = pd.Series(b, index=[y.index.max()])
elif isinstance(b, pd.Series):
# case y is pd.DataFrame and x is pd.Series
b = b.to_frame().transpose()
b.index = [y.index.max()]
elif isinstance(b, pd.DataFrame):
# case y is pd.Series and x is pd.Dataframe
b.index = [y.index.max()]
beta.append(b)
beta = pd.concat(beta, axis=0)
return beta
def compute_annualized_downside_deviation(returns, benchmark_rate=0):
"""
Calculates the downside deviation for use in the sortino ratio.
Benchmark rate is assumed to be annualized. It will be adjusted according
to the number of periods per year seen in the data.
"""
# For both de-annualizing the benchmark rate and annualizing result
years_past = get_years_past(returns)
entries_per_year = returns.shape[0] / years_past
adjusted_benchmark_rate = ((1 + benchmark_rate) ** (1 / entries_per_year)) - 1
downside_series = adjusted_benchmark_rate - returns
downside_sum_of_squares = (downside_series[downside_series > 0] ** 2).sum()
denominator = returns.shape[0] - 1
downside_deviation = np.sqrt(downside_sum_of_squares / denominator)
return downside_deviation * np.sqrt(entries_per_year)
def compute_sortino_ratio(prices, benchmark_rate=0):
"""
Calculates the sortino ratio.
"""
cagr = compute_cagr(prices)
return_series = compute_returns(prices)
downside_deviation = compute_annualized_downside_deviation(return_series)
return (cagr - benchmark_rate) / downside_deviation
def compute_jensens_alpha(returns, benchmark_return_series):
"""
Calculates jensens alpha. Prefers input series have the same index. Handles
NAs.
:param returns: pd.Series
:param benchmark_return_series: pd.Series with benchmark return
"""
if isinstance(returns, pd.DataFrame):
warnings.warn("returns must be pd.Series, taking the first column: {}".format(returns.columns[0]))
returns = returns[returns.columns[0]]
# Join series along date index and purge NAs
df = pd.concat([returns, benchmark_return_series], sort=True, axis=1)
df = df.dropna()
# Get the appropriate data structure for scikit learn
clean_returns = df[df.columns.values[0]]
clean_benchmarks = pd.DataFrame(df[df.columns.values[1]])
# Fit a linear regression and return the alpha
regression = LinearRegression().fit(clean_benchmarks, y=clean_returns)
return regression.intercept_
def compute_drawdown_series(prices, method="simple"):
"""
Returns the drawdown series
"""
if method == "simple":
evaluator = lambda price, peak: (price / peak) - 1
elif method == "log":
evaluator = lambda price, peak: np.log(prices) - np.log(peak)
else:
ValueError("method should be either simple or log")
return evaluator(prices, prices.cummax())
def compute_max_drawdown(prices, method="simple"):
"""
Simply returns the max drawdown as a float
"""
return compute_drawdown_series(prices, method=method).min()
def compute_calmar_ratio(prices, years_past=None, method="simple"):
"""
Return the percent max drawdown ratio over the past n years, otherwise
known as the Calmar Ratio (3yr)
"""
if isinstance(years_past, int):
# Filter series on past three years
last_date = prices.index[-1]
n_years_ago = last_date - pd.Timedelta(days=years_past * 365.25)
prices = prices[prices.index > n_years_ago]
# Compute annualized percent max drawdown ratio
percent_drawdown = -compute_max_drawdown(prices, method=method)
cagr = compute_cagr(prices)
return cagr / percent_drawdown
def compute_parametric_var(returns, conf_lvl=.95):
"""
:param returns pd.Series or pd.DataFrame
:param conf_lvl: float, confidence level
ref: https://blog.quantinsti.com/calculating-value-at-risk-in-excel-python/
"""
mu = np.mean(returns)
sigma = np.std(returns)
# Percent Point Function
VaR = norm.ppf(1 - conf_lvl, mu, sigma)
if isinstance(returns, pd.DataFrame):
VaR = pd.Series(VaR, index=returns.columns, name="Parametric VaR")
return VaR
def compute_historical_var(returns, conf_lvl=.95):
"""
:param returns pd.Series or pd.DataFrame
:param conf_lvl: float, confidence level
ref: https://blog.quantinsti.com/calculating-value-at-risk-in-excel-python/
"""
VaR = returns.quantile(1 - conf_lvl)
if isinstance(returns, pd.DataFrame):
VaR.name = "Historical VaR"
return VaR
def compute_corr(ts, df=None):
"""
computes correlation over all given period
if `ts` is pd.Series, then it computes `ts` vs all `df` cols
if `ts` is pd.DataFrame and `df` is None, then it computes all pairwise corr between `ts` cols
if `ts` is pd.DataFrame and `df` is pd.Series, then it computes all `ts` vs `df`
:param ts: pd.Series or pd.DataFrame
if pd.Series, then `df` is mandatory and must be pd.Series or pd.DataFrame
if pd.DataFrame and `df` is not given, then all pairwise correlations are computed
if pd.DataFrame and `df` is pd.Series, then all correlation btw `ts` and `df` are computed
:param df: None or pd.Series, pd.DataFrame
"""
if isinstance(ts, pd.Series) and df is None:
print("please provide argument `df` (can't be None if `ts` is pd.Series)")
return
if isinstance(ts, pd.Series):
if isinstance(df, pd.Series):
# output: float
corr = ts.corr(df)
# corr.columns = [ts.name + "-" + df.name]
elif isinstance(df, pd.DataFrame):
# output: pd.Series
corr = df.apply(lambda x: x.corr(ts), axis=0).reset_index(name="corr")
# corr.columns = [ts.name + "-" + col for col in corr.columns]
if isinstance(ts, pd.DataFrame):
if df is None:
corr = pd.DataFrame(0, index=ts.columns, columns=ts.columns)
for i in range(len(ts.columns)):
for j in range(i, len(ts.columns)):
corr.iloc[i, j] = ts[ts.columns[i]].corr(ts[ts.columns[j]])
# it's the same
corr.iloc[j, i] = corr.iloc[i, j]
elif isinstance(df, pd.Series):
corr = ts.apply(lambda x: x.corr(df), axis=0)
corr.name = "corr"
elif isinstance(df, pd.DataFrame):
corr = list()
for i in range(len(df.columns)):
pair_corr = ts.apply(lambda x: x.corr(df[df.columns[i]]), axis=0) # .reset_index(name=df.columns[i])
pair_corr.name = df.columns[i]
corr.append(pair_corr)
corr = pd.concat(corr, axis=1)
return corr
def compute_rolling_corr(ts, df=None, window=252):
"""
compute rolling correlations. if `ts` is pd.Series, then it computes `ts` vs all `df` cols
if `ts` is pd.DataFrame and `df` is None, then it computes all pairwise corr between `ts` cols
if `ts` is pd.DataFrame and `df` is pd.Series, then it computes all `ts` vs `df`
:param ts: pd.Series or pd.DataFrame
if pd.Series, then `df` is mandatory and must be pd.Series or pd.DataFrame
if pd.DataFrame and `df` is not given, then all pairwise correlations are computed
if pd.DataFrame and `df` is pd.Series, then all correlation btw `ts` and `df` are computed
:param df: None or pd.Series, pd.DataFrame
:param window: int, rolling window
"""
if isinstance(ts, pd.Series) and df is None:
raise TypeError("please provide argument `df` (can't be None if `ts` is pd.Series)")
if isinstance(ts, pd.DataFrame) and len(ts.columns) == 1:
# if ts is pd.DataFrame with 1 col, convert to pd.Series
ts = ts[ts.columns[0]]
if isinstance(df, pd.DataFrame) and len(df.columns) == 1:
# if df is pd.DataFrame with 1 col, convert to pd.Series
df = df[df.columns[0]]
if isinstance(ts, pd.Series):
if isinstance(df, pd.Series):
corr = ts.rolling(window).corr(df).to_frame()
corr.columns = [ts.name + "-" + df.name]
elif isinstance(df, pd.DataFrame):
corr = df.rolling(window).apply(lambda x: x.corr(ts))
corr.columns = [ts.name + "-" + col for col in corr.columns]
if isinstance(ts, pd.DataFrame):
if df is None:
corr = list()
for i in range(len(ts.columns) - 1):
for j in range(i + 1, len(ts.columns)):
pair_corr = ts[ts.columns[i]].rolling(window).corr(ts[ts.columns[j]]).to_frame()
pair_corr.columns = [ts.columns[i] + "-" + ts.columns[j]]
corr.append(pair_corr)
corr = pd.concat(corr, axis=1)
elif isinstance(df, pd.Series):
corr = list()
for i in range(len(ts.columns)):
pair_corr = ts[ts.columns[i]].rolling(window).corr(df).to_frame()
pair_corr.columns = [ts.columns[i] + "-" + df.name]
corr.append(pair_corr)
corr = pd.concat(corr, axis=1)
corr = corr.dropna()
return corr
def compute_summary_statistics(ts, return_annualized=True):
"""
Computes statistics (annualised return and annualised std) for various time-frame
Time-frames are: YTD, 1m, 3m, 6m, 1y, 2y, 3y, 5y, ALL
:param ts: pd.DataFrame with prices time series
:param return_annualized: boolean, if True return annualized returns, otherwise periodic returns
:return: pd.DataFrame(s) with summary statistics with column
if ts is pd.DataFrame: | ShareClassISIN | metric | interval | value |
if ts is pd.Series: | metric | interval | value |
"""
assert(isinstance(ts, (pd.Series, pd.DataFrame)))
# quanti anni è lunga la serie storica? in base a questo capiamo fino a che periodo possiamo calcolare
n_years = get_years_past(ts)
# calcola ritorni sui vari time-frame.
last_date = ts.index.to_list()[-1]
ytd_date = last_date + pd.tseries.offsets.YearEnd(-1)
one_mo_date = last_date + pd.tseries.offsets.DateOffset(months=-1)
three_mo_date = last_date + pd.tseries.offsets.DateOffset(months=-3)
six_mo_date = last_date + pd.tseries.offsets.DateOffset(months=-6)
one_ye_date = last_date + pd.tseries.offsets.DateOffset(years=-1)
two_ye_date = last_date + pd.tseries.offsets.DateOffset(years=-2)
three_ye_date = last_date + pd.tseries.offsets.DateOffset(years=-3)
five_ye_date = last_date + pd.tseries.offsets.DateOffset(years=-5)
ret = compute_returns(ts)
if return_annualized:
return_function = compute_cagr
ret_type = "Annualized Return"
else:
return_function = compute_allperiod_returns
ret_type = "Return"
if isinstance(ts, pd.Series):
statistics = [
[ret_type, "YTD", return_function(ts.loc[ytd_date:])],
[ret_type, "1 Month", return_function(ts.loc[one_mo_date:])],
[ret_type, "3 Months", return_function(ts.loc[three_mo_date:])],
[ret_type, "6 Months", return_function(ts.loc[six_mo_date:])],
[ret_type, "1 Year", return_function(ts.loc[one_ye_date:])],
[ret_type, "2 Years", return_function(ts.loc[two_ye_date:])],
[ret_type, "3 Years", return_function(ts.loc[three_ye_date:])],
[ret_type, "5 Years", return_function(ts.loc[five_ye_date:])],
[ret_type, "All Period", return_function(ts)],
["Standard Deviation", "YTD", compute_annualized_volatility(ret.loc[ytd_date:])],
["Standard Deviation", "1 Month", compute_annualized_volatility(ret.loc[one_mo_date:])],
["Standard Deviation", "3 Months", compute_annualized_volatility(ret.loc[three_mo_date:])],
["Standard Deviation", "6 Months", compute_annualized_volatility(ret.loc[six_mo_date:])],
["Standard Deviation", "1 Year", compute_annualized_volatility(ret.loc[one_ye_date:])],
["Standard Deviation", "2 Years", compute_annualized_volatility(ret.loc[two_ye_date:])],
["Standard Deviation", "3 Years", compute_annualized_volatility(ret.loc[three_ye_date:])],
["Standard Deviation", "5 Years", compute_annualized_volatility(ret.loc[five_ye_date:])],
["Standard Deviation", "All Period", compute_annualized_volatility(ret)]
]
# crea pd.DataFrame()
statistics = pd.DataFrame(statistics, columns=["metric", "interval", "value"])
else:
# ts è pd.DataFrame()
statistics = pd.concat([
pd.DataFrame({"metric": ret_type, "interval": "YTD", "value": return_function(ts.loc[ytd_date:])}),
pd.DataFrame({"metric": ret_type, "interval": "1 Month", "value": return_function(ts.loc[one_mo_date:])}),
pd.DataFrame({"metric": ret_type, "interval": "3 Months", "value": return_function(ts.loc[three_mo_date:])}),
pd.DataFrame({"metric": ret_type, "interval": "6 Months", "value": return_function(ts.loc[six_mo_date:])}),
pd.DataFrame({"metric": ret_type, "interval": "1 Year", "value": return_function(ts.loc[one_ye_date:])}),
pd.DataFrame({"metric": ret_type, "interval": "2 Years", "value": return_function(ts.loc[two_ye_date:])}),
pd.DataFrame({"metric": ret_type, "interval": "3 Years", "value": return_function(ts.loc[three_ye_date:])}),
pd.DataFrame({"metric": ret_type, "interval": "5 Years", "value": return_function(ts.loc[five_ye_date:])}),
pd.DataFrame({"metric": ret_type, "interval": "All Period", "value": return_function(ts)}),
pd.DataFrame({"metric": "Standard Deviation", "interval": "YTD",
"value": compute_annualized_volatility(ret.loc[ytd_date:])}),
pd.DataFrame({"metric": "Standard Deviation", "interval": "1 Month",
"value": compute_annualized_volatility(ret.loc[one_mo_date:])}),
pd.DataFrame({"metric": "Standard Deviation", "interval": "3 Months",
"value": compute_annualized_volatility(ret.loc[three_mo_date:])}),
pd.DataFrame({"metric": "Standard Deviation", "interval": "6 Months",
"value": compute_annualized_volatility(ret.loc[six_mo_date:])}),
pd.DataFrame({"metric": "Standard Deviation", "interval": "1 Year",
"value": compute_annualized_volatility(ret.loc[one_ye_date:])}),
pd.DataFrame({"metric": "Standard Deviation", "interval": "2 Years",
"value": compute_annualized_volatility(ret.loc[two_ye_date:])}),
pd.DataFrame({"metric": "Standard Deviation", "interval": "3 Years",
"value": compute_annualized_volatility(ret.loc[three_ye_date:])}),
pd.DataFrame({"metric": "Standard Deviation", "interval": "5 Years",
"value": compute_annualized_volatility(ret.loc[five_ye_date:])}),
pd.DataFrame({"metric": "Standard Deviation", "interval": "All Period",
"value": compute_annualized_volatility(ret)})
])
statistics = statistics.reset_index()
return statistics
def compute_turnover(hldg, index="Date", columns="ISIN", values="w_rebase"):
"""
NB: per il turnover preciso, usare Portfolio().portfolio_returns(verbose=True). quella funzione calcola
il turnover usando i pesi end of period.
Se si vuole calcolare il turnover di indici o ptf per cui si hanno solo i pesi puntuali alle rebalancing, ma non
i prezzi per poter calcolare i pesi end of period, allora usare questa funzione. è un'approssimazione molto fedele.
:param hldg: pd.DataFrame with holdings over time
:param index: column with dates. if pd.DF is indexed by Dates, then use index=True
:param columns: column with instruments identifier (es: "ISIN", "Ticker")
:param values: column with weights
:return: portfolio turnover over time
"""
if index is True:
# https://docs.quantifiedcode.com/python-anti-patterns/readability/comparison_to_true.html
# Dates are in hdlg.index
hldg = hldg.reset_index()
index = "index"
if not all([x in hldg.columns for x in [index, columns, values]]):
raise IndexError(f"hldg must contains columns: {index}, {columns}, {values}")
# pivot per calcolare più velocemente il turnover
hh = hldg.pivot(index=index, columns=columns, values=values)
hh = hh.fillna(0)
turnover_i = list()
for i in range(len(hh)):
if i == 0:
continue
# secondo la definizione di cui sopra, il massimo turnover è 2. se modifichiamo l'allocazione dell'intero
# ptf vogliamo turnover=1
# turnover_i.append(np.sum(np.abs(hh.iloc[i] - hh.iloc[i - 1])) / 2)
turnover_i.append(np.sum(np.abs(hh.iloc[i] - hh.iloc[i - 1])))
turnover = pd.Series(turnover_i, index=hh.index[1:])
return turnover
# PRINT NICE STATISTICS
def print_stats(ts, line_length=50):
"""
given pd.Series or pd.DataFrame of time-series (prices), prints statistics
:param ts: ts.index must contain dates
:param line_length: int, lenght of line print
:return:
"""
if isinstance(ts, pd.Series):
is_series = True
elif isinstance(ts, pd.DataFrame):
is_series = False
else:
raise TypeError(f"ts must be pd.Series, pd.DataFrame.")
# compute returns
ret = compute_returns(ts)
def _nice(line, length=50):
# print nice line given lenght.
assert isinstance(line, str)
if line[:2] != "# ":
line = "# " + line
print(f"{line}{' ' * max(0, (length - len(line) - 2))} #")
print("#" * line_length)
if is_series:
_nice(f"Timeseries: {ts.name}", line_length)
else:
_nice(f"Timeseries: {', '.join(ts.columns)}", line_length)
_nice(f"# Period: {ts.index.min().strftime('%Y-%m-%d')} - {ts.index.max().strftime('%Y-%m-%d')}", line_length)
print("#" * line_length)
if is_series:
_nice(f"CAGR: {compute_cagr(ts):.2%}", line_length)
_nice(f"All period return: {compute_allperiod_returns(ts):.2%}", line_length)
_nice(f"Volatility: {compute_annualized_volatility(ret):.2%}", line_length)
_nice(f"Sharpe Ratio: {compute_sharpe_ratio(ret):.2}", line_length)
_nice(f"Sortino Ratio: {compute_sortino_ratio(ts):.2}", line_length)
_nice(f"Calmar Ratio: {compute_calmar_ratio(ts):.2}", line_length)
_nice(f"Max Drawdown: {compute_max_drawdown(ts):.2%}", line_length)
_nice(f"Parametric 95% VaR: {compute_parametric_var(ret):.2%}", line_length)
_nice(f"Historical 95% VaR: {compute_historical_var(ret):.2%}", line_length)
print("#" * line_length)
else:
_nice(f"That's all for now folks")
print("#" * line_length)
# REPLICA
def compute_replica_groupby(holdings, groupby=["country", "sector"], overall_coverage=.85, groupby_coverage=None,
threshold=.02, rebase=1, minw=0, maxw=1, id_col="isin", w_col="w", keep_all_cols=True):
"""
Compute replica of a portfolio (could be index), grouping on key specified by `groupby`
:param holdings: pd.DataFrame with components for a single date
:param groupby: key for the index replication. must be cols of holdings. str or list of str
:param overall_coverage: percentage of index covering. float
:param groupby_coverage: None or float. if float, then also check for coverage inside groupby.
Makes sense to be used if index is weighted by marketcap
:param threshold: minimum weight a groupby cell must have in order to get more than 1 stock. float
:param rebase: int/float or None. if None, do not rebase. if not None, rebase to value of rebase
:param minw: float, minimum weight
:param maxw: float, maximum weight
:param id_col: str, column of holdings. col of the identifier
:param w_col: str, column of holdings. col of the weights
:param keep_all_cols: boolean, if True keep all columns from initial holdings
:return replica portfolio
"""
# check if inputs are of the correct type
if not isinstance(holdings, pd.DataFrame):
raise TypeError("holdings must be pd.DataFrame")
if not isinstance(groupby, (str, list)):
raise TypeError("groupby must be str or list of str")
if isinstance(groupby, list):
if not all(isinstance(item, str) for item in groupby):
raise TypeError("all elements of groupby must be str")
else:
groupby = [groupby]
if not isinstance(overall_coverage, (int, float)):
raise TypeError("overall_coverage must be a float")
if groupby_coverage is not None:
if not isinstance(groupby_coverage, float):
raise TypeError("groupby_coverage must be None or float")
if not isinstance(threshold, (int, float)):
raise TypeError("threshold must be a float")
if rebase is not None:
if not isinstance(rebase, (int, float)):
raise TypeError("groupby_coverage must be None or int/float")
assert isinstance(minw, (int, float)), "`minw` must be float"
assert isinstance(maxw, (int, float)), "`maxw` must be float"
if (minw < 0) | (minw >= 1):
raise ValueError("`minw` in [0, 1) required")
if (maxw <= 0) | (maxw > 1):
raise ValueError("`maxw` in (0, 1] required")
if not isinstance(id_col, (str, list)):
raise TypeError("id_col must be str or list of str")
if isinstance(id_col, list):
if not all(isinstance(item, str) for item in id_col):
raise TypeError("all elements of id_col must be str")
else:
id_col = [id_col]
if not isinstance(w_col, str):
raise TypeError("w_col must be str")
if not isinstance(keep_all_cols, bool):
raise TypeError("keep_all_cols must be boolean")
# check if all needed columns are in holdings
required_cols = [*id_col, w_col, *groupby]
if not set(required_cols).issubset(set(holdings.columns)):
raise Exception(f"components must have columns: {id_col}, {w_col}, {groupby}")
def cut_coverage(df, col, lvl):
"""
:param df: pd.DataFrame with col in df.columns
:param col: str, df's column of floats
:param lvl: float, threshold where to cut
"""
x = df[col].values
# https://stackoverflow.com/questions/2361426/get-the-first-item-from-an-iterable-that-matches-a-condition
cut_idx = next((i for i, y in enumerate(x) if y > lvl), 1)
return df.iloc[:cut_idx]
if rebase is not None:
# rebase weights
holdings[w_col] = holdings[w_col] / holdings[w_col].sum() * rebase
if keep_all_cols:
# mantieni da parte le colonne non necessarie, fai il merge in fondo
other_cols = list(set(holdings.columns).difference(required_cols))
other_cols = [*other_cols, *id_col]
if len(other_cols) > 1:
df_other_cols = holdings[other_cols]
# select only needed columns
hldg = holdings[required_cols]
stat = hldg.groupby(groupby).sum()
# sort descending by weight
stat = stat.sort_values(by=[w_col], ascending=False)
# compute cumulative sum
stat["cumulative_sum"] = stat[w_col].cumsum()
stat = stat.reset_index()
# select groupby cells up to `overall_coverage`
cells = cut_coverage(stat, col="cumulative_sum", lvl=overall_coverage)
cells = cells.copy()
print(f"Selecting first {len(cells)} out of {len(stat)} combinations of {groupby}")
# rebase weight to 1 on selected cells
cells["w_rebase"] = cells[w_col] / cells[w_col].sum()
# assegna il numero di titoli da scegliere all'interno di ogni combinazione groupby
cells["n_stocks"] = np.ceil(cells["w_rebase"] / threshold)
if groupby_coverage is None:
# first method
# gli n assegnati NON vengono modificati
# vengono scelte le prime n stock per weight in ogni combinazione groupby
# attacca a `hldg` le informazioni sulla numerosità delle coppie sector/country
hldg = pd.merge(hldg, cells[[*groupby, "n_stocks"]], how="left", on=groupby)
# sort by groupby and weight, ascending order for groupby and descending for weight
hldg = hldg.sort_values([*groupby, w_col], ascending=[*[True] * len(groupby), False])
# NA sono le celle non scelte
replica = hldg.dropna()
# select first n_stock for each cells
# select first x.shape[0] if n_stock > x.shape[0]
replica = replica.groupby(groupby).apply(lambda x: x.iloc[:min(int(x["n_stocks"].unique()), x.shape[0])])
replica = replica.reset_index(drop=True)
else:
# second method
# es: per sector == 'a' & country == 'A' ho n = 2, e le seguenti stock:
# | ticker | w |
# | aa | .15 |
# | bb | .12 |
# | cc | .10 |
# | dd | .09 |
# | ee | .08 |
# con METODO 1 verrebbero scelte le stock `aa` e `bb`, poiché le prime 2 (n = 2)
# per marketcap
# con METOOD 2 vengono scelte le stock `aa`, `bb` e `cc` per rispettare la
# `copertura_groupby` = .7
# tot_w = .15 + .12 + .1 + .09 + .08 = .54
# tot_w * copertura_groupby = .378 <-- quando la cumulata dei pesi raggiunge .378 TAGLIA !
# cumsum(w) = .15, .27, .37, .46, .54
# tagliamo al terzo elemento, per cui la `cumsum` raggiunge il massimo valore
# che è minore di .378
# coppie groupby da cui devo pescare k stocks s.t. venga replicato almeno
# copertura_groupby% della capitalizzazione della coppia
cells_k = cells.loc[cells["n_stocks"] > 1]
hldg_k = pd.merge(hldg, cells_k[groupby], how="inner", on=groupby)
# sort by groupby and weight, ascending order for groupby and descending for weight
hldg_k = hldg_k.sort_values([*groupby, w_col], ascending=[*[True] * len(groupby), False])
# calcola il peso cumulato delle combinazioni groupby
hldg_k["cumulative_sum"] = \
hldg_k.groupby(groupby).apply(lambda x: x[w_col].cumsum() / x[w_col].sum()).values
# prendi le prime k stocks s.t. vi è una copertura almeno del copertura_groupby%
replica = hldg_k.groupby(groupby).apply(lambda x: cut_coverage(x, col="cumulative_sum", lvl=groupby_coverage))
replica = replica.reset_index(drop=True)
del replica["cumulative_sum"]
# combinazioni groupby da cui devo pescare solo 1 stock
cells_k = cells.loc[cells["n_stocks"] == 1]
if len(cells_k):
hldg_k = pd.merge(hldg, cells_k[groupby], how="inner", on=groupby)
# sort by groupby and weight, ascending order for groupby and descending for weight
hldg_k = hldg_k.sort_values([*groupby, w_col], ascending=[*[True] * len(groupby), False])
# prendi le prime stocks in ogni combinazione ed aggiungile a ptf
replica = replica.append(
hldg_k.groupby(groupby).apply(lambda x: x.iloc[0]).reset_index(drop=True)
)
print(f"Selected {replica.shape[0]} stocks out of {holdings.shape[0]}")
# set replica weights
# aggiungi colonna contente il peso di ogni combinazione groupby
replica =
|
pd.merge(replica, cells[[*groupby, "w_rebase"]], how="left", on=groupby)
|
pandas.merge
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import re
import pandas as pd
def get_date_etf_list_from_data(directory='data'):
"""
Returns list of dates and etfs based on files in the given directory
Parameters
----------
directory : str, optional
Directory where CSV files are stored. The default is 'data'.
Returns
-------
dates : list of str
Strings of dates found in files. Format YYYY-MM-DD.
etfs : list of str
Strings of ETF ticker symbols.
"""
files = os.listdir(directory)
files = [f.split('.csv')[0] for f in files if '.csv' in f]
dates = set()
etfs = set()
ba_data_name = re.compile('[0-9]{4}\-[0-9]{2}\-[0-9]{2}_[A-Z]{2,6}')
for f in files:
if ba_data_name.match(f):
date, etf = f.split('_')
dates.add(date)
etfs.add(etf)
return dates, etfs
def create_and_save_quoated_spread_data(directory='data', sample_frequency=60, ignore_errors=1):
"""
Convert quoted spreads from various CSV files of various days' and ETFs' data to one data frame.
Parameters
----------
directory : str, optional
Folder containing data to be read. The default is 'data'.
sample_frequency : int, optional
Number of seconds of each data lump. The default is 60.
ignore_errors : int, optional
Level of ignoring errors in file reading:
0 = raise exceptions
1 = catch and print unavailable files
2 = catch and pass
Returns
-------
quoted_spread : pd.DataFrame
If an exeption occurs, returns data frame of quoted spread data. If no
exception, returns None.
"""
dates, etfs = get_date_etf_list_from_data(directory)
mi = pd.MultiIndex.from_product([dates, etfs], names=['dates','etf'])
quoted_spread = pd.DataFrame(columns=mi)
for index, date in enumerate(dates):
for etf in etfs:
try:
df = pd.read_csv(os.path.join(directory, '{}_{}.csv'.format(date, etf)), index_col=0)
except FileNotFoundError as e:
if ignore_errors == 0:
raise e
elif ignore_errors == 1:
print("Failed to find file for {} on {}".format(etf, date))
elif ignore_errors == 2:
pass
else:
raise AttributeError("ignore_errors must be 0, 1, 2. Given {}".format(ignore_errors))
quoted_spread[(date, etf)] = df['relative spread']
if index%10 == 0:
print('finished {}/{} dates'.format(index, len(dates)))
try:
basetime =
|
pd.to_datetime('2021-01-01')
|
pandas.to_datetime
|
""" parquet compat """
from __future__ import annotations
from distutils.version import LooseVersion
import io
import os
from typing import Any, AnyStr, Dict, List, Optional, Tuple
from warnings import catch_warnings
from pandas._typing import FilePathOrBuffer, StorageOptions
from pandas.compat._optional import import_optional_dependency
from pandas.errors import AbstractMethodError
from pandas.util._decorators import doc
from pandas import DataFrame, MultiIndex, get_option
from pandas.core import generic
from pandas.io.common import (
IOHandles,
get_handle,
is_fsspec_url,
is_url,
stringify_path,
)
def get_engine(engine: str) -> BaseImpl:
""" return our implementation """
if engine == "auto":
engine = get_option("io.parquet.engine")
if engine == "auto":
# try engines in this order
engine_classes = [PyArrowImpl, FastParquetImpl]
error_msgs = ""
for engine_class in engine_classes:
try:
return engine_class()
except ImportError as err:
error_msgs += "\n - " + str(err)
raise ImportError(
"Unable to find a usable engine; "
"tried using: 'pyarrow', 'fastparquet'.\n"
"A suitable version of "
"pyarrow or fastparquet is required for parquet "
"support.\n"
"Trying to import the above resulted in these errors:"
f"{error_msgs}"
)
if engine == "pyarrow":
return PyArrowImpl()
elif engine == "fastparquet":
return FastParquetImpl()
raise ValueError("engine must be one of 'pyarrow', 'fastparquet'")
def _get_path_or_handle(
path: FilePathOrBuffer,
fs: Any,
storage_options: StorageOptions = None,
mode: str = "rb",
is_dir: bool = False,
) -> Tuple[FilePathOrBuffer, Optional[IOHandles], Any]:
"""File handling for PyArrow."""
path_or_handle = stringify_path(path)
if is_fsspec_url(path_or_handle) and fs is None:
fsspec = import_optional_dependency("fsspec")
fs, path_or_handle = fsspec.core.url_to_fs(
path_or_handle, **(storage_options or {})
)
elif storage_options and (not is_url(path_or_handle) or mode != "rb"):
# can't write to a remote url
# without making use of fsspec at the moment
raise ValueError("storage_options passed with buffer, or non-supported URL")
handles = None
if (
not fs
and not is_dir
and isinstance(path_or_handle, str)
and not os.path.isdir(path_or_handle)
):
# use get_handle only when we are very certain that it is not a directory
# fsspec resources can also point to directories
# this branch is used for example when reading from non-fsspec URLs
handles = get_handle(
path_or_handle, mode, is_text=False, storage_options=storage_options
)
fs = None
path_or_handle = handles.handle
return path_or_handle, handles, fs
class BaseImpl:
@staticmethod
def validate_dataframe(df: DataFrame):
if not isinstance(df, DataFrame):
raise ValueError("to_parquet only supports IO with DataFrames")
# must have value column names for all index levels (strings only)
if isinstance(df.columns, MultiIndex):
if not all(
x.inferred_type in {"string", "empty"} for x in df.columns.levels
):
raise ValueError(
"""
parquet must have string column names for all values in
each level of the MultiIndex
"""
)
else:
if df.columns.inferred_type not in {"string", "empty"}:
raise ValueError("parquet must have string column names")
# index level names must be strings
valid_names = all(
isinstance(name, str) for name in df.index.names if name is not None
)
if not valid_names:
raise ValueError("Index level names must be strings")
def write(self, df: DataFrame, path, compression, **kwargs):
raise AbstractMethodError(self)
def read(self, path, columns=None, **kwargs):
raise AbstractMethodError(self)
class PyArrowImpl(BaseImpl):
def __init__(self):
import_optional_dependency(
"pyarrow", extra="pyarrow is required for parquet support."
)
import pyarrow.parquet
# import utils to register the pyarrow extension types
import pandas.core.arrays._arrow_utils # noqa
self.api = pyarrow
def write(
self,
df: DataFrame,
path: FilePathOrBuffer[AnyStr],
compression: Optional[str] = "snappy",
index: Optional[bool] = None,
storage_options: StorageOptions = None,
partition_cols: Optional[List[str]] = None,
**kwargs,
):
self.validate_dataframe(df)
from_pandas_kwargs: Dict[str, Any] = {"schema": kwargs.pop("schema", None)}
if index is not None:
from_pandas_kwargs["preserve_index"] = index
table = self.api.Table.from_pandas(df, **from_pandas_kwargs)
path_or_handle, handles, kwargs["filesystem"] = _get_path_or_handle(
path,
kwargs.pop("filesystem", None),
storage_options=storage_options,
mode="wb",
is_dir=partition_cols is not None,
)
try:
if partition_cols is not None:
# writes to multiple files under the given path
self.api.parquet.write_to_dataset(
table,
path_or_handle,
compression=compression,
partition_cols=partition_cols,
**kwargs,
)
else:
# write to single output file
self.api.parquet.write_table(
table, path_or_handle, compression=compression, **kwargs
)
finally:
if handles is not None:
handles.close()
def read(
self,
path,
columns=None,
use_nullable_dtypes=False,
storage_options: StorageOptions = None,
**kwargs,
):
kwargs["use_pandas_metadata"] = True
to_pandas_kwargs = {}
if use_nullable_dtypes:
if LooseVersion(self.api.__version__) >= "0.16":
import pandas as pd
mapping = {
self.api.int8(): pd.Int8Dtype(),
self.api.int16(): pd.Int16Dtype(),
self.api.int32(): pd.Int32Dtype(),
self.api.int64(): pd.Int64Dtype(),
self.api.uint8(): pd.UInt8Dtype(),
self.api.uint16():
|
pd.UInt16Dtype()
|
pandas.UInt16Dtype
|
#
# Copyright 2018 Quantopian, 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.
from __future__ import annotations
from datetime import time
from os.path import abspath, dirname, join
from unittest import TestCase
import typing
import re
import functools
import itertools
import pathlib
from collections import abc
import pytest
import numpy as np
import pandas as pd
import pandas.testing as tm
from pandas import Timedelta, read_csv
from parameterized import parameterized
import pytz
from pytz import UTC
from toolz import concat
from exchange_calendars import get_calendar
from exchange_calendars.calendar_utils import (
ExchangeCalendarDispatcher,
_default_calendar_aliases,
_default_calendar_factories,
)
from exchange_calendars.errors import (
CalendarNameCollision,
InvalidCalendarName,
NoSessionsError,
)
from exchange_calendars.exchange_calendar import ExchangeCalendar, days_at_time
from .test_utils import T
class FakeCalendar(ExchangeCalendar):
name = "DMY"
tz = "Asia/Ulaanbaatar"
open_times = ((None, time(11, 13)),)
close_times = ((None, time(11, 49)),)
class CalendarRegistrationTestCase(TestCase):
def setup_method(self, method):
self.dummy_cal_type = FakeCalendar
self.dispatcher = ExchangeCalendarDispatcher({}, {}, {})
def teardown_method(self, method):
self.dispatcher.clear_calendars()
def test_register_calendar(self):
# Build a fake calendar
dummy_cal = self.dummy_cal_type()
# Try to register and retrieve the calendar
self.dispatcher.register_calendar("DMY", dummy_cal)
retr_cal = self.dispatcher.get_calendar("DMY")
self.assertEqual(dummy_cal, retr_cal)
# Try to register again, expecting a name collision
with self.assertRaises(CalendarNameCollision):
self.dispatcher.register_calendar("DMY", dummy_cal)
# Deregister the calendar and ensure that it is removed
self.dispatcher.deregister_calendar("DMY")
with self.assertRaises(InvalidCalendarName):
self.dispatcher.get_calendar("DMY")
def test_register_calendar_type(self):
self.dispatcher.register_calendar_type("DMY", self.dummy_cal_type)
retr_cal = self.dispatcher.get_calendar("DMY")
self.assertEqual(self.dummy_cal_type, type(retr_cal))
def test_both_places_are_checked(self):
dummy_cal = self.dummy_cal_type()
# if instance is registered, can't register type with same name
self.dispatcher.register_calendar("DMY", dummy_cal)
with self.assertRaises(CalendarNameCollision):
self.dispatcher.register_calendar_type("DMY", type(dummy_cal))
self.dispatcher.deregister_calendar("DMY")
# if type is registered, can't register instance with same name
self.dispatcher.register_calendar_type("DMY", type(dummy_cal))
with self.assertRaises(CalendarNameCollision):
self.dispatcher.register_calendar("DMY", dummy_cal)
def test_force_registration(self):
self.dispatcher.register_calendar("DMY", self.dummy_cal_type())
first_dummy = self.dispatcher.get_calendar("DMY")
# force-register a new instance
self.dispatcher.register_calendar("DMY", self.dummy_cal_type(), force=True)
second_dummy = self.dispatcher.get_calendar("DMY")
self.assertNotEqual(first_dummy, second_dummy)
class DefaultsTestCase(TestCase):
def test_default_calendars(self):
dispatcher = ExchangeCalendarDispatcher(
calendars={},
calendar_factories=_default_calendar_factories,
aliases=_default_calendar_aliases,
)
# These are ordered aliases first, so that we can deregister the
# canonical factories when we're done with them, and we'll be done with
# them after they've been used by all aliases and by canonical name.
for name in concat([_default_calendar_aliases, _default_calendar_factories]):
self.assertIsNotNone(
dispatcher.get_calendar(name), "get_calendar(%r) returned None" % name
)
dispatcher.deregister_calendar(name)
class DaysAtTimeTestCase(TestCase):
@parameterized.expand(
[
# NYSE standard day
(
"2016-07-19",
0,
time(9, 31),
pytz.timezone("America/New_York"),
"2016-07-19 9:31",
),
# CME standard day
(
"2016-07-19",
-1,
time(17, 1),
pytz.timezone("America/Chicago"),
"2016-07-18 17:01",
),
# CME day after DST start
(
"2004-04-05",
-1,
time(17, 1),
pytz.timezone("America/Chicago"),
"2004-04-04 17:01",
),
# ICE day after DST start
(
"1990-04-02",
-1,
time(19, 1),
pytz.timezone("America/Chicago"),
"1990-04-01 19:01",
),
]
)
def test_days_at_time(self, day, day_offset, time_offset, tz, expected):
days = pd.DatetimeIndex([pd.Timestamp(day, tz=tz)])
result = days_at_time(days, time_offset, tz, day_offset)[0]
expected = pd.Timestamp(expected, tz=tz).tz_convert(UTC)
self.assertEqual(result, expected)
class ExchangeCalendarTestBase(object):
# Override in subclasses.
answer_key_filename = None
calendar_class = None
# Affects test_start_bound. Should be set to earliest date for which
# calendar can be instantiated, or None if no start bound.
START_BOUND: pd.Timestamp | None = None
# Affects test_end_bound. Should be set to latest date for which
# calendar can be instantiated, or None if no end bound.
END_BOUND: pd.Timestamp | None = None
# Affects tests that care about the empty periods between sessions. Should
# be set to False for 24/7 calendars.
GAPS_BETWEEN_SESSIONS = True
# Affects tests that care about early closes. Should be set to False for
# calendars that don't have any early closes.
HAVE_EARLY_CLOSES = True
# Affects tests that care about late opens. Since most do not, defaulting
# to False.
HAVE_LATE_OPENS = False
# Affects test_for_breaks. True if one or more calendar sessions has a
# break.
HAVE_BREAKS = False
# Affects test_session_has_break.
SESSION_WITH_BREAK = None # None if no session has a break
SESSION_WITHOUT_BREAK = T("2011-06-15") # None if all sessions have breaks
# Affects test_sanity_check_session_lengths. Should be set to the largest
# number of hours that ever appear in a single session.
MAX_SESSION_HOURS = 0
# Affects test_minute_index_to_session_labels.
# Change these if the start/end dates of your test suite don't contain the
# defaults.
MINUTE_INDEX_TO_SESSION_LABELS_START = pd.Timestamp("2011-01-04", tz=UTC)
MINUTE_INDEX_TO_SESSION_LABELS_END = pd.Timestamp("2011-04-04", tz=UTC)
# Affects tests around daylight savings. If possible, should contain two
# dates that are not both in the same daylight savings regime.
DAYLIGHT_SAVINGS_DATES = ["2004-04-05", "2004-11-01"]
# Affects test_start_end. Change these if your calendar start/end
# dates between 2010-01-03 and 2010-01-10 don't match the defaults.
TEST_START_END_FIRST = pd.Timestamp("2010-01-03", tz=UTC)
TEST_START_END_LAST = pd.Timestamp("2010-01-10", tz=UTC)
TEST_START_END_EXPECTED_FIRST = pd.Timestamp("2010-01-04", tz=UTC)
TEST_START_END_EXPECTED_LAST = pd.Timestamp("2010-01-08", tz=UTC)
@staticmethod
def load_answer_key(filename):
"""
Load a CSV from tests/resources/{filename}.csv
"""
fullpath = join(
dirname(abspath(__file__)),
"./resources",
filename + ".csv",
)
return read_csv(
fullpath,
index_col=0,
# NOTE: Merely passing parse_dates=True doesn't cause pandas to set
# the dtype correctly, and passing all reasonable inputs to the
# dtype kwarg cause read_csv to barf.
parse_dates=[0, 1, 2],
date_parser=lambda x: pd.Timestamp(x, tz=UTC),
)
@classmethod
def setup_class(cls):
cls.answers = cls.load_answer_key(cls.answer_key_filename)
cls.start_date = cls.answers.index[0]
cls.end_date = cls.answers.index[-1]
cls.calendar = cls.calendar_class(cls.start_date, cls.end_date)
cls.one_minute = pd.Timedelta(1, "T")
cls.one_hour = pd.Timedelta(1, "H")
cls.one_day = pd.Timedelta(1, "D")
cls.today = pd.Timestamp.now(tz="UTC").floor("D")
@classmethod
def teardown_class(cls):
cls.calendar = None
cls.answers = None
def test_bound_start(self):
if self.START_BOUND is not None:
cal = self.calendar_class(self.START_BOUND, self.today)
self.assertIsInstance(cal, ExchangeCalendar)
start = self.START_BOUND - pd.DateOffset(days=1)
with pytest.raises(ValueError, match=re.escape(f"{start}")):
self.calendar_class(start, self.today)
else:
# verify no bound imposed
cal = self.calendar_class(pd.Timestamp("1902-01-01", tz="UTC"), self.today)
self.assertIsInstance(cal, ExchangeCalendar)
def test_bound_end(self):
if self.END_BOUND is not None:
cal = self.calendar_class(self.today, self.END_BOUND)
self.assertIsInstance(cal, ExchangeCalendar)
end = self.END_BOUND + pd.DateOffset(days=1)
with pytest.raises(ValueError, match=re.escape(f"{end}")):
self.calendar_class(self.today, end)
else:
# verify no bound imposed
cal = self.calendar_class(self.today, pd.Timestamp("2050-01-01", tz="UTC"))
self.assertIsInstance(cal, ExchangeCalendar)
def test_sanity_check_session_lengths(self):
# make sure that no session is longer than self.MAX_SESSION_HOURS hours
for session in self.calendar.all_sessions:
o, c = self.calendar.open_and_close_for_session(session)
delta = c - o
self.assertLessEqual(delta.seconds / 3600, self.MAX_SESSION_HOURS)
def test_calculated_against_csv(self):
tm.assert_index_equal(self.calendar.schedule.index, self.answers.index)
def test_adhoc_holidays_specification(self):
"""adhoc holidays should be tz-naive (#33, #39)."""
dti = pd.DatetimeIndex(self.calendar.adhoc_holidays)
assert dti.tz is None
def test_is_open_on_minute(self):
one_minute = pd.Timedelta(minutes=1)
m = self.calendar.is_open_on_minute
for market_minute in self.answers.market_open[1:]:
market_minute_utc = market_minute
# The exchange should be classified as open on its first minute
self.assertTrue(m(market_minute_utc, _parse=False))
if self.GAPS_BETWEEN_SESSIONS:
# Decrement minute by one, to minute where the market was not
# open
pre_market = market_minute_utc - one_minute
self.assertFalse(m(pre_market, _parse=False))
for market_minute in self.answers.market_close[:-1]:
close_minute_utc = market_minute
# should be open on its last minute
self.assertTrue(m(close_minute_utc, _parse=False))
if self.GAPS_BETWEEN_SESSIONS:
# increment minute by one minute, should be closed
post_market = close_minute_utc + one_minute
self.assertFalse(m(post_market, _parse=False))
def _verify_minute(
self,
calendar,
minute,
next_open_answer,
prev_open_answer,
next_close_answer,
prev_close_answer,
):
next_open = calendar.next_open(minute, _parse=False)
self.assertEqual(next_open, next_open_answer)
prev_open = self.calendar.previous_open(minute, _parse=False)
self.assertEqual(prev_open, prev_open_answer)
next_close = self.calendar.next_close(minute, _parse=False)
self.assertEqual(next_close, next_close_answer)
prev_close = self.calendar.previous_close(minute, _parse=False)
self.assertEqual(prev_close, prev_close_answer)
def test_next_prev_open_close(self):
# for each session, check:
# - the minute before the open (if gaps exist between sessions)
# - the first minute of the session
# - the second minute of the session
# - the minute before the close
# - the last minute of the session
# - the first minute after the close (if gaps exist between sessions)
opens = self.answers.market_open.iloc[1:-2]
closes = self.answers.market_close.iloc[1:-2]
previous_opens = self.answers.market_open.iloc[:-1]
previous_closes = self.answers.market_close.iloc[:-1]
next_opens = self.answers.market_open.iloc[2:]
next_closes = self.answers.market_close.iloc[2:]
for (
open_minute,
close_minute,
previous_open,
previous_close,
next_open,
next_close,
) in zip(
opens, closes, previous_opens, previous_closes, next_opens, next_closes
):
minute_before_open = open_minute - self.one_minute
# minute before open
if self.GAPS_BETWEEN_SESSIONS:
self._verify_minute(
self.calendar,
minute_before_open,
open_minute,
previous_open,
close_minute,
previous_close,
)
# open minute
self._verify_minute(
self.calendar,
open_minute,
next_open,
previous_open,
close_minute,
previous_close,
)
# second minute of session
self._verify_minute(
self.calendar,
open_minute + self.one_minute,
next_open,
open_minute,
close_minute,
previous_close,
)
# minute before the close
self._verify_minute(
self.calendar,
close_minute - self.one_minute,
next_open,
open_minute,
close_minute,
previous_close,
)
# the close
self._verify_minute(
self.calendar,
close_minute,
next_open,
open_minute,
next_close,
previous_close,
)
# minute after the close
if self.GAPS_BETWEEN_SESSIONS:
self._verify_minute(
self.calendar,
close_minute + self.one_minute,
next_open,
open_minute,
next_close,
close_minute,
)
def test_next_prev_minute(self):
all_minutes = self.calendar.all_minutes
# test 20,000 minutes because it takes too long to do the rest.
for idx, minute in enumerate(all_minutes[1:20000]):
self.assertEqual(
all_minutes[idx + 2], self.calendar.next_minute(minute, _parse=False)
)
self.assertEqual(
all_minutes[idx], self.calendar.previous_minute(minute, _parse=False)
)
# test a couple of non-market minutes
if self.GAPS_BETWEEN_SESSIONS:
for open_minute in self.answers.market_open[1:]:
hour_before_open = open_minute - self.one_hour
self.assertEqual(
open_minute,
self.calendar.next_minute(hour_before_open, _parse=False),
)
for close_minute in self.answers.market_close[1:]:
hour_after_close = close_minute + self.one_hour
self.assertEqual(
close_minute,
self.calendar.previous_minute(hour_after_close, _parse=False),
)
def test_date_to_session_label(self):
m = self.calendar.date_to_session_label
sessions = self.answers.index[:30] # first 30 sessions
# test for error if request session prior to first calendar session.
date = self.answers.index[0] - self.one_day
error_msg = (
"Cannot get a session label prior to the first calendar"
f" session ('{self.answers.index[0]}'). Consider passing"
" `direction` as 'next'."
)
with pytest.raises(ValueError, match=re.escape(error_msg)):
m(date, "previous", _parse=False)
# direction as "previous"
dates = pd.date_range(sessions[0], sessions[-1], freq="D")
last_session = None
for date in dates:
session_label = m(date, "previous", _parse=False)
if date in sessions:
assert session_label == date
last_session = session_label
else:
assert session_label == last_session
# direction as "next"
last_session = None
for date in dates.sort_values(ascending=False):
session_label = m(date, "next", _parse=False)
if date in sessions:
assert session_label == date
last_session = session_label
else:
assert session_label == last_session
# test for error if request session after last calendar session.
date = self.answers.index[-1] + self.one_day
error_msg = (
"Cannot get a session label later than the last calendar"
f" session ('{self.answers.index[-1]}'). Consider passing"
" `direction` as 'previous'."
)
with pytest.raises(ValueError, match=re.escape(error_msg)):
m(date, "next", _parse=False)
if self.GAPS_BETWEEN_SESSIONS:
not_sessions = dates[~dates.isin(sessions)][:5]
for not_session in not_sessions:
error_msg = (
f"`date` '{not_session}' does not represent a session. Consider"
" passing a `direction`."
)
with pytest.raises(ValueError, match=re.escape(error_msg)):
m(not_session, "none", _parse=False)
# test default behaviour
with pytest.raises(ValueError, match=re.escape(error_msg)):
m(not_session, _parse=False)
# non-valid direction (can only be thrown if gaps between sessions)
error_msg = (
"'not a direction' is not a valid `direction`. Valid `direction`"
' values are "next", "previous" and "none".'
)
with pytest.raises(ValueError, match=re.escape(error_msg)):
m(not_session, "not a direction", _parse=False)
def test_minute_to_session_label(self):
m = self.calendar.minute_to_session_label
# minute is prior to first session's open
minute_before_first_open = self.answers.iloc[0].market_open - self.one_minute
session_label = self.answers.index[0]
minutes_that_resolve_to_this_session = [
m(minute_before_first_open, _parse=False),
m(minute_before_first_open, direction="next", _parse=False),
]
unique_session_labels = set(minutes_that_resolve_to_this_session)
self.assertTrue(len(unique_session_labels) == 1)
self.assertIn(session_label, unique_session_labels)
with self.assertRaises(ValueError):
m(minute_before_first_open, direction="previous", _parse=False)
with self.assertRaises(ValueError):
m(minute_before_first_open, direction="none", _parse=False)
# minute is between first session's open and last session's close
for idx, (session_label, open_minute, close_minute, _, _) in enumerate(
self.answers.iloc[1:-2].itertuples(name=None)
):
hour_into_session = open_minute + self.one_hour
minute_before_session = open_minute - self.one_minute
minute_after_session = close_minute + self.one_minute
next_session_label = self.answers.index[idx + 2]
previous_session_label = self.answers.index[idx]
# verify that minutes inside a session resolve correctly
minutes_that_resolve_to_this_session = [
m(open_minute, _parse=False),
m(open_minute, direction="next", _parse=False),
m(open_minute, direction="previous", _parse=False),
m(open_minute, direction="none", _parse=False),
m(hour_into_session, _parse=False),
m(hour_into_session, direction="next", _parse=False),
m(hour_into_session, direction="previous", _parse=False),
m(hour_into_session, direction="none", _parse=False),
m(close_minute),
m(close_minute, direction="next", _parse=False),
m(close_minute, direction="previous", _parse=False),
m(close_minute, direction="none", _parse=False),
session_label,
]
if self.GAPS_BETWEEN_SESSIONS:
minutes_that_resolve_to_this_session.append(
m(minute_before_session, _parse=False)
)
minutes_that_resolve_to_this_session.append(
m(minute_before_session, direction="next", _parse=False)
)
minutes_that_resolve_to_this_session.append(
m(minute_after_session, direction="previous", _parse=False)
)
self.assertTrue(
all(
x == minutes_that_resolve_to_this_session[0]
for x in minutes_that_resolve_to_this_session
)
)
minutes_that_resolve_to_next_session = [
m(minute_after_session, _parse=False),
m(minute_after_session, direction="next", _parse=False),
next_session_label,
]
self.assertTrue(
all(
x == minutes_that_resolve_to_next_session[0]
for x in minutes_that_resolve_to_next_session
)
)
self.assertEqual(
m(minute_before_session, direction="previous", _parse=False),
previous_session_label,
)
if self.GAPS_BETWEEN_SESSIONS:
# Make sure we use the cache correctly
minutes_that_resolve_to_different_sessions = [
m(minute_after_session, direction="next", _parse=False),
m(minute_after_session, direction="previous", _parse=False),
m(minute_after_session, direction="next", _parse=False),
]
self.assertEqual(
minutes_that_resolve_to_different_sessions,
[next_session_label, session_label, next_session_label],
)
# make sure that exceptions are raised at the right time
with self.assertRaises(ValueError):
m(open_minute, "asdf", _parse=False)
if self.GAPS_BETWEEN_SESSIONS:
with self.assertRaises(ValueError):
m(minute_before_session, direction="none", _parse=False)
# minute is later than last session's close
minute_after_last_close = self.answers.iloc[-1].market_close + self.one_minute
session_label = self.answers.index[-1]
minute_that_resolves_to_session_label = m(
minute_after_last_close, direction="previous", _parse=False
)
self.assertEqual(session_label, minute_that_resolves_to_session_label)
with self.assertRaises(ValueError):
m(minute_after_last_close, _parse=False)
with self.assertRaises(ValueError):
m(minute_after_last_close, direction="next", _parse=False)
with self.assertRaises(ValueError):
m(minute_after_last_close, direction="none", _parse=False)
@parameterized.expand(
[
(1, 0),
(2, 0),
(2, 1),
]
)
def test_minute_index_to_session_labels(self, interval, offset):
minutes = self.calendar.minutes_for_sessions_in_range(
self.MINUTE_INDEX_TO_SESSION_LABELS_START,
self.MINUTE_INDEX_TO_SESSION_LABELS_END,
)
minutes = minutes[range(offset, len(minutes), interval)]
np.testing.assert_array_equal(
pd.DatetimeIndex(minutes.map(self.calendar.minute_to_session_label)),
self.calendar.minute_index_to_session_labels(minutes),
)
def test_next_prev_session(self):
session_labels = self.answers.index[1:-2]
max_idx = len(session_labels) - 1
# the very first session
first_session_label = self.answers.index[0]
with self.assertRaises(ValueError):
self.calendar.previous_session_label(first_session_label, _parse=False)
# all the sessions in the middle
for idx, session_label in enumerate(session_labels):
if idx < max_idx:
self.assertEqual(
self.calendar.next_session_label(session_label, _parse=False),
session_labels[idx + 1],
)
if idx > 0:
self.assertEqual(
self.calendar.previous_session_label(session_label, _parse=False),
session_labels[idx - 1],
)
# the very last session
last_session_label = self.answers.index[-1]
with self.assertRaises(ValueError):
self.calendar.next_session_label(last_session_label, _parse=False)
@staticmethod
def _find_full_session(calendar):
for session_label in calendar.schedule.index:
if session_label not in calendar.early_closes:
return session_label
return None
def test_minutes_for_period(self):
# full session
# find a session that isn't an early close. start from the first
# session, should be quick.
full_session_label = self._find_full_session(self.calendar)
if full_session_label is None:
raise ValueError("Cannot find a full session to test!")
minutes = self.calendar.minutes_for_session(full_session_label)
_open, _close = self.calendar.open_and_close_for_session(full_session_label)
_break_start, _break_end = self.calendar.break_start_and_end_for_session(
full_session_label
)
if not pd.isnull(_break_start):
constructed_minutes = np.concatenate(
[
pd.date_range(start=_open, end=_break_start, freq="min"),
pd.date_range(start=_break_end, end=_close, freq="min"),
]
)
else:
constructed_minutes = pd.date_range(start=_open, end=_close, freq="min")
np.testing.assert_array_equal(
minutes,
constructed_minutes,
)
# early close period
if self.HAVE_EARLY_CLOSES:
early_close_session_label = self.calendar.early_closes[0]
minutes_for_early_close = self.calendar.minutes_for_session(
early_close_session_label
)
_open, _close = self.calendar.open_and_close_for_session(
early_close_session_label
)
np.testing.assert_array_equal(
minutes_for_early_close,
pd.date_range(start=_open, end=_close, freq="min"),
)
# late open period
if self.HAVE_LATE_OPENS:
late_open_session_label = self.calendar.late_opens[0]
minutes_for_late_open = self.calendar.minutes_for_session(
late_open_session_label
)
_open, _close = self.calendar.open_and_close_for_session(
late_open_session_label
)
np.testing.assert_array_equal(
minutes_for_late_open,
pd.date_range(start=_open, end=_close, freq="min"),
)
def test_sessions_in_range(self):
# pick two sessions
session_count = len(self.calendar.schedule.index)
first_idx = session_count // 3
second_idx = 2 * first_idx
first_session_label = self.calendar.schedule.index[first_idx]
second_session_label = self.calendar.schedule.index[second_idx]
answer_key = self.calendar.schedule.index[first_idx : second_idx + 1]
rtrn = self.calendar.sessions_in_range(
first_session_label, second_session_label, _parse=False
)
np.testing.assert_array_equal(answer_key, rtrn)
def get_session_block(self):
"""
Get an "interesting" range of three sessions in a row. By default this
tries to find and return a (full session, early close session, full
session) block.
"""
if not self.HAVE_EARLY_CLOSES:
# If we don't have any early closes, just return a "random" chunk
# of three sessions.
return self.calendar.all_sessions[10:13]
shortened_session = self.calendar.early_closes[0]
shortened_session_idx = self.calendar.schedule.index.get_loc(shortened_session)
session_before = self.calendar.schedule.index[shortened_session_idx - 1]
session_after = self.calendar.schedule.index[shortened_session_idx + 1]
return [session_before, shortened_session, session_after]
def test_minutes_in_range(self):
sessions = self.get_session_block()
first_open, first_close = self.calendar.open_and_close_for_session(sessions[0])
minute_before_first_open = first_open - self.one_minute
middle_open, middle_close = self.calendar.open_and_close_for_session(
sessions[1]
)
last_open, last_close = self.calendar.open_and_close_for_session(sessions[-1])
minute_after_last_close = last_close + self.one_minute
# get all the minutes between first_open and last_close
minutes1 = self.calendar.minutes_in_range(first_open, last_close, _parse=False)
minutes2 = self.calendar.minutes_in_range(
minute_before_first_open, minute_after_last_close, _parse=False
)
if self.GAPS_BETWEEN_SESSIONS:
np.testing.assert_array_equal(minutes1, minutes2)
else:
# if no gaps, then minutes2 should have 2 extra minutes
np.testing.assert_array_equal(minutes1, minutes2[1:-1])
# manually construct the minutes
(
first_break_start,
first_break_end,
) = self.calendar.break_start_and_end_for_session(sessions[0])
(
middle_break_start,
middle_break_end,
) = self.calendar.break_start_and_end_for_session(sessions[1])
(
last_break_start,
last_break_end,
) = self.calendar.break_start_and_end_for_session(sessions[-1])
intervals = [
(first_open, first_break_start, first_break_end, first_close),
(middle_open, middle_break_start, middle_break_end, middle_close),
(last_open, last_break_start, last_break_end, last_close),
]
all_minutes = []
for _open, _break_start, _break_end, _close in intervals:
if pd.isnull(_break_start):
all_minutes.append(
pd.date_range(start=_open, end=_close, freq="min"),
)
else:
all_minutes.append(
pd.date_range(start=_open, end=_break_start, freq="min"),
)
all_minutes.append(
pd.date_range(start=_break_end, end=_close, freq="min"),
)
all_minutes = np.concatenate(all_minutes)
np.testing.assert_array_equal(all_minutes, minutes1)
def test_minutes_for_sessions_in_range(self):
sessions = self.get_session_block()
minutes = self.calendar.minutes_for_sessions_in_range(sessions[0], sessions[-1])
# do it manually
session0_minutes = self.calendar.minutes_for_session(sessions[0])
session1_minutes = self.calendar.minutes_for_session(sessions[1])
session2_minutes = self.calendar.minutes_for_session(sessions[2])
concatenated_minutes = np.concatenate(
[session0_minutes.values, session1_minutes.values, session2_minutes.values]
)
np.testing.assert_array_equal(concatenated_minutes, minutes.values)
def test_sessions_window(self):
sessions = self.get_session_block()
np.testing.assert_array_equal(
self.calendar.sessions_window(sessions[0], len(sessions) - 1, _parse=False),
self.calendar.sessions_in_range(sessions[0], sessions[-1], _parse=False),
)
np.testing.assert_array_equal(
self.calendar.sessions_window(
sessions[-1], -1 * (len(sessions) - 1), _parse=False
),
self.calendar.sessions_in_range(sessions[0], sessions[-1], _parse=False),
)
def test_session_distance(self):
sessions = self.get_session_block()
forward_distance = self.calendar.session_distance(
sessions[0],
sessions[-1],
_parse=False,
)
self.assertEqual(forward_distance, len(sessions))
backward_distance = self.calendar.session_distance(
sessions[-1],
sessions[0],
_parse=False,
)
self.assertEqual(backward_distance, -len(sessions))
one_day_distance = self.calendar.session_distance(
sessions[0],
sessions[0],
_parse=False,
)
self.assertEqual(one_day_distance, 1)
def test_open_and_close_for_session(self):
for session_label, open_answer, close_answer, _, _ in self.answers.itertuples(
name=None
):
found_open, found_close = self.calendar.open_and_close_for_session(
session_label, _parse=False
)
# Test that the methods for just session open and close produce the
# same values as the method for getting both.
alt_open = self.calendar.session_open(session_label, _parse=False)
self.assertEqual(alt_open, found_open)
alt_close = self.calendar.session_close(session_label, _parse=False)
self.assertEqual(alt_close, found_close)
self.assertEqual(open_answer, found_open)
self.assertEqual(close_answer, found_close)
def test_session_opens_in_range(self):
found_opens = self.calendar.session_opens_in_range(
self.answers.index[0],
self.answers.index[-1],
_parse=False,
)
found_opens.index.freq = None
tm.assert_series_equal(found_opens, self.answers["market_open"])
def test_session_closes_in_range(self):
found_closes = self.calendar.session_closes_in_range(
self.answers.index[0],
self.answers.index[-1],
_parse=False,
)
found_closes.index.freq = None
tm.assert_series_equal(found_closes, self.answers["market_close"])
def test_daylight_savings(self):
# 2004 daylight savings switches:
# Sunday 2004-04-04 and Sunday 2004-10-31
# make sure there's no weirdness around calculating the next day's
# session's open time.
m = dict(self.calendar.open_times)
m[pd.Timestamp.min] = m.pop(None)
open_times = pd.Series(m)
for date in self.DAYLIGHT_SAVINGS_DATES:
next_day = pd.Timestamp(date, tz=UTC)
open_date = next_day + Timedelta(days=self.calendar.open_offset)
the_open = self.calendar.schedule.loc[next_day].market_open
localized_open = the_open.tz_localize(UTC).tz_convert(self.calendar.tz)
self.assertEqual(
(open_date.year, open_date.month, open_date.day),
(localized_open.year, localized_open.month, localized_open.day),
)
open_ix = open_times.index.searchsorted(pd.Timestamp(date), side="right")
if open_ix == len(open_times):
open_ix -= 1
self.assertEqual(open_times.iloc[open_ix].hour, localized_open.hour)
self.assertEqual(open_times.iloc[open_ix].minute, localized_open.minute)
def test_start_end(self):
"""
Check ExchangeCalendar with defined start/end dates.
"""
calendar = self.calendar_class(
start=self.TEST_START_END_FIRST,
end=self.TEST_START_END_LAST,
)
self.assertEqual(
calendar.first_trading_session,
self.TEST_START_END_EXPECTED_FIRST,
)
self.assertEqual(
calendar.last_trading_session,
self.TEST_START_END_EXPECTED_LAST,
)
def test_has_breaks(self):
has_breaks = self.calendar.has_breaks()
self.assertEqual(has_breaks, self.HAVE_BREAKS)
def test_session_has_break(self):
if self.SESSION_WITHOUT_BREAK is not None:
self.assertFalse(
self.calendar.session_has_break(self.SESSION_WITHOUT_BREAK)
)
if self.SESSION_WITH_BREAK is not None:
self.assertTrue(self.calendar.session_has_break(self.SESSION_WITH_BREAK))
# TODO remove this class when all calendars migrated. No longer requried as
# `minute_index_to_session_labels` comprehensively tested under new suite.
class OpenDetectionTestCase(TestCase):
# This is an extra set of unit tests that were added during a rewrite of
# `minute_index_to_session_labels` to ensure that the existing
# calendar-generic test suite correctly covered edge cases around
# non-market minutes.
def test_detect_non_market_minutes(self):
cal = get_calendar("NYSE")
# NOTE: This test is here instead of being on the base class for all
# calendars because some of our calendars are 24/7, which means there
# aren't any non-market minutes to find.
day0 = cal.minutes_for_sessions_in_range(
pd.Timestamp("2013-07-03", tz=UTC),
pd.Timestamp("2013-07-03", tz=UTC),
)
for minute in day0:
self.assertTrue(cal.is_open_on_minute(minute))
day1 = cal.minutes_for_sessions_in_range(
pd.Timestamp("2013-07-05", tz=UTC),
pd.Timestamp("2013-07-05", tz=UTC),
)
for minute in day1:
self.assertTrue(cal.is_open_on_minute(minute))
def NYSE_timestamp(s):
return pd.Timestamp(s, tz="America/New_York").tz_convert(UTC)
non_market = [
# After close.
NYSE_timestamp("2013-07-03 16:01"),
# Holiday.
NYSE_timestamp("2013-07-04 10:00"),
# Before open.
NYSE_timestamp("2013-07-05 9:29"),
]
for minute in non_market:
self.assertFalse(cal.is_open_on_minute(minute), minute)
input_ = pd.to_datetime(
np.hstack([day0.values, minute.asm8, day1.values]),
utc=True,
)
with self.assertRaises(ValueError) as e:
cal.minute_index_to_session_labels(input_)
exc_str = str(e.exception)
self.assertIn("First Bad Minute: {}".format(minute), exc_str)
# TODO remove this class when all calendars migrated. No longer requried as
# this case is handled by new test base internally.
class NoDSTExchangeCalendarTestBase(ExchangeCalendarTestBase):
def test_daylight_savings(self):
"""
Several countries in Africa / Asia do not observe DST
so we need to skip over this test for those markets
"""
pass
def get_csv(name: str) -> pd.DataFrame:
"""Get csv file as DataFrame for given calendar `name`."""
filename = name.replace("/", "-").lower() + ".csv"
path = pathlib.Path(__file__).parent.joinpath("resources", filename)
df = pd.read_csv(
path,
index_col=0,
parse_dates=[0, 1, 2, 3, 4],
infer_datetime_format=True,
)
df.index = df.index.tz_localize("UTC")
for col in df:
df[col] = df[col].dt.tz_localize("UTC")
return df
class Answers:
"""Inputs and expected output for testing a given calendar and side.
Inputs and expected outputs are provided by public instance methods and
properties. These either read directly from the corresponding .csv file
or are evaluated from the .csv file contents. NB Properites / methods
MUST NOT make evaluations by way of repeating the code of the
ExchangeCalendar method they are intended to test!
Parameters
----------
calendar_name
Canonical name of calendar for which require answer info. For
example, 'XNYS'.
side {'both', 'left', 'right', 'neither'}
Side of sessions to treat as trading minutes.
"""
ONE_MIN = pd.Timedelta(1, "T")
TWO_MIN = pd.Timedelta(2, "T")
ONE_DAY = pd.Timedelta(1, "D")
LEFT_SIDES = ["left", "both"]
RIGHT_SIDES = ["right", "both"]
def __init__(
self,
calendar_name: str,
side: str,
):
self._name = calendar_name.upper()
self._side = side
# --- Exposed constructor arguments ---
@property
def name(self) -> str:
"""Name of corresponding calendar."""
return self._name
@property
def side(self) -> str:
"""Side of calendar for which answers valid."""
return self._side
# --- Properties read (indirectly) from csv file ---
@functools.lru_cache(maxsize=4)
def _answers(self) -> pd.DataFrame:
return get_csv(self.name)
@property
def answers(self) -> pd.DataFrame:
"""Answers as correspoding csv."""
return self._answers()
@property
def sessions(self) -> pd.DatetimeIndex:
"""Session labels."""
return self.answers.index
@property
def opens(self) -> pd.Series:
"""Market open time for each session."""
return self.answers.market_open
@property
def closes(self) -> pd.Series:
"""Market close time for each session."""
return self.answers.market_close
@property
def break_starts(self) -> pd.Series:
"""Break start time for each session."""
return self.answers.break_start
@property
def break_ends(self) -> pd.Series:
"""Break end time for each session."""
return self.answers.break_end
# --- get and helper methods ---
def get_next_session(self, session: pd.Timestamp) -> pd.Timestamp:
"""Get session that immediately follows `session`."""
assert (
session != self.last_session
), "Cannot get session later than last answers' session."
idx = self.sessions.get_loc(session) + 1
return self.sessions[idx]
def session_has_break(self, session: pd.Timestamp) -> bool:
"""Query if `session` has a break."""
return session in self.sessions_with_break
@staticmethod
def get_sessions_sample(sessions: pd.DatetimeIndex):
"""Return sample of given `sessions`.
Sample includes:
All sessions within first two years of `sessions`.
All sessions within last two years of `sessions`.
All sessions falling:
within first 3 days of any month.
from 28th of any month.
from 14th through 16th of any month.
"""
if sessions.empty:
return sessions
mask = (
(sessions < sessions[0] + pd.DateOffset(years=2))
| (sessions > sessions[-1] - pd.DateOffset(years=2))
| (sessions.day <= 3)
| (sessions.day >= 28)
| (14 <= sessions.day) & (sessions.day <= 16)
)
return sessions[mask]
def get_sessions_minutes(
self, start: pd.Timestamp, end: pd.Timestamp | int = 1
) -> pd.DatetimeIndex:
"""Get trading minutes for 1 or more consecutive sessions.
Parameters
----------
start
Session from which to get trading minutes.
end
Session through which to get trading mintues. Can be passed as:
pd.Timestamp: return will include trading minutes for `end`
session.
int: where int represents number of consecutive sessions
inclusive of `start`, for which require trading
minutes. Default is 1, such that by default will return
trading minutes for only `start` session.
"""
idx = self.sessions.get_loc(start)
stop = idx + end if isinstance(end, int) else self.sessions.get_loc(end) + 1
indexer = slice(idx, stop)
dtis = []
for first, last, last_am, first_pm in zip(
self.first_minutes[indexer],
self.last_minutes[indexer],
self.last_am_minutes[indexer],
self.first_pm_minutes[indexer],
):
if pd.isna(last_am):
dtis.append(pd.date_range(first, last, freq="T"))
else:
dtis.append(pd.date_range(first, last_am, freq="T"))
dtis.append(pd.date_range(first_pm, last, freq="T"))
return dtis[0].union_many(dtis[1:])
# --- Evaluated general calendar properties ---
@functools.lru_cache(maxsize=4)
def _has_a_session_with_break(self) -> pd.DatetimeIndex:
return self.break_starts.notna().any()
@property
def has_a_session_with_break(self) -> bool:
"""Does any session of answers have a break."""
return self._has_a_session_with_break()
@property
def has_a_session_without_break(self) -> bool:
"""Does any session of answers not have a break."""
return self.break_starts.isna().any()
# --- Evaluated properties for first and last sessions ---
@property
def first_session(self) -> pd.Timestamp:
"""First session covered by answers."""
return self.sessions[0]
@property
def last_session(self) -> pd.Timestamp:
"""Last session covered by answers."""
return self.sessions[-1]
@property
def sessions_range(self) -> tuple[pd.Timestamp, pd.Timestamp]:
"""First and last sessions covered by answers."""
return self.first_session, self.last_session
@property
def first_session_open(self) -> pd.Timestamp:
"""Open time of first session covered by answers."""
return self.opens[0]
@property
def last_session_close(self) -> pd.Timestamp:
"""Close time of last session covered by answers."""
return self.closes[-1]
@property
def first_trading_minute(self) -> pd.Timestamp:
open_ = self.first_session_open
return open_ if self.side in self.LEFT_SIDES else open_ + self.ONE_MIN
@property
def last_trading_minute(self) -> pd.Timestamp:
close = self.last_session_close
return close if self.side in self.RIGHT_SIDES else close - self.ONE_MIN
@property
def trading_minutes_range(self) -> tuple[pd.Timestamp, pd.Timestamp]:
"""First and last trading minutes covered by answers."""
return self.first_trading_minute, self.last_trading_minute
# --- out-of-bounds properties ---
@property
def minute_too_early(self) -> pd.Timestamp:
"""Minute earlier than first trading minute."""
return self.first_trading_minute - self.ONE_MIN
@property
def minute_too_late(self) -> pd.Timestamp:
"""Minute later than last trading minute."""
return self.last_trading_minute + self.ONE_MIN
@property
def session_too_early(self) -> pd.Timestamp:
"""Date earlier than first session."""
return self.first_session - self.ONE_DAY
@property
def session_too_late(self) -> pd.Timestamp:
"""Date later than last session."""
return self.last_session + self.ONE_DAY
# --- Evaluated properties covering every session. ---
@functools.lru_cache(maxsize=4)
def _first_minutes(self) -> pd.Series:
if self.side in self.LEFT_SIDES:
minutes = self.opens.copy()
else:
minutes = self.opens + self.ONE_MIN
minutes.name = "first_minutes"
return minutes
@property
def first_minutes(self) -> pd.Series:
"""First trading minute of each session (UTC)."""
return self._first_minutes()
@property
def first_minutes_plus_one(self) -> pd.Series:
"""First trading minute of each session plus one minute."""
return self.first_minutes + self.ONE_MIN
@property
def first_minutes_less_one(self) -> pd.Series:
"""First trading minute of each session less one minute."""
return self.first_minutes - self.ONE_MIN
@functools.lru_cache(maxsize=4)
def _last_minutes(self) -> pd.Series:
if self.side in self.RIGHT_SIDES:
minutes = self.closes.copy()
else:
minutes = self.closes - self.ONE_MIN
minutes.name = "last_minutes"
return minutes
@property
def last_minutes(self) -> pd.Series:
"""Last trading minute of each session."""
return self._last_minutes()
@property
def last_minutes_plus_one(self) -> pd.Series:
"""Last trading minute of each session plus one minute."""
return self.last_minutes + self.ONE_MIN
@property
def last_minutes_less_one(self) -> pd.Series:
"""Last trading minute of each session less one minute."""
return self.last_minutes - self.ONE_MIN
@functools.lru_cache(maxsize=4)
def _last_am_minutes(self) -> pd.Series:
if self.side in self.RIGHT_SIDES:
minutes = self.break_starts.copy()
else:
minutes = self.break_starts - self.ONE_MIN
minutes.name = "last_am_minutes"
return minutes
@property
def last_am_minutes(self) -> pd.Series:
"""Last pre-break trading minute of each session.
NaT if session does not have a break.
"""
return self._last_am_minutes()
@property
def last_am_minutes_plus_one(self) -> pd.Series:
"""Last pre-break trading minute of each session plus one minute."""
return self.last_am_minutes + self.ONE_MIN
@property
def last_am_minutes_less_one(self) -> pd.Series:
"""Last pre-break trading minute of each session less one minute."""
return self.last_am_minutes - self.ONE_MIN
@functools.lru_cache(maxsize=4)
def _first_pm_minutes(self) -> pd.Series:
if self.side in self.LEFT_SIDES:
minutes = self.break_ends.copy()
else:
minutes = self.break_ends + self.ONE_MIN
minutes.name = "first_pm_minutes"
return minutes
@property
def first_pm_minutes(self) -> pd.Series:
"""First post-break trading minute of each session.
NaT if session does not have a break.
"""
return self._first_pm_minutes()
@property
def first_pm_minutes_plus_one(self) -> pd.Series:
"""First post-break trading minute of each session plus one minute."""
return self.first_pm_minutes + self.ONE_MIN
@property
def first_pm_minutes_less_one(self) -> pd.Series:
"""First post-break trading minute of each session less one minute."""
return self.first_pm_minutes - self.ONE_MIN
# --- Evaluated session sets and ranges that meet a specific condition ---
@property
def _mask_breaks(self) -> pd.Series:
return self.break_starts.notna()
@functools.lru_cache(maxsize=4)
def _sessions_with_break(self) -> pd.DatetimeIndex:
return self.sessions[self._mask_breaks]
@property
def sessions_with_break(self) -> pd.DatetimeIndex:
return self._sessions_with_break()
@functools.lru_cache(maxsize=4)
def _sessions_without_break(self) -> pd.DatetimeIndex:
return self.sessions[~self._mask_breaks]
@property
def sessions_without_break(self) -> pd.DatetimeIndex:
return self._sessions_without_break()
@property
def sessions_without_break_run(self) -> pd.DatetimeIndex:
"""Longest run of consecutive sessions without a break."""
s = self.break_starts.isna()
if s.empty:
return pd.DatetimeIndex([], tz="UTC")
trues_grouped = (~s).cumsum()[s]
group_sizes = trues_grouped.value_counts()
max_run_size = group_sizes.max()
max_run_group_id = group_sizes[group_sizes == max_run_size].index[0]
run_without_break = trues_grouped[trues_grouped == max_run_group_id].index
return run_without_break
@property
def sessions_without_break_range(self) -> tuple[pd.Timestamp, pd.Timestamp] | None:
"""Longest session range that does not include a session with a break.
Returns None if all sessions have a break.
"""
sessions = self.sessions_without_break_run
if sessions.empty:
return None
return sessions[0], sessions[-1]
@property
def _mask_sessions_without_gap_after(self) -> pd.Series:
if self.side == "neither":
# will always have gap after if neither open or close are trading
# minutes (assuming sessions cannot overlap)
return pd.Series(False, index=self.sessions)
elif self.side == "both":
# a trading minute cannot be a minute of more than one session.
assert not (self.closes == self.opens.shift(-1)).any()
# there will be no gap if next open is one minute after previous close
closes_plus_min = self.closes + pd.Timedelta(1, "T")
return self.opens.shift(-1) == closes_plus_min
else:
return self.opens.shift(-1) == self.closes
@property
def _mask_sessions_without_gap_before(self) -> pd.Series:
if self.side == "neither":
# will always have gap before if neither open or close are trading
# minutes (assuming sessions cannot overlap)
return pd.Series(False, index=self.sessions)
elif self.side == "both":
# a trading minute cannot be a minute of more than one session.
assert not (self.closes == self.opens.shift(-1)).any()
# there will be no gap if previous close is one minute before next open
opens_minus_one = self.opens - pd.Timedelta(1, "T")
return self.closes.shift(1) == opens_minus_one
else:
return self.closes.shift(1) == self.opens
@functools.lru_cache(maxsize=4)
def _sessions_without_gap_after(self) -> pd.DatetimeIndex:
mask = self._mask_sessions_without_gap_after
return self.sessions[mask][:-1]
@property
def sessions_without_gap_after(self) -> pd.DatetimeIndex:
"""Sessions not followed by a non-trading minute.
Rather, sessions immediately followed by first trading minute of
next session.
"""
return self._sessions_without_gap_after()
@functools.lru_cache(maxsize=4)
def _sessions_with_gap_after(self) -> pd.DatetimeIndex:
mask = self._mask_sessions_without_gap_after
return self.sessions[~mask][:-1]
@property
def sessions_with_gap_after(self) -> pd.DatetimeIndex:
"""Sessions followed by a non-trading minute."""
return self._sessions_with_gap_after()
@functools.lru_cache(maxsize=4)
def _sessions_without_gap_before(self) -> pd.DatetimeIndex:
mask = self._mask_sessions_without_gap_before
return self.sessions[mask][1:]
@property
def sessions_without_gap_before(self) -> pd.DatetimeIndex:
"""Sessions not preceeded by a non-trading minute.
Rather, sessions immediately preceeded by last trading minute of
previous session.
"""
return self._sessions_without_gap_before()
@functools.lru_cache(maxsize=4)
def _sessions_with_gap_before(self) -> pd.DatetimeIndex:
mask = self._mask_sessions_without_gap_before
return self.sessions[~mask][1:]
@property
def sessions_with_gap_before(self) -> pd.DatetimeIndex:
"""Sessions preceeded by a non-trading minute."""
return self._sessions_with_gap_before()
# times are changing...
@functools.lru_cache(maxsize=16)
def _get_sessions_with_times_different_to_next_session(
self,
column: str, # typing.Literal["opens", "closes", "break_starts", "break_ends"]
) -> list[pd.DatetimeIndex]:
"""For a given answers column, get session labels where time differs
from time of next session.
Where `column` is a break time ("break_starts" or "break_ends"), return
will not include sessions when next session has a different `has_break`
status. For example, if session_0 has a break and session_1 does not have
a break, or vice versa, then session_0 will not be included to return. For
sessions followed by a session with a different `has_break` status, see
`_get_sessions_with_has_break_different_to_next_session`.
Returns
-------
list of pd.Datetimeindex
[0] sessions with earlier next session
[1] sessions with later next session
"""
# column takes string to allow lru_cache (Series not hashable)
is_break_col = column[0] == "b"
column_ = getattr(self, column)
if is_break_col:
if column_.isna().all():
return [pd.DatetimeIndex([], tz="UTC")] * 4
column_ = column_.fillna(method="ffill").fillna(method="bfill")
diff = (column_.shift(-1) - column_)[:-1]
remainder = diff % pd.Timedelta(hours=24)
mask = remainder != pd.Timedelta(0)
sessions = self.sessions[:-1][mask]
next_session_earlier_mask = remainder[mask] > pd.Timedelta(hours=12)
next_session_earlier = sessions[next_session_earlier_mask]
next_session_later = sessions[~next_session_earlier_mask]
if is_break_col:
mask = next_session_earlier.isin(self.sessions_without_break)
next_session_earlier = next_session_earlier.drop(next_session_earlier[mask])
mask = next_session_later.isin(self.sessions_without_break)
next_session_later = next_session_later.drop(next_session_later[mask])
return [next_session_earlier, next_session_later]
@property
def _sessions_with_opens_different_to_next_session(
self,
) -> list[pd.DatetimeIndex]:
return self._get_sessions_with_times_different_to_next_session("opens")
@property
def _sessions_with_closes_different_to_next_session(
self,
) -> list[pd.DatetimeIndex]:
return self._get_sessions_with_times_different_to_next_session("closes")
@property
def _sessions_with_break_start_different_to_next_session(
self,
) -> list[pd.DatetimeIndex]:
return self._get_sessions_with_times_different_to_next_session("break_starts")
@property
def _sessions_with_break_end_different_to_next_session(
self,
) -> list[pd.DatetimeIndex]:
return self._get_sessions_with_times_different_to_next_session("break_ends")
@property
def sessions_next_open_earlier(self) -> pd.DatetimeIndex:
return self._sessions_with_opens_different_to_next_session[0]
@property
def sessions_next_open_later(self) -> pd.DatetimeIndex:
return self._sessions_with_opens_different_to_next_session[1]
@property
def sessions_next_open_different(self) -> pd.DatetimeIndex:
return self.sessions_next_open_earlier.union(self.sessions_next_open_later)
@property
def sessions_next_close_earlier(self) -> pd.DatetimeIndex:
return self._sessions_with_closes_different_to_next_session[0]
@property
def sessions_next_close_later(self) -> pd.DatetimeIndex:
return self._sessions_with_closes_different_to_next_session[1]
@property
def sessions_next_close_different(self) -> pd.DatetimeIndex:
return self.sessions_next_close_earlier.union(self.sessions_next_close_later)
@property
def sessions_next_break_start_earlier(self) -> pd.DatetimeIndex:
return self._sessions_with_break_start_different_to_next_session[0]
@property
def sessions_next_break_start_later(self) -> pd.DatetimeIndex:
return self._sessions_with_break_start_different_to_next_session[1]
@property
def sessions_next_break_start_different(self) -> pd.DatetimeIndex:
earlier = self.sessions_next_break_start_earlier
later = self.sessions_next_break_start_later
return earlier.union(later)
@property
def sessions_next_break_end_earlier(self) -> pd.DatetimeIndex:
return self._sessions_with_break_end_different_to_next_session[0]
@property
def sessions_next_break_end_later(self) -> pd.DatetimeIndex:
return self._sessions_with_break_end_different_to_next_session[1]
@property
def sessions_next_break_end_different(self) -> pd.DatetimeIndex:
earlier = self.sessions_next_break_end_earlier
later = self.sessions_next_break_end_later
return earlier.union(later)
@functools.lru_cache(maxsize=4)
def _get_sessions_with_has_break_different_to_next_session(
self,
) -> tuple[pd.DatetimeIndex, pd.DatetimeIndex]:
"""Get sessions with 'has_break' different to next session.
Returns
-------
tuple[pd.DatetimeIndex, pd.DatetimeIndex]
[0] Sessions that have a break and are immediately followed by
a session which does not have a break.
[1] Sessions that do not have a break and are immediately
followed by a session which does have a break.
"""
mask = (self.break_starts.notna() & self.break_starts.shift(-1).isna())[:-1]
sessions_with_break_next_session_without_break = self.sessions[:-1][mask]
mask = (self.break_starts.isna() & self.break_starts.shift(-1).notna())[:-1]
sessions_without_break_next_session_with_break = self.sessions[:-1][mask]
return (
sessions_with_break_next_session_without_break,
sessions_without_break_next_session_with_break,
)
@property
def sessions_with_break_next_session_without_break(self) -> pd.DatetimeIndex:
return self._get_sessions_with_has_break_different_to_next_session()[0]
@property
def sessions_without_break_next_session_with_break(self) -> pd.DatetimeIndex:
return self._get_sessions_with_has_break_different_to_next_session()[1]
@functools.lru_cache(maxsize=4)
def _sessions_next_time_different(self) -> pd.DatetimeIndex:
return self.sessions_next_open_different.union_many(
[
self.sessions_next_close_different,
self.sessions_next_break_start_different,
self.sessions_next_break_end_different,
self.sessions_with_break_next_session_without_break,
self.sessions_without_break_next_session_with_break,
]
)
@property
def sessions_next_time_different(self) -> pd.DatetimeIndex:
"""Sessions where next session has a different time for any column.
Includes sessions where next session has a different `has_break`
status.
"""
return self._sessions_next_time_different()
# session blocks...
def _create_changing_times_session_block(
self, session: pd.Timestamp
) -> pd.DatetimeIndex:
"""Create block of sessions with changing times.
Given a `session` known to have at least one time (open, close,
break_start or break_end) different from the next session, returns
a block of consecutive sessions ending with the first session after
`session` that has the same times as the session that immediately
preceeds it (i.e. the last two sessions of the block will have the
same times), or the last calendar session.
"""
start_idx = self.sessions.get_loc(session)
end_idx = start_idx + 1
while self.sessions[end_idx] in self.sessions_next_time_different:
end_idx += 1
end_idx += 2 # +1 to include session with same times, +1 to serve as end index
return self.sessions[start_idx:end_idx]
def _get_normal_session_block(self) -> pd.DatetimeIndex:
"""Block of 3 sessions with unchanged timings."""
start_idx = len(self.sessions) // 3
end_idx = start_idx + 21
for i in range(start_idx, end_idx):
times_1 = self.answers.iloc[i].dt.time
times_2 = self.answers.iloc[i + 1].dt.time
times_3 = self.answers.iloc[i + 2].dt.time
one_and_two_equal = (times_1 == times_2) | (times_1.isna() & times_2.isna())
one_and_three_equal = (times_1 == times_3) | (
times_1.isna() & times_3.isna()
)
if (one_and_two_equal & one_and_three_equal).all():
break
assert i < (end_idx - 1), "Unable to evaluate a normal session block!"
return self.sessions[i : i + 3]
def _get_session_block(
self, from_session_of: pd.DatetimeIndex, to_session_of: pd.DatetimeIndex
) -> pd.DatetimeIndex:
"""Get session block with bounds defined by sessions of given indexes.
Block will start with middle session of `from_session_of`.
Block will run to the nearest subsequent session of `to_session_of`
(or `self.final_session` if this comes first). Block will end with
the session that immedidately follows this session.
"""
i = len(from_session_of) // 2
start_session = from_session_of[i]
start_idx = self.sessions.get_loc(start_session)
end_idx = start_idx + 1
end_session = self.sessions[end_idx]
while end_session not in to_session_of and end_session != self.last_session:
end_idx += 1
end_session = self.sessions[end_idx]
return self.sessions[start_idx : end_idx + 2]
@functools.lru_cache(maxsize=4)
def _session_blocks(self) -> dict[str, pd.DatetimeIndex]:
blocks = {}
blocks["normal"] = self._get_normal_session_block()
blocks["first_three"] = self.sessions[:3]
blocks["last_three"] = self.sessions[-3:]
# blocks here include where:
# session 1 has at least one different time from session 0
# session 0 has a break and session 1 does not (and vice versa)
sessions_indexes = (
("next_open_earlier", self.sessions_next_open_earlier),
("next_open_later", self.sessions_next_open_later),
("next_close_earlier", self.sessions_next_close_earlier),
("next_close_later", self.sessions_next_close_later),
("next_break_start_earlier", self.sessions_next_break_start_earlier),
("next_break_start_later", self.sessions_next_break_start_later),
("next_break_end_earlier", self.sessions_next_break_end_earlier),
("next_break_end_later", self.sessions_next_break_end_later),
(
"with_break_to_without_break",
self.sessions_with_break_next_session_without_break,
),
(
"without_break_to_with_break",
self.sessions_without_break_next_session_with_break,
),
)
for name, index in sessions_indexes:
if index.empty:
blocks[name] = pd.DatetimeIndex([], tz="UTC")
else:
session = index[0]
blocks[name] = self._create_changing_times_session_block(session)
# blocks here move from session with gap to session without gap and vice versa
if (not self.sessions_with_gap_after.empty) and (
not self.sessions_without_gap_after.empty
):
without_gap_to_with_gap = self._get_session_block(
self.sessions_without_gap_after, self.sessions_with_gap_after
)
with_gap_to_without_gap = self._get_session_block(
self.sessions_with_gap_after, self.sessions_without_gap_after
)
else:
without_gap_to_with_gap = pd.DatetimeIndex([], tz="UTC")
with_gap_to_without_gap = pd.DatetimeIndex([], tz="UTC")
blocks["without_gap_to_with_gap"] = without_gap_to_with_gap
blocks["with_gap_to_without_gap"] = with_gap_to_without_gap
# blocks that adjoin or contain a non_session date
follows_non_session = pd.DatetimeIndex([], tz="UTC")
preceeds_non_session = pd.DatetimeIndex([], tz="UTC")
contains_non_session = pd.DatetimeIndex([], tz="UTC")
if len(self.non_sessions) > 1:
diff = self.non_sessions[1:] - self.non_sessions[:-1]
mask = diff != pd.Timedelta(
1, "D"
) # non_session dates followed by a session
valid_non_sessions = self.non_sessions[:-1][mask]
if len(valid_non_sessions) > 1:
slce = self.sessions.slice_indexer(
valid_non_sessions[0], valid_non_sessions[1]
)
sessions_between_non_sessions = self.sessions[slce]
block_length = min(2, len(sessions_between_non_sessions))
follows_non_session = sessions_between_non_sessions[:block_length]
preceeds_non_session = sessions_between_non_sessions[-block_length:]
# take session before and session after non-session
contains_non_session = self.sessions[slce.stop - 1 : slce.stop + 1]
blocks["follows_non_session"] = follows_non_session
blocks["preceeds_non_session"] = preceeds_non_session
blocks["contains_non_session"] = contains_non_session
return blocks
@property
def session_blocks(self) -> dict[str, pd.DatetimeIndex]:
"""Dictionary of session blocks of a particular behaviour.
A block comprises either a single session or multiple contiguous
sessions.
Keys:
"normal" - three sessions with unchanging timings.
"first_three" - answers' first three sessions.
"last_three" - answers's last three sessions.
"next_open_earlier" - session 1 open is earlier than session 0
open.
"next_open_later" - session 1 open is later than session 0
open.
"next_close_earlier" - session 1 close is earlier than session
0 close.
"next_close_later" - session 1 close is later than session 0
close.
"next_break_start_earlier" - session 1 break_start is earlier
than session 0 break_start.
"next_break_start_later" - session 1 break_start is later than
session 0 break_start.
"next_break_end_earlier" - session 1 break_end is earlier than
session 0 break_end.
"next_break_end_later" - session 1 break_end is later than
session 0 break_end.
"with_break_to_without_break" - session 0 has a break, session
1 does not have a break.
"without_break_to_with_break" - session 0 does not have a
break, session 1 does have a break.
"without_gap_to_with_gap" - session 0 is not followed by a
gap, session -2 is followed by a gap, session -1 is
preceeded by a gap.
"with_gap_to_without_gap" - session 0 is followed by a gap,
session -2 is not followed by a gap, session -1 is not
preceeded by a gap.
"follows_non_session" - one or two sessions where session 0
is preceeded by a date that is a non-session.
"follows_non_session" - one or two sessions where session -1
is followed by a date that is a non-session.
"contains_non_session" = two sessions with at least one
non-session date in between.
If no such session block exists for any key then value will take an
empty DatetimeIndex (UTC).
"""
return self._session_blocks()
def session_block_generator(self) -> abc.Iterator[tuple[str, pd.DatetimeIndex]]:
"""Generator of session blocks of a particular behaviour."""
for name, block in self.session_blocks.items():
if not block.empty:
yield (name, block)
@functools.lru_cache(maxsize=4)
def _session_block_minutes(self) -> dict[str, pd.DatetimeIndex]:
d = {}
for name, block in self.session_blocks.items():
if block.empty:
d[name] = pd.DatetimeIndex([], tz="UTC")
continue
d[name] = self.get_sessions_minutes(block[0], len(block))
return d
@property
def session_block_minutes(self) -> dict[str, pd.DatetimeIndex]:
"""Trading minutes for each `session_block`.
Key:
Session block name as documented to `session_blocks`.
Value:
Trading minutes of corresponding session block.
"""
return self._session_block_minutes()
@property
def sessions_sample(self) -> pd.DatetimeIndex:
"""Sample of normal and unusual sessions.
Sample comprises set of sessions of all `session_blocks` (see
`session_blocks` doc). In this way sample includes at least one
sample of every indentified unique circumstance.
"""
dtis = list(self.session_blocks.values())
return dtis[0].union_many(dtis[1:])
# non-sessions...
@functools.lru_cache(maxsize=4)
def _non_sessions(self) -> pd.DatetimeIndex:
all_dates = pd.date_range(
start=self.first_session, end=self.last_session, freq="D"
)
return all_dates.difference(self.sessions)
@property
def non_sessions(self) -> pd.DatetimeIndex:
"""Dates (UTC midnight) within answers range that are not sessions."""
return self._non_sessions()
@property
def sessions_range_defined_by_non_sessions(
self,
) -> tuple[tuple[pd.Timestamp, pd.Timestamp], pd.Datetimeindex] | None:
"""Range containing sessions although defined with non-sessions.
Returns
-------
tuple[tuple[pd.Timestamp, pd.Timestamp], pd.Datetimeindex]:
[0] tuple[pd.Timestamp, pd.Timestamp]:
[0] range start as non-session date.
[1] range end as non-session date.
[1] pd.DatetimeIndex:
Sessions in range.
"""
non_sessions = self.non_sessions
if len(non_sessions) <= 1:
return None
limit = len(self.non_sessions) - 2
i = 0
start, end = non_sessions[i], non_sessions[i + 1]
while (end - start) < pd.Timedelta(4, "D"):
i += 1
start, end = non_sessions[i], non_sessions[i + 1]
if i == limit:
# Unable to evaluate range from consecutive non-sessions
# that covers >= 3 sessions. Just go with max range...
start, end = non_sessions[0], non_sessions[-1]
slice_start, slice_end = self.sessions.searchsorted((start, end))
return (start, end), self.sessions[slice_start:slice_end]
@property
def non_sessions_run(self) -> pd.DatetimeIndex:
"""Longest run of non_sessions."""
ser = self.sessions.to_series()
diff = ser.shift(-1) - ser
max_diff = diff.max()
if max_diff == pd.Timedelta(1, "D"):
return pd.DatetimeIndex([])
session_before_run = diff[diff == max_diff].index[-1]
run = pd.date_range(
start=session_before_run + pd.Timedelta(1, "D"),
periods=(max_diff // pd.Timedelta(1, "D")) - 1,
freq="D",
)
assert run.isin(self.non_sessions).all()
assert run[0] > self.first_session
assert run[-1] < self.last_session
return run
@property
def non_sessions_range(self) -> tuple[pd.Timestamp, pd.Timestamp] | None:
"""Longest range covering a period without a session."""
non_sessions_run = self.non_sessions_run
if non_sessions_run.empty:
return None
else:
return self.non_sessions_run[0], self.non_sessions_run[-1]
# --- Evaluated sets of minutes ---
@functools.lru_cache(maxsize=4)
def _evaluate_trading_and_break_minutes(self) -> tuple[tuple, tuple]:
sessions = self.sessions_sample
first_mins = self.first_minutes[sessions]
first_mins_plus_one = first_mins + self.ONE_MIN
last_mins = self.last_minutes[sessions]
last_mins_less_one = last_mins - self.ONE_MIN
trading_mins = []
break_mins = []
for session, mins_ in zip(
sessions,
zip(first_mins, first_mins_plus_one, last_mins, last_mins_less_one),
):
trading_mins.append((mins_, session))
if self.has_a_session_with_break:
last_am_mins = self.last_am_minutes[sessions]
last_am_mins = last_am_mins[last_am_mins.notna()]
first_pm_mins = self.first_pm_minutes[last_am_mins.index]
last_am_mins_less_one = last_am_mins - self.ONE_MIN
last_am_mins_plus_one = last_am_mins + self.ONE_MIN
last_am_mins_plus_two = last_am_mins + self.TWO_MIN
first_pm_mins_plus_one = first_pm_mins + self.ONE_MIN
first_pm_mins_less_one = first_pm_mins - self.ONE_MIN
first_pm_mins_less_two = first_pm_mins - self.TWO_MIN
for session, mins_ in zip(
last_am_mins.index,
zip(
last_am_mins,
last_am_mins_less_one,
first_pm_mins,
first_pm_mins_plus_one,
),
):
trading_mins.append((mins_, session))
for session, mins_ in zip(
last_am_mins.index,
zip(
last_am_mins_plus_one,
last_am_mins_plus_two,
first_pm_mins_less_one,
first_pm_mins_less_two,
),
):
break_mins.append((mins_, session))
return (tuple(trading_mins), tuple(break_mins))
@property
def trading_minutes(self) -> tuple[tuple[tuple[pd.Timestamp], pd.Timestamp]]:
"""Edge trading minutes of `sessions_sample`.
Returns
-------
tuple of tuple[tuple[trading_minutes], session]
tuple[trading_minutes] includes:
first two trading minutes of a session.
last two trading minutes of a session.
If breaks:
last two trading minutes of session's am subsession.
first two trading minutes of session's pm subsession.
session
Session of trading_minutes
"""
return self._evaluate_trading_and_break_minutes()[0]
def trading_minutes_only(self) -> abc.Iterator[pd.Timestamp]:
"""Generator of trading minutes of `self.trading_minutes`."""
for mins, _ in self.trading_minutes:
for minute in mins:
yield minute
@property
def trading_minute(self) -> pd.Timestamp:
"""A single trading minute."""
return self.trading_minutes[0][0][0]
@property
def break_minutes(self) -> tuple[tuple[tuple[pd.Timestamp], pd.Timestamp]]:
"""Sample of break minutes of `sessions_sample`.
Returns
-------
tuple of tuple[tuple[break_minutes], session]
tuple[break_minutes]:
first two minutes of a break.
last two minutes of a break.
session
Session of break_minutes
"""
return self._evaluate_trading_and_break_minutes()[1]
def break_minutes_only(self) -> abc.Iterator[pd.Timestamp]:
"""Generator of break minutes of `self.break_minutes`."""
for mins, _ in self.break_minutes:
for minute in mins:
yield minute
@functools.lru_cache(maxsize=4)
def _non_trading_minutes(
self,
) -> tuple[tuple[tuple[pd.Timestamp], pd.Timestamp, pd.Timestamp]]:
non_trading_mins = []
sessions = self.sessions_sample
sessions = prev_sessions = sessions[sessions.isin(self.sessions_with_gap_after)]
next_sessions = self.sessions[self.sessions.get_indexer(sessions) + 1]
last_mins_plus_one = self.last_minutes[sessions] + self.ONE_MIN
first_mins_less_one = self.first_minutes[next_sessions] - self.ONE_MIN
for prev_session, next_session, mins_ in zip(
prev_sessions, next_sessions, zip(last_mins_plus_one, first_mins_less_one)
):
non_trading_mins.append((mins_, prev_session, next_session))
return tuple(non_trading_mins)
@property
def non_trading_minutes(
self,
) -> tuple[tuple[tuple[pd.Timestamp], pd.Timestamp, pd.Timestamp]]:
"""non_trading_minutes that edge `sessions_sample`.
NB. Does not include break minutes.
Returns
-------
tuple of tuple[tuple[non-trading minute], previous session, next session]
tuple[non-trading minute]
Two non-trading minutes.
[0] first non-trading minute to follow a session.
[1] last non-trading minute prior to the next session.
previous session
Session that preceeds non-trading minutes.
next session
Session that follows non-trading minutes.
See Also
--------
break_minutes
"""
return self._non_trading_minutes()
def non_trading_minutes_only(self) -> abc.Iterator[pd.Timestamp]:
"""Generator of non-trading minutes of `self.non_trading_minutes`."""
for mins, _, _ in self.non_trading_minutes:
for minute in mins:
yield minute
# --- method-specific inputs/outputs ---
def prev_next_open_close_minutes(
self,
) -> abc.Iterator[
tuple[
pd.Timestamp,
tuple[
pd.Timestamp | None,
pd.Timestamp | None,
pd.Timestamp | None,
pd.Timestamp | None,
],
]
]:
"""Generator of test parameters for prev/next_open/close methods.
Inputs include following minutes of each session:
open
one minute prior to open (not included for first session)
one minute after open
close
one minute before close
one minute after close (not included for last session)
NB Assumed that minutes prior to first open and after last close
will be handled via parse_timestamp.
Yields
------
2-tuple:
[0] Input a minute sd pd.Timestamp
[1] 4 tuple of expected output of corresponding method:
[0] previous_open as pd.Timestamp | None
[1] previous_close as pd.Timestamp | None
[2] next_open as pd.Timestamp | None
[3] next_close as pd.Timestamp | None
NB None indicates that corresponding method is expected to
raise a ValueError for this input.
"""
close_is_next_open_bv = self.closes == self.opens.shift(-1)
open_was_prev_close_bv = self.opens == self.closes.shift(+1)
close_is_next_open = close_is_next_open_bv[0]
# minutes for session 0
minute = self.opens[0]
yield (minute, (None, None, self.opens[1], self.closes[0]))
minute = minute + self.ONE_MIN
yield (minute, (self.opens[0], None, self.opens[1], self.closes[0]))
minute = self.closes[0]
next_open = self.opens[2] if close_is_next_open else self.opens[1]
yield (minute, (self.opens[0], None, next_open, self.closes[1]))
minute += self.ONE_MIN
prev_open = self.opens[1] if close_is_next_open else self.opens[0]
yield (minute, (prev_open, self.closes[0], next_open, self.closes[1]))
minute = self.closes[0] - self.ONE_MIN
yield (minute, (self.opens[0], None, self.opens[1], self.closes[0]))
# minutes for sessions over [1:-1] except for -1 close and 'close + one_min'
opens = self.opens[1:-1]
closes = self.closes[1:-1]
prev_opens = self.opens[:-2]
prev_closes = self.closes[:-2]
next_opens = self.opens[2:]
next_closes = self.closes[2:]
opens_after_next = self.opens[3:]
# add dummy row to equal lengths (won't be used)
_ = pd.Series(pd.Timestamp("2200-01-01", tz="UTC"))
opens_after_next = opens_after_next.append(_)
stop = closes[-1]
for (
open_,
close,
prev_open,
prev_close,
next_open,
next_close,
open_after_next,
close_is_next_open,
open_was_prev_close,
) in zip(
opens,
closes,
prev_opens,
prev_closes,
next_opens,
next_closes,
opens_after_next,
close_is_next_open_bv[1:-2],
open_was_prev_close_bv[1:-2],
):
if not open_was_prev_close:
# only include open minutes if not otherwise duplicating
# evaluations already made for prior close.
yield (open_, (prev_open, prev_close, next_open, close))
yield (open_ - self.ONE_MIN, (prev_open, prev_close, open_, close))
yield (open_ + self.ONE_MIN, (open_, prev_close, next_open, close))
yield (close - self.ONE_MIN, (open_, prev_close, next_open, close))
if close != stop:
next_open_ = open_after_next if close_is_next_open else next_open
yield (close, (open_, prev_close, next_open_, next_close))
open_ = next_open if close_is_next_open else open_
yield (close + self.ONE_MIN, (open_, close, next_open_, next_close))
# close and 'close + one_min' for session -2
minute = self.closes[-2]
next_open = None if close_is_next_open_bv[-2] else self.opens[-1]
yield (minute, (self.opens[-2], self.closes[-3], next_open, self.closes[-1]))
minute += self.ONE_MIN
prev_open = self.opens[-1] if close_is_next_open_bv[-2] else self.opens[-2]
yield (minute, (prev_open, self.closes[-2], next_open, self.closes[-1]))
# minutes for session -1
if not open_was_prev_close_bv[-1]:
open_ = self.opens[-1]
prev_open = self.opens[-2]
prev_close = self.closes[-2]
next_open = None
close = self.closes[-1]
yield (open_, (prev_open, prev_close, next_open, close))
yield (open_ - self.ONE_MIN, (prev_open, prev_close, open_, close))
yield (open_ + self.ONE_MIN, (open_, prev_close, next_open, close))
minute = self.closes[-1]
next_open = self.opens[2] if close_is_next_open_bv[-1] else self.opens[1]
yield (minute, (self.opens[-1], self.closes[-2], None, None))
minute -= self.ONE_MIN
yield (minute, (self.opens[-1], self.closes[-2], None, self.closes[-1]))
# dunder
def __repr__(self) -> str:
return f"<Answers: calendar {self.name}, side {self.side}>"
def no_parsing(f: typing.Callable):
"""Wrap a method under test so that it skips input parsing."""
return lambda *args, **kwargs: f(*args, _parse=False, **kwargs)
class ExchangeCalendarTestBaseNew:
"""Test base for an ExchangeCalendar.
Notes
-----
=== Fixtures ===
In accordance with the pytest framework, whilst methods are requried to
have `self` as their first argument, no method should use `self`.
All required inputs should come by way of fixtures received to the
test method's arguments.
Methods that are directly or indirectly dependent on the evaluation of
trading minutes should be tested against the parameterized
`all_calendars_with_answers` fixture. This fixture will execute the
test against multiple calendar instances, one for each viable `side`.
The following methods directly evaluate trading minutes:
all_minutes
_last_minute_nanos()
_last_am_minute_nanos()
_first_minute_nanos()
_first_pm_minute_nanos()
NB this list does not include methods that indirectly evaluate methods
by way of calling (directly or indirectly) one of the above methods.
Methods that are not dependent on the evaluation of trading minutes
should only be tested against only the `default_calendar_with_answers`
or `default_calendar` fixture.
Calendar instances provided by fixtures should be used exclusively to
call the method being tested. NO TEST INPUT OR EXPECTED OUTPUT SHOULD
BE EVALUATED BY WAY OF CALLING A CALENDAR METHOD. Rather, test
inputs and expected output should be taken directly, or evaluated from,
properties/methods of the corresponding Answers fixture.
Subclasses are required to override a limited number of fixtures and
may be required to override others. Refer to the block comments.
"""
# subclass must override the following fixtures
@pytest.fixture(scope="class")
def calendar_cls(self) -> abc.Iterator[typing.Type[ExchangeCalendar]]:
"""ExchangeCalendar class to be tested.
Examples:
XNYSExchangeCalendar
AlwaysOpenCalendar
"""
raise NotImplementedError("fixture must be implemented on subclass")
@pytest.fixture
def max_session_hours(self) -> abc.Iterator[int | float]:
"""Largest number of hours that can comprise a single session.
Examples:
8
6.5
"""
raise NotImplementedError("fixture must be implemented on subclass")
# if subclass has a 24h session then subclass must override this fixture.
# Define on subclass as is here with only difference being passing
# ["left", "right"] to decorator's 'params' arg (24h calendars cannot
# have a side defined as 'both' or 'neither'.).
@pytest.fixture(scope="class", params=["both", "left", "right", "neither"])
def all_calendars_with_answers(
self, request, calendars, answers
) -> abc.Iterator[tuple[ExchangeCalendar, Answers]]:
"""Parameterized calendars and answers for each side."""
yield (calendars[request.param], answers[request.param])
# subclass should override the following fixtures in the event that the
# default defined here does not apply.
@pytest.fixture
def start_bound(self) -> abc.Iterator[pd.Timestamp | None]:
"""Earliest date for which calendar can be instantiated, or None if
there is no start bound."""
yield None
@pytest.fixture
def end_bound(self) -> abc.Iterator[pd.Timestamp | None]:
"""Latest date for which calendar can be instantiated, or None if
there is no end bound."""
yield None
# Subclass can optionally override the following fixtures. By overriding
# a fixture the associated test will be executed with input as yielded
# by the fixture. Where fixtures are not overriden the associated tests
# will be skipped.
@pytest.fixture
def regular_holidays_sample(self) -> abc.Iterator[list[str]]:
"""Sample of known regular calendar holidays. Empty list if no holidays.
`test_regular_holidays_sample` will check that each date does not
represent a calendar session.
Example return:
["2020-12-25", "2021-01-01", ...]
"""
yield []
@pytest.fixture
def adhoc_holidays_sample(self) -> abc.Iterator[list[str]]:
"""Sample of adhoc calendar holidays. Empty list if no adhoc holidays.
`test_adhoc_holidays_sample` will check that each date does not
represent a calendar session.
Example return:
["2015-04-17", "2021-09-12", ...]
"""
yield []
@pytest.fixture
def non_holidays_sample(self) -> abc.Iterator[list[str]]:
"""Sample of known dates that are not holidays.
`test_non_holidays_sample` will check that each date represents a
calendar session.
Subclass should use this fixture if wishes to test edge cases, for
example where a session is an exception to a rule, or where session
preceeds/follows a holiday that is an exception to a rule.
Example return:
["2019-12-27", "2020-01-02", ...]
"""
yield []
@pytest.fixture
def late_opens_sample(self) -> abc.Iterator[list[str]]:
"""Sample of known calendar sessions with late opens.
`test_late_opens_sample` will check that each date represents a
session with a late open.
Example returns:
["2022-01-03", "2022-04-22", ...]
"""
yield []
@pytest.fixture
def early_closes_sample(self) -> abc.Iterator[list[str]]:
"""Sample of known calendar sessions with early closes.
`test_early_closes_sample` will check that each date represents a
session with an early close.
Example returns:
["2019-12-24", "2019-12-31", ...]
"""
yield []
@pytest.fixture
def early_closes_sample_time(self) -> abc.Iterator[pd.Timedelta | None]:
"""Local close time of sessions of `early_closes_sample` fixture.
`test_early_closes_sample_time` will check all sessions of
`early_closes_sample` have this close time.
Only override fixture if:
- `early_closes_sample` is overriden by subclass
- ALL sessions of `early_closes_sample` have the same local
close time (if sessions of `early_closes_sample` have
different local close times then the subclass should
instead check close times with a test defined on the
subclass).
Example returns:
pd.Timedelta(14, "H") # 14:00 local time
pd.Timedelta(hours=13, minutes=15) # 13:15 local time
"""
yield None
@pytest.fixture
def non_early_closes_sample(self) -> abc.Iterator[list[str]]:
"""Sample of known calendar sessions with normal close times.
`test_non_early_closes_sample` will check each date does not
represent a calendar session with an early close.
Subclass should use this fixture to test edge cases, for example
where an otherwise early close is an exception to a rule.
Example return:
["2022-12-23", "2022-12-30]
"""
yield []
@pytest.fixture
def non_early_closes_sample_time(self) -> abc.Iterator[pd.Timedelta | None]:
"""Local close time of sessions of `non_early_closes_sample` fixture.
`test_non_early_closes_sample_time` will check all sessions of
`non_early_closes_sample` have this close time.
Only override fixture if:
- `non_early_closes_sample` is overriden by subclass.
- ALL sessions of `non_early_closes_sample` have the same local
close time (if sessions of `non_early_closes_sample` have
different local close times then the subclass should
instead check close times with a test defined on the
subclass).
Example returns:
pd.Timedelta(17, "H") # 17:00 local time
pd.Timedelta(hours=16, minutes=30) # 16:30 local time
"""
yield None
# --- NO FIXTURE BELOW THIS LINE SHOULD BE OVERRIDEN ON A SUBCLASS ---
def test_testbase_integrity(self):
"""Ensure integrity of TestBase.
Raises error if a reserved fixture is overriden by the subclass.
"""
cls = self.__class__
for fixture in [
"test_testbase_integrity",
"name",
"has_24h_session",
"default_side",
"sides",
"answers",
"default_answers",
"calendars",
"default_calendar",
"calendars_with_answers",
"default_calendar_with_answers",
"one_minute",
"today",
"all_directions",
"valid_overrides",
"non_valid_overrides",
"daylight_savings_dates",
"late_opens",
"early_closes",
]:
if getattr(cls, fixture) != getattr(ExchangeCalendarTestBaseNew, fixture):
raise RuntimeError(f"fixture '{fixture}' should not be overriden!")
# Base class fixtures
@pytest.fixture(scope="class")
def name(self, calendar_cls) -> abc.Iterator[str]:
"""Calendar name."""
yield calendar_cls.name
@pytest.fixture(scope="class")
def has_24h_session(self, name) -> abc.Iterator[bool]:
df = get_csv(name)
yield (df.market_close == df.market_open.shift(-1)).any()
@pytest.fixture(scope="class")
def default_side(self, has_24h_session) -> abc.Iterator[str]:
"""Default calendar side."""
if has_24h_session:
yield "left"
else:
yield "both"
@pytest.fixture(scope="class")
def sides(self, has_24h_session) -> abc.Iterator[list[str]]:
"""All valid sides options for calendar."""
if has_24h_session:
yield ["left", "right"]
else:
yield ["both", "left", "right", "neither"]
# Calendars and answers
@pytest.fixture(scope="class")
def answers(self, name, sides) -> abc.Iterator[dict[str, Answers]]:
"""Dict of answers, key as side, value as corresoponding answers."""
yield {side: Answers(name, side) for side in sides}
@pytest.fixture(scope="class")
def default_answers(self, answers, default_side) -> abc.Iterator[Answers]:
yield answers[default_side]
@pytest.fixture(scope="class")
def calendars(
self, calendar_cls, default_answers, sides
) -> abc.Iterator[dict[str, ExchangeCalendar]]:
"""Dict of calendars, key as side, value as corresoponding calendar."""
start = default_answers.first_session
end = default_answers.last_session
yield {side: calendar_cls(start, end, side) for side in sides}
@pytest.fixture(scope="class")
def default_calendar(
self, calendars, default_side
) -> abc.Iterator[ExchangeCalendar]:
yield calendars[default_side]
@pytest.fixture(scope="class")
def calendars_with_answers(
self, calendars, answers, sides
) -> abc.Iterator[dict[str, tuple[ExchangeCalendar, Answers]]]:
"""Dict of calendars and answers, key as side."""
yield {side: (calendars[side], answers[side]) for side in sides}
@pytest.fixture(scope="class")
def default_calendar_with_answers(
self, calendars_with_answers, default_side
) -> abc.Iterator[tuple[ExchangeCalendar, Answers]]:
yield calendars_with_answers[default_side]
# General use fixtures.
@pytest.fixture(scope="class")
def one_minute(self) -> abc.Iterator[pd.Timedelta]:
yield pd.Timedelta(1, "T")
@pytest.fixture(scope="class")
def today(self) -> abc.Iterator[pd.Timedelta]:
yield pd.Timestamp.now(tz="UTC").floor("D")
@pytest.fixture(scope="class", params=["next", "previous", "none"])
def all_directions(self, request) -> abc.Iterator[str]:
"""Parameterised fixture of direction to go if minute is not a trading minute"""
yield request.param
@pytest.fixture(scope="class")
def valid_overrides(self) -> abc.Iterator[list[str]]:
"""Names of methods that can be overriden by a subclass."""
yield [
"name",
"bound_start",
"bound_end",
"_bound_start_error_msg",
"_bound_end_error_msg",
"default_start",
"default_end",
"tz",
"open_times",
"break_start_times",
"break_end_times",
"close_times",
"weekmask",
"open_offset",
"close_offset",
"regular_holidays",
"adhoc_holidays",
"special_opens",
"special_opens_adhoc",
"special_closes",
"special_closes_adhoc",
"special_weekmasks",
"special_offsets",
"special_offsets_adhoc",
]
@pytest.fixture(scope="class")
def non_valid_overrides(self, valid_overrides) -> abc.Iterator[list[str]]:
"""Names of methods that cannot be overriden by a subclass."""
yield [
name
for name in dir(ExchangeCalendar)
if name not in valid_overrides
and not name.startswith("__")
and not name == "_abc_impl"
]
@pytest.fixture(scope="class")
def daylight_savings_dates(
self, default_calendar
) -> abc.Iterator[list[pd.Timestamp]]:
"""All dates in a specific year that mark the first day of a new
time regime.
Yields empty list if timezone's UCT offset does not change.
Notes
-----
NB Any test that employs this fixture assumes the accuarcy of the
default calendar's `tz` property.
"""
cal = default_calendar
year = cal.last_session.year - 1
days = pd.date_range(str(year), str(year + 1), freq="D")
tzinfo = pytz.timezone(cal.tz.zone)
prev_offset = tzinfo.utcoffset(days[0])
dates = []
for day in days[1:]:
try:
offset = tzinfo.utcoffset(day)
except pytz.NonExistentTimeError:
offset = tzinfo.utcoffset(day + pd.Timedelta(1, "H"))
if offset != prev_offset:
dates.append(day)
if len(dates) == 2:
break
prev_offset = offset
yield dates
@pytest.fixture(scope="class")
def late_opens(
self, default_calendar_with_answers
) -> abc.Iterator[pd.DatetimeIndex]:
"""Calendar sessions with a late open.
Late opens evaluated as those that are later than the prevailing
open time as defined by `default_calendar.open_times`.
Notes
-----
NB Any test that employs this fixture ASSUMES the accuarcy of the
following calendar properties:
`open_times`
`tz`
"""
cal, ans = default_calendar_with_answers
d = dict(cal.open_times)
d[pd.Timestamp.min] = d.pop(None)
s = pd.Series(d).sort_index(ascending=False)
date_to = pd.Timestamp.max
dtis: list[pd.DatetimeIndex] = []
# For each period over which a distinct open time prevails...
for date_from, time_ in s.iteritems():
opens = ans.opens.tz_convert(None)[date_from:date_to] # index to tz-naive
sessions = opens.index
td = pd.Timedelta(hours=time_.hour, minutes=time_.minute)
# Evaluate session opens as if were all normal open time.
normal_opens = sessions + pd.Timedelta(cal.open_offset, "D") + td
normal_opens_utc = normal_opens.tz_localize(cal.tz).tz_convert("UTC")
# Append those sessions with opens (according to answers) later than
# what would be normal.
dtis.append(sessions[opens > normal_opens_utc])
if date_from != pd.Timestamp.min:
date_to = date_from - pd.Timedelta(1, "D")
late_opens = dtis[0].union_many(dtis[1:]).tz_localize("UTC")
yield late_opens
@pytest.fixture(scope="class")
def early_closes(
self, default_calendar_with_answers
) -> abc.Iterator[pd.DatetimeIndex]:
"""Calendar sessions with a late open.
Early closes evaluated as those that are earlier than the
prevailing close time as defined by `default_calendar.close_times`.
Notes
-----
NB Any test that employs this fixture ASSUMES the accuarcy of the
following calendar properties:
`close_times`
`tz`
"""
cal, ans = default_calendar_with_answers
d = dict(cal.close_times)
d[pd.Timestamp.min] = d.pop(None)
s = pd.Series(d).sort_index(ascending=False)
date_to = pd.Timestamp.max
dtis: list[pd.DatetimeIndex] = []
for date_from, time_ in s.iteritems():
closes = ans.closes.tz_convert(None)[date_from:date_to] # index to tz-naive
sessions = closes.index
td = pd.Timedelta(hours=time_.hour, minutes=time_.minute)
normal_closes = sessions + pd.Timedelta(cal.close_offset, "D") + td
normal_closes_utc = normal_closes.tz_localize(cal.tz).tz_convert("UTC")
dtis.append(sessions[closes < normal_closes_utc])
if date_from != pd.Timestamp.min:
date_to = date_from - pd.Timedelta(1, "D")
early_closes = dtis[0].union_many(dtis[1:]).tz_localize("UTC")
yield early_closes
# --- TESTS ---
# Tests for calendar definition and construction methods.
def test_base_integrity(self, calendar_cls, non_valid_overrides):
cls = calendar_cls
for name in non_valid_overrides:
assert getattr(cls, name) == getattr(ExchangeCalendar, name)
def test_calculated_against_csv(self, default_calendar_with_answers):
calendar, ans = default_calendar_with_answers
tm.assert_index_equal(calendar.schedule.index, ans.sessions)
def test_start_end(self, default_answers, calendar_cls):
ans = default_answers
sessions = ans.session_blocks["normal"]
start, end = sessions[0], sessions[-1]
cal = calendar_cls(start, end)
assert cal.first_session == start
assert cal.last_session == end
if len(ans.non_sessions) > 1:
# start and end as non-sessions
(start, end), sessions = ans.sessions_range_defined_by_non_sessions
cal = calendar_cls(start, end)
assert cal.first_session == sessions[0]
assert cal.last_session == sessions[-1]
def test_invalid_input(self, calendar_cls, sides, default_answers, name):
ans = default_answers
invalid_side = "both" if "both" not in sides else "invalid_side"
error_msg = f"`side` must be in {sides} although received as {invalid_side}."
with pytest.raises(ValueError, match=re.escape(error_msg)):
calendar_cls(side=invalid_side)
start = ans.sessions[1]
end_same_as_start = ans.sessions[1]
error_msg = (
"`start` must be earlier than `end` although `start` parsed as"
f" '{start}' and `end` as '{end_same_as_start}'."
)
with pytest.raises(ValueError, match=re.escape(error_msg)):
calendar_cls(start=start, end=end_same_as_start)
end_before_start = ans.sessions[0]
error_msg = (
"`start` must be earlier than `end` although `start` parsed as"
f" '{start}' and `end` as '{end_before_start}'."
)
with pytest.raises(ValueError, match=re.escape(error_msg)):
calendar_cls(start=start, end=end_before_start)
if len(ans.non_sessions) > 1:
start, end = ans.non_sessions_range
error_msg = (
f"The requested ExchangeCalendar, {name.upper()}, cannot be created as"
f" there would be no sessions between the requested `start` ('{start}')"
f" and `end` ('{end}') dates."
)
with pytest.raises(NoSessionsError, match=re.escape(error_msg)):
calendar_cls(start=start, end=end)
def test_bound_start(self, calendar_cls, start_bound, today):
if start_bound is not None:
cal = calendar_cls(start_bound, today)
assert isinstance(cal, ExchangeCalendar)
start = start_bound - pd.DateOffset(days=1)
with pytest.raises(ValueError, match=re.escape(f"{start}")):
calendar_cls(start, today)
else:
# verify no bound imposed
cal = calendar_cls(pd.Timestamp("1902-01-01", tz="UTC"), today)
assert isinstance(cal, ExchangeCalendar)
def test_bound_end(self, calendar_cls, end_bound, today):
if end_bound is not None:
cal = calendar_cls(today, end_bound)
assert isinstance(cal, ExchangeCalendar)
end = end_bound + pd.DateOffset(days=1)
with pytest.raises(ValueError, match=re.escape(f"{end}")):
calendar_cls(today, end)
else:
# verify no bound imposed
cal = calendar_cls(today, pd.Timestamp("2050-01-01", tz="UTC"))
assert isinstance(cal, ExchangeCalendar)
def test_sanity_check_session_lengths(self, default_calendar, max_session_hours):
cal = default_calendar
cal_max_secs = (cal.market_closes_nanos - cal.market_opens_nanos).max()
assert cal_max_secs / 3600000000000 <= max_session_hours
def test_adhoc_holidays_specification(self, default_calendar):
"""adhoc holidays should be tz-naive (#33, #39)."""
dti = pd.DatetimeIndex(default_calendar.adhoc_holidays)
assert dti.tz is None
def test_daylight_savings(self, default_calendar, daylight_savings_dates):
# make sure there's no weirdness around calculating the next day's
# session's open time.
if not daylight_savings_dates:
pytest.skip()
cal = default_calendar
d = dict(cal.open_times)
d[pd.Timestamp.min] = d.pop(None)
open_times = pd.Series(d)
for date in daylight_savings_dates:
# where `next day` is first session of new daylight savings regime
next_day = cal.date_to_session_label(T(date), "next")
open_date = next_day + Timedelta(days=cal.open_offset)
the_open = cal.schedule.loc[next_day].market_open
localized_open = the_open.tz_localize(UTC).tz_convert(cal.tz)
assert open_date.year == localized_open.year
assert open_date.month == localized_open.month
assert open_date.day == localized_open.day
open_ix = open_times.index.searchsorted(date, side="right")
if open_ix == len(open_times):
open_ix -= 1
open_time = open_times.iloc[open_ix]
assert open_time.hour == localized_open.hour
assert open_time.minute == localized_open.minute
# Tests for properties covering all sessions.
def test_all_sessions(self, default_calendar_with_answers):
cal, ans = default_calendar_with_answers
ans_sessions = ans.sessions
cal_sessions = cal.all_sessions
tm.assert_index_equal(ans_sessions, cal_sessions)
def test_opens_closes_break_starts_ends(self, default_calendar_with_answers):
"""Test `opens`, `closes, `break_starts` and `break_ends` properties."""
cal, ans = default_calendar_with_answers
for prop in (
"opens",
"closes",
"break_starts",
"break_ends",
):
ans_series = getattr(ans, prop).dt.tz_convert(None)
cal_series = getattr(cal, prop)
tm.assert_series_equal(ans_series, cal_series, check_freq=False)
def test_minutes_properties(self, all_calendars_with_answers):
"""Test minute properties.
Tests following calendar properties:
all_first_minutes
all_last_minutes
all_last_am_minutes
all_first_pm_minutes
"""
cal, ans = all_calendars_with_answers
for prop in (
"first_minutes",
"last_minutes",
"last_am_minutes",
"first_pm_minutes",
):
ans_minutes = getattr(ans, prop)
cal_minutes = getattr(cal, "all_" + prop)
tm.assert_series_equal(ans_minutes, cal_minutes, check_freq=False)
# Tests for properties covering all minutes.
def test_all_minutes(self, all_calendars_with_answers, one_minute):
"""Test trading minutes at sessions' bounds."""
calendar, ans = all_calendars_with_answers
side = ans.side
mins = calendar.all_minutes
assert isinstance(mins, pd.DatetimeIndex)
assert not mins.empty
mins_plus_1 = mins + one_minute
mins_less_1 = mins - one_minute
if side in ["left", "neither"]:
# Test that close and break_start not in mins,
# but are in mins_plus_1 (unless no gap after)
# do not test here for sessions with no gap after as for "left" these
# sessions' close IS a trading minute as it's the same as next session's
# open.
# NB For "neither" all sessions will have gap after.
closes = ans.closes[ans.sessions_with_gap_after]
# closes should not be in minutes
assert not mins.isin(closes).any()
# all closes should be in minutes plus 1
# for speed, use only subset of mins that are of interest
mins_plus_1_on_close = mins_plus_1[mins_plus_1.isin(closes)]
assert closes.isin(mins_plus_1_on_close).all()
# as noted above, if no gap after then close should be a trading minute
# as will be first minute of next session.
closes = ans.closes[ans.sessions_without_gap_after]
mins_on_close = mins[mins.isin(closes)]
assert closes.isin(mins_on_close).all()
if ans.has_a_session_with_break:
# break start should not be in minutes
assert not mins.isin(ans.break_starts).any()
# break start should be in minutes plus 1
break_starts = ans.break_starts[ans.sessions_with_break]
mins_plus_1_on_start = mins_plus_1[mins_plus_1.isin(break_starts)]
assert break_starts.isin(mins_plus_1_on_start).all()
if side in ["left", "both"]:
# Test that open and break_end are in mins,
# but not in mins_plus_1 (unless no gap before)
mins_on_open = mins[mins.isin(ans.opens)]
assert ans.opens.isin(mins_on_open).all()
opens = ans.opens[ans.sessions_with_gap_before]
assert not mins_plus_1.isin(opens).any()
opens = ans.opens[ans.sessions_without_gap_before]
mins_plus_1_on_open = mins_plus_1[mins_plus_1.isin(opens)]
assert opens.isin(mins_plus_1_on_open).all()
if ans.has_a_session_with_break:
break_ends = ans.break_ends[ans.sessions_with_break]
mins_on_end = mins[mins.isin(ans.break_ends)]
assert break_ends.isin(mins_on_end).all()
if side in ["right", "neither"]:
# Test that open and break_end are not in mins,
# but are in mins_less_1 (unless no gap before)
opens = ans.opens[ans.sessions_with_gap_before]
assert not mins.isin(opens).any()
mins_less_1_on_open = mins_less_1[mins_less_1.isin(opens)]
assert opens.isin(mins_less_1_on_open).all()
opens = ans.opens[ans.sessions_without_gap_before]
mins_on_open = mins[mins.isin(opens)]
assert opens.isin(mins_on_open).all()
if ans.has_a_session_with_break:
assert not mins.isin(ans.break_ends).any()
break_ends = ans.break_ends[ans.sessions_with_break]
mins_less_1_on_end = mins_less_1[mins_less_1.isin(break_ends)]
assert break_ends.isin(mins_less_1_on_end).all()
if side in ["right", "both"]:
# Test that close and break_start are in mins,
# but not in mins_less_1 (unless no gap after)
mins_on_close = mins[mins.isin(ans.closes)]
assert ans.closes.isin(mins_on_close).all()
closes = ans.closes[ans.sessions_with_gap_after]
assert not mins_less_1.isin(closes).any()
closes = ans.closes[ans.sessions_without_gap_after]
mins_less_1_on_close = mins_less_1[mins_less_1.isin(closes)]
assert closes.isin(mins_less_1_on_close).all()
if ans.has_a_session_with_break:
break_starts = ans.break_starts[ans.sessions_with_break]
mins_on_start = mins[mins.isin(ans.break_starts)]
assert break_starts.isin(mins_on_start).all()
# Tests for calendar properties.
def test_calendar_bounds_properties(self, all_calendars_with_answers):
"""Test calendar properties that define a calendar bound.
Tests following calendar properties:
first_session
last_session
first_session_open
last_session_close
first_trading_minute
last_trading_minute
"""
cal, ans = all_calendars_with_answers
assert ans.first_session == cal.first_session
assert ans.last_session == cal.last_session
assert ans.first_session_open.tz_convert(None) == cal.first_session_open
assert ans.last_session_close.tz_convert(None) == cal.last_session_close
assert ans.first_trading_minute == cal.first_trading_minute
assert ans.last_trading_minute == cal.last_trading_minute
def test_has_breaks(self, default_calendar_with_answers):
cal, ans = default_calendar_with_answers
f = no_parsing(cal.has_breaks)
has_a_break = ans.has_a_session_with_break
assert f() == has_a_break
if ans.has_a_session_without_break:
assert not f(*ans.sessions_without_break_range)
if has_a_break:
# i.e. mixed, some sessions have a break, some don't
block = ans.session_blocks["with_break_to_without_break"]
if not block.empty:
# guard against starting with no breaks, then an introduction
# of breaks to every session after a certain date
# (i.e. there would be no with_break_to_without_break)
assert f(block[0], block[-1])
block = ans.session_blocks["without_break_to_with_break"]
if not block.empty:
# ...guard against opposite case (e.g. XKRX)
assert f(block[0], block[-1])
else:
# in which case all sessions must have a break. Make sure...
assert cal.break_starts.notna().all()
def test_regular_holidays_sample(self, default_calendar, regular_holidays_sample):
"""Test that calendar-specific sample of holidays are not sessions."""
if not regular_holidays_sample:
pytest.skip()
for holiday in regular_holidays_sample:
assert T(holiday) not in default_calendar.all_sessions
def test_adhoc_holidays_sample(self, default_calendar, adhoc_holidays_sample):
"""Test that calendar-specific sample of holidays are not sessions."""
if not adhoc_holidays_sample:
pytest.skip()
for holiday in adhoc_holidays_sample:
assert T(holiday) not in default_calendar.all_sessions
def test_non_holidays_sample(self, default_calendar, non_holidays_sample):
"""Test that calendar-specific sample of non-holidays are sessions."""
if not non_holidays_sample:
pytest.skip()
for date in non_holidays_sample:
assert T(date) in default_calendar.all_sessions
# NOTE: As of Oct 21 no calendar tests late opens (indeed, believe that no
# calendar defines late opens). Test commented out to prevent skip tests littering
# output. REINSTATE TEST IF any calendar defines and test late opens.
# def test_late_opens_sample(self, default_calendar, late_opens_sample):
# """Test calendar-specific sample of sessions are included to late opens."""
# if not late_opens_sample:
# pytest.skip()
# for date in late_opens_sample:
# assert T(date) in default_calendar.late_opens
def test_early_closes_sample(self, default_calendar, early_closes_sample):
"""Test calendar-specific sample of sessions are included to early closes."""
if not early_closes_sample:
pytest.skip()
for date in early_closes_sample:
assert T(date) in default_calendar.early_closes
def test_early_closes_sample_time(
self, default_calendar, early_closes_sample, early_closes_sample_time
):
"""Test close time of calendar-specific sample of early closing sessions.
Notes
-----
TEST RELIES ON ACCURACY OF CALENDAR PROPERTIES `closes`, `tz` and
`close_offset`.
"""
if early_closes_sample_time is None:
pytest.skip()
cal, tz = default_calendar, default_calendar.tz
offset = pd.Timedelta(cal.close_offset, "D") + early_closes_sample_time
for date in early_closes_sample:
early_close = cal.closes[date].tz_localize(UTC).tz_convert(tz)
expected = pd.Timestamp(date, tz=tz) + offset
assert early_close == expected
def test_non_early_closes_sample(self, default_calendar, non_early_closes_sample):
"""Test calendar-specific sample of sessions are not early closes."""
if not non_early_closes_sample:
pytest.skip()
for date in non_early_closes_sample:
assert T(date) not in default_calendar.early_closes
def test_non_early_closes_sample_time(
self, default_calendar, non_early_closes_sample, non_early_closes_sample_time
):
"""Test close time of calendar-specific sample of sessions with normal closes.
Notes
-----
TEST RELIES ON ACCURACY OF CALENDAR PROPERTIES `closes`, `tz` and
`close_offset`.
"""
if non_early_closes_sample_time is None:
pytest.skip()
cal, tz = default_calendar, default_calendar.tz
offset = pd.Timedelta(cal.close_offset, "D") + non_early_closes_sample_time
for date in non_early_closes_sample:
close = cal.closes[date].tz_localize(UTC).tz_convert(tz)
expected_close = pd.Timestamp(date, tz=tz) + offset
assert close == expected_close
def test_late_opens(self, default_calendar, late_opens):
"""Test late opens.
Notes
-----
TEST RELIES ON ACCURACY OF CALENDAR PROPERTIES `open_times` and
`tz`. See `late_opens` fixture.
"""
tm.assert_index_equal(late_opens, default_calendar.late_opens)
def test_early_closes(self, default_calendar, early_closes):
"""Test early closes.
Notes
-----
TEST RELIES ON ACCURACY OF CALENDAR PROPERTIES `close_times` and
`tz`. See `early_closes` fixture.
"""
tm.assert_index_equal(early_closes, default_calendar.early_closes)
# Tests for methods that interrogate a given session.
def test_session_open_close_break_start_end(self, default_calendar_with_answers):
"""Test methods that get session open, close, break_start, break_end.
Tests following calendar methods:
session_open
session_close
open_and_close_for_session
session_break_start
session_break_end
break_start_and_end_for_session
"""
# considered sufficient to limit test to sessions of session blocks.
cal, ans = default_calendar_with_answers
for _, block in ans.session_block_generator():
for session in block:
ans_open = ans.opens[session]
ans_close = ans.closes[session]
assert cal.session_open(session, _parse=False) == ans_open
assert cal.session_close(session, _parse=False) == ans_close
assert cal.open_and_close_for_session(session, _parse=False) == (
ans_open,
ans_close,
)
break_start = cal.session_break_start(session, _parse=False)
break_end = cal.session_break_end(session, _parse=False)
break_start_and_end = cal.break_start_and_end_for_session(
session, _parse=False
)
ans_break_start = ans.break_starts[session]
ans_break_end = ans.break_ends[session]
if pd.isna(ans_break_start):
assert pd.isna(break_start) and pd.isna(break_end)
assert pd.isna(break_start_and_end[0])
assert pd.isna(break_start_and_end[1])
else:
assert break_start == ans_break_start
assert break_end == ans_break_end
assert break_start_and_end[0] == ans_break_start
assert break_start_and_end[1] == ans_break_end
def test_session_minute_methods(self, all_calendars_with_answers):
"""Test methods that get a minute bound of a session or subsession.
Tests following calendar methods:
session_first_minute
session_last_minute
session_last_am_minute
session_first_pm_minute
session_first_and_last_minute
"""
# considered sufficient to limit test to sessions of session blocks.
cal, ans = all_calendars_with_answers
for _, block in ans.session_block_generator():
for session in block:
ans_first_minute = ans.first_minutes[session]
ans_last_minute = ans.last_minutes[session]
assert (
cal.session_first_minute(session, _parse=False) == ans_first_minute
)
assert cal.session_last_minute(session, _parse=False) == ans_last_minute
assert cal.session_first_and_last_minute(session, _parse=False) == (
ans_first_minute,
ans_last_minute,
)
last_am_minute = cal.session_last_am_minute(session, _parse=False)
first_pm_minute = cal.session_first_pm_minute(session, _parse=False)
ans_last_am_minute = ans.last_am_minutes[session]
ans_first_pm_minute = ans.first_pm_minutes[session]
if pd.isna(ans_last_am_minute):
assert
|
pd.isna(last_am_minute)
|
pandas.isna
|
from fuzzywuzzy import fuzz
import string
import pandas as pd
import random
import datetime
from annoy import AnnoyIndex
import numpy as np
from pandas.api.types import is_numeric_dtype
### UTILITY Methods
# from importutil import reload
#sys.path.append('c:\\users\\pkapaleeswaran\\workspacej3\\py')
class PyFrame:
x = 7
def __init__(self, cache):
self.cache = cache
@classmethod
def makefm(cls, frame):
cache = {}
cache['data']=frame
cache['version'] = 0
cache['low_version'] = 0
cache[0] = frame
return cls(cache)
@classmethod
def makefm_csv(cls, fileName):
frame = pd.read_csv(fileName)
cache = {}
cache['data']=frame
cache['version'] = 0
cache['low_version'] = 0
cache[0] = frame
return cls(cache)
def id_generator(self, size=6, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
def makeCopy(this):
version = 0
if(version in this.cache):
if('high_version' in this.cache):
version = this.cache['high_version']
else:
version = this.cache['version']
version = version+1
this.cache[version] = this.cache['data'].copy()
this.cache['version'] = version
this.cache['high_version'] = version
# falls back to the last version
def fallback(this):
version = this.cache['version']
low_version = this.cache['low_version']
if(version in this.cache and version > low_version):
this.cache['high_version'] = version
version = version - 1
this.cache['version'] = version
this.cache['data'] = this.cache[version]
else:
print ('cant fall back. In the latest')
def calcRatio(self, actual_col, predicted_col):
result = []
#actual_col = actual_col.unique
#predicted_col = predicted_col.unique
for x in actual_col:
for y in predicted_col:
ratio = fuzz.ratio(x,y)
ratio = 1 - (ratio / 100)
if(ratio != 0):
data = [x,y,ratio]
result.append(data)
result = pd.DataFrame(result)
return result
def match(this, actual_col, predicted_col):
cache = this.cache
key_name = actual_col + "_" + predicted_col
if( not(key_name in cache)):
print ('building cache', key_name)
daFrame = cache['data']
var_name = this.calcRatio(daFrame[actual_col].unique(), daFrame[predicted_col].unique())
var_name.columns = ['col1','col2','distance']
cache[key_name] = var_name
var_name = cache[key_name]
#print(var_name.head())
# seems like we dont need that right now
#output = var_name[(var_name[2] > threshold) & (var_name[2] != 100)]
return var_name
def drop_col(this, col_name, inplace=True):
frame = this.cache['data']
if not inplace:
this.makeCopy()
frame.drop(col_name, axis =1, inplace=True)
this.cache['data'] = frame
def split(this, col_name, delim, inplace=True):
frame = this.cache['data']
if not inplace:
this.makeCopy()
col_to_split = frame[col_name]
splitcol = col_to_split.str.split(delim, expand = True)
for len in splitcol:
frame[col_name + '_' + str(len)] = splitcol[len]
this.cache['data'] = frame
return frame
def replace_val(this, col_name, old_value, new_value, regx=True, inplace=True):
frame = this.cache['data']
if not inplace:
this.makeCopy()
nf = frame.replace({col_name: old_value}, {col_name: new_value}, regex=regx, inplace=inplace)
print('replacing inplace')
#this.cache['data'] = nf
def replace_val2(this, col_name, cur_value, new_col, new_value, regx= True, inplace=True):
frame = this.cache['data']
if not inplace:
this.makeCopy()
nf = frame.replace({col_name: cur_value}, {new_col: new_value}, regex=regx, inplace=inplace)
print('replacing inplace')
def upper(this, col_name, inplace=True):
if not inplace:
this.makeCopy()
frame = this.cache['data']
column = frame[col_name]
frame[col_name] = column.str.upper()
this.cache['data'] = frame
def lower(this, col_name, inplace=True):
if not inplace:
this.makeCopy()
frame = this.cache['data']
column = frame[col_name]
frame[col_name] = column.str.lower()
this.cache['data'] = frame
def title(this, col_name, inplace=True):
if not inplace:
this.makeCopy()
frame = this.cache['data']
column = frame[col_name]
frame[col_name] = column.str.title()
this.cache['data'] = frame
def concat(this, col1, col2, newcol, glue='_', inplace=True):
if not inplace:
this.makeCopy()
frame = this.cache['data']
frame[newcol] = frame[col1] + glue + frame[col2]
this.cache['data'] = frame
def mathcat(this, operation, newcol, inplace=True):
if not inplace:
this.makeCopy()
frame = this.cache['data']
frame[newcol] = operation
this.cache['data'] = frame
def dupecol(this, oldcol, newcol, inplace=True):
if not inplace:
this.makeCopy()
frame = this.cache['data']
frame[newcol] = frame[oldcol]
this.cache['data'] = frame
# dropping row has to be done from inside java
# newframe = mv[mv['Genre'] != 'Drama']
# change type is also done from java
# The actual type is sent from java
def change_col_type(this, col, type, inplace=True):
frame = this.cache['data']
if not inplace:
this.makeCopy()
frame[col] = frame[col].astype(type)
this.cache['data'] = frame
# Index in euclidean space tc.
# input is a pandas frame
# the first column is typically the identifier
# The remaining are the vector
def buildnn(this, trees=10, type='euclidean'):
frame = this.cache['data']
cols = len(frame.columns) - 1
t = AnnoyIndex()
for i, row in frame:
t.add_item(i, row[1:])
this.cache['nn'] = t
# drops non numeric data columns from the frame
def dropalpha(this, inplace=True):
numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']
df = this.cache['data']
if not inplace:
this.makeCopy()
this.cache['data'] = df.select_dtypes(include=numerics)
# drops non numeric data columns from the frame
def dropnum(this, inplace=True):
numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']
df = this.cache['data']
if not inplace:
this.makeCopy()
this.cache['data'] = df.select_dtypes(exclude=numerics)
def extract_num(this, col_name, newcol='assign', inplace=True):
if(newcol == 'assign'):
this.replace_val(col_name, '[a-zA-Z]+', '')
else:
this.dupecol(col_name, newcol)
this.replace_val(newcol, '[a-zA-Z]+', '')
def extract_alpha(this, col_name, newcol='assign', inplace=True):
if(newcol == 'assign'):
this.replace_val(col_name, '\d+', '')
else:
this.dupecol(col_name, newcol)
this.replace_val(newcol, '\d+', '')
def unpivot(this, valcols, idcols=['all'], inplace=True):
frame = this.cache['data']
if not inplace:
this.makeCopy()
# assimilate all the columns if the idcols = 'all'
if idcols == ['all']:
idcols = list(set(list(frame.columns.values)) - set(valcols))
output =
|
pd.melt(mv, id_vars=idcols, value_vars=valcols)
|
pandas.melt
|
# parse log files and generate an excel file
import re
import sys, getopt
import pandas as pd
import xlsxwriter
rx_dict = {
'File': re.compile(r'File: (?P<file>.*) , Top Module: (?P<top_module>.*)'),
'Faults': re.compile(r'Found (?P<fault_sites>.*) fault sites in (?P<gates>.*) gates and (?P<ports>.*) ports.'),
'Time': re.compile(r'Time elapsed: (?P<time>.*)s.'),
'Coverage': re.compile(r'Simulations concluded: Coverage (?P<coverage>.*)%'),
'Iteration': re.compile(r'\((?P<current_coverage>.*)%/(?P<min_coverage>.*)%,\) incrementing to (?P<tv_count>.*).'),
}
def main(argv):
log_file, output_file = parse_args(argv)
data =
|
pd.DataFrame(columns=["File", "Top Module", "Fault Sites", "Gate Count", "Ports", "Run Time", "TV Count", "Coverage"])
|
pandas.DataFrame
|
from psaw import PushshiftAPI
import pandas as pd
import numpy as np
import datetime
class SubmissionData(object):
def __init__(self, api_obj, subreddit_name):
self.api = api_obj
self.subreddit_name = subreddit_name
self.submission_results = None
self.submission_df = None
def retrieve_submissions(self, limit=None):
if limit is not None:
submission_results = list(self.api.search_submissions(subreddit=self.subreddit_name,
filter=['title', 'selftext', 'permalink', 'created_utc'],
limit=limit))
else:
submission_results = list(self.api.search_submissions(subreddit=self.subreddit_name,
filter=['title', 'selftext', 'permalink', 'created_utc']))
self.submission_results = submission_results
return None
def submissions_to_dataframe(self):
sub_dict = {'title': [],
'text': [],
'link': [],
'created_utc': []}
for post in self.submission_results:
try:
title = post.title
text = post.selftext
link = post.permalink
created = post.created_utc
except AttributeError:
continue
else:
sub_dict['title'].append(title)
sub_dict['text'].append(text)
sub_dict['link'].append(link)
sub_dict['created_utc'].append(created)
self.submission_df =
|
pd.DataFrame(sub_dict)
|
pandas.DataFrame
|
# *****************************************************************************
# Copyright (c) 2019, Intel Corporation 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.
#
# 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.
# *****************************************************************************
import operator
import numpy
import pandas
import numba
import sdc
from numba import types
from numba.typing.templates import (infer_global, AbstractTemplate, infer,
signature, AttributeTemplate, infer_getattr, bound_function)
import numba.typing.typeof
from numba.datamodel import StructModel
from numba.errors import TypingError
from numba.extending import (typeof_impl, type_callable, models, register_model, NativeValue,
make_attribute_wrapper, lower_builtin, box, unbox,
lower_getattr, intrinsic, overload_method, overload, overload_attribute)
from numba import cgutils
from sdc.str_ext import string_type
from numba.targets.imputils import (impl_ret_new_ref, impl_ret_borrowed,
iternext_impl, RefType)
from sdc.str_arr_ext import (string_array_type, get_data_ptr,
is_str_arr_typ, pre_alloc_string_array, _memcpy)
from llvmlite import ir as lir
import llvmlite.binding as ll
from llvmlite.llvmpy.core import Type as LLType
from .. import hstr_ext
ll.add_symbol('array_setitem', hstr_ext.array_setitem)
ll.add_symbol('array_getptr1', hstr_ext.array_getptr1)
ll.add_symbol('dtor_str_arr_split_view', hstr_ext.dtor_str_arr_split_view)
ll.add_symbol('str_arr_split_view_impl', hstr_ext.str_arr_split_view_impl)
ll.add_symbol('str_arr_split_view_alloc', hstr_ext.str_arr_split_view_alloc)
char_typ = types.uint8
offset_typ = types.uint32
data_ctypes_type = types.ArrayCTypes(types.Array(char_typ, 1, 'C'))
offset_ctypes_type = types.ArrayCTypes(types.Array(offset_typ, 1, 'C'))
# nested offset structure to represent S.str.split()
# data_offsets array includes offsets to character data array
# index_offsets array includes offsets to data_offsets array to identify lists
class StringArraySplitViewType(types.IterableType):
def __init__(self):
super(StringArraySplitViewType, self).__init__(
name='StringArraySplitViewType()')
@property
def dtype(self):
# TODO: optimized list type
return types.List(string_type)
# TODO
@property
def iterator_type(self):
return # StringArrayIterator()
def copy(self):
return StringArraySplitViewType()
string_array_split_view_type = StringArraySplitViewType()
class StringArraySplitViewPayloadType(types.Type):
def __init__(self):
super(StringArraySplitViewPayloadType, self).__init__(
name='StringArraySplitViewPayloadType()')
str_arr_split_view_payload_type = StringArraySplitViewPayloadType()
# XXX: C equivalent in _str_ext.cpp
@register_model(StringArraySplitViewPayloadType)
class StringArrayPayloadModel(models.StructModel):
def __init__(self, dmm, fe_type):
members = [
('index_offsets', types.CPointer(offset_typ)),
('data_offsets', types.CPointer(offset_typ)),
#('null_bitmap', types.CPointer(char_typ)),
]
models.StructModel.__init__(self, dmm, fe_type, members)
str_arr_model_members = [
('num_items', types.uint64), # number of lists
# ('num_total_strs', types.uint64), # number of strings total
#('num_total_chars', types.uint64),
('index_offsets', types.CPointer(offset_typ)),
('data_offsets', types.CPointer(offset_typ)),
('data', data_ctypes_type),
#('null_bitmap', types.CPointer(char_typ)),
('meminfo', types.MemInfoPointer(str_arr_split_view_payload_type)),
]
@register_model(StringArraySplitViewType)
class StringArrayModel(models.StructModel):
def __init__(self, dmm, fe_type):
models.StructModel.__init__(self, dmm, fe_type, str_arr_model_members)
make_attribute_wrapper(StringArraySplitViewType, 'num_items', '_num_items')
make_attribute_wrapper(StringArraySplitViewType, 'index_offsets', '_index_offsets')
make_attribute_wrapper(StringArraySplitViewType, 'data_offsets', '_data_offsets')
make_attribute_wrapper(StringArraySplitViewType, 'data', '_data')
class SplitViewStringMethodsType(types.IterableType):
"""
Type definition for pandas.core.strings.StringMethods functions handling.
Members
----------
_data: :class:`SeriesType`
input arg
"""
def __init__(self, data):
self.data = data
name = 'SplitViewStringMethodsType({})'.format(self.data)
super(SplitViewStringMethodsType, self).__init__(name)
@property
def iterator_type(self):
return None
@register_model(SplitViewStringMethodsType)
class SplitViewStringMethodsTypeModel(StructModel):
"""
Model for SplitViewStringMethodsType type
All members must be the same as main type for this model
"""
def __init__(self, dmm, fe_type):
members = [
('data', fe_type.data)
]
models.StructModel.__init__(self, dmm, fe_type, members)
make_attribute_wrapper(SplitViewStringMethodsType, 'data', '_data')
def construct_str_arr_split_view(context, builder):
"""Creates meminfo and sets dtor.
"""
alloc_type = context.get_data_type(str_arr_split_view_payload_type)
alloc_size = context.get_abi_sizeof(alloc_type)
llvoidptr = context.get_value_type(types.voidptr)
llsize = context.get_value_type(types.uintp)
dtor_ftype = lir.FunctionType(lir.VoidType(),
[llvoidptr, llsize, llvoidptr])
dtor_fn = builder.module.get_or_insert_function(
dtor_ftype, name="dtor_str_arr_split_view")
meminfo = context.nrt.meminfo_alloc_dtor(
builder,
context.get_constant(types.uintp, alloc_size),
dtor_fn,
)
meminfo_data_ptr = context.nrt.meminfo_data(builder, meminfo)
meminfo_data_ptr = builder.bitcast(meminfo_data_ptr,
alloc_type.as_pointer())
# Nullify all data
# builder.store( cgutils.get_null_value(alloc_type),
# meminfo_data_ptr)
return meminfo, meminfo_data_ptr
@intrinsic
def compute_split_view(typingctx, str_arr_typ, sep_typ=None):
assert str_arr_typ == string_array_type and isinstance(sep_typ, types.StringLiteral)
def codegen(context, builder, sig, args):
str_arr, _ = args
meminfo, meminfo_data_ptr = construct_str_arr_split_view(
context, builder)
in_str_arr = context.make_helper(
builder, string_array_type, str_arr)
# (str_arr_split_view_payload* out_view, int64_t n_strs,
# uint32_t* offsets, char* data, char sep)
fnty = lir.FunctionType(lir.VoidType(),
[meminfo_data_ptr.type,
lir.IntType(64),
lir.IntType(32).as_pointer(),
lir.IntType(8).as_pointer(),
lir.IntType(8)])
fn_impl = builder.module.get_or_insert_function(
fnty, name="str_arr_split_view_impl")
sep_val = context.get_constant(types.int8, ord(sep_typ.literal_value))
builder.call(fn_impl,
[meminfo_data_ptr, in_str_arr.num_items,
in_str_arr.offsets, in_str_arr.data, sep_val])
view_payload = cgutils.create_struct_proxy(
str_arr_split_view_payload_type)(
context, builder, value=builder.load(meminfo_data_ptr))
out_view = context.make_helper(builder, string_array_split_view_type)
out_view.num_items = in_str_arr.num_items
out_view.index_offsets = view_payload.index_offsets
out_view.data_offsets = view_payload.data_offsets
# TODO: incref?
out_view.data = context.compile_internal(
builder, lambda S: get_data_ptr(S),
data_ctypes_type(string_array_type), [str_arr])
# out_view.null_bitmap = view_payload.null_bitmap
out_view.meminfo = meminfo
ret = out_view._getvalue()
#context.nrt.decref(builder, ty, ret)
return impl_ret_new_ref(
context, builder, string_array_split_view_type, ret)
return string_array_split_view_type(
string_array_type, sep_typ), codegen
@box(StringArraySplitViewType)
def box_str_arr_split_view(typ, val, c):
context = c.context
builder = c.builder
sp_view = context.make_helper(builder, string_array_split_view_type, val)
# create array of objects with num_items shape
mod_name = c.context.insert_const_string(c.builder.module, "numpy")
np_class_obj = c.pyapi.import_module_noblock(mod_name)
dtype = c.pyapi.object_getattr_string(np_class_obj, 'object_')
l_num_items = builder.sext(sp_view.num_items, c.pyapi.longlong)
num_items_obj = c.pyapi.long_from_longlong(l_num_items)
out_arr = c.pyapi.call_method(
np_class_obj, "ndarray", (num_items_obj, dtype))
# Array setitem call
arr_get_fnty = LLType.function(
lir.IntType(8).as_pointer(), [c.pyapi.pyobj, c.pyapi.py_ssize_t])
arr_get_fn = c.pyapi._get_function(arr_get_fnty, name="array_getptr1")
arr_setitem_fnty = LLType.function(
lir.VoidType(),
[c.pyapi.pyobj, lir.IntType(8).as_pointer(), c.pyapi.pyobj])
arr_setitem_fn = c.pyapi._get_function(
arr_setitem_fnty, name="array_setitem")
# for each string
with cgutils.for_range(builder, sp_view.num_items) as loop:
str_ind = loop.index
# start and end offset of string's list in index_offsets
# sp_view.index_offsets[str_ind]
list_start_offset = builder.sext(builder.load(builder.gep(sp_view.index_offsets, [str_ind])), lir.IntType(64))
# sp_view.index_offsets[str_ind+1]
list_end_offset = builder.sext(
builder.load(
builder.gep(
sp_view.index_offsets, [
builder.add(
str_ind, str_ind.type(1))])), lir.IntType(64))
# cgutils.printf(builder, "%d %d\n", list_start, list_end)
# Build a new Python list
nitems = builder.sub(list_end_offset, list_start_offset)
nitems = builder.sub(nitems, nitems.type(1))
# cgutils.printf(builder, "str %lld n %lld\n", str_ind, nitems)
list_obj = c.pyapi.list_new(nitems)
with c.builder.if_then(cgutils.is_not_null(c.builder, list_obj),
likely=True):
with cgutils.for_range(c.builder, nitems) as loop:
# data_offsets of current list
start_index = builder.add(list_start_offset, loop.index)
data_start = builder.load(builder.gep(sp_view.data_offsets, [start_index]))
# add 1 since starts from -1
data_start = builder.add(data_start, data_start.type(1))
data_end = builder.load(
builder.gep(
sp_view.data_offsets, [
builder.add(
start_index, start_index.type(1))]))
# cgutils.printf(builder, "ind %lld %lld\n", data_start, data_end)
data_ptr = builder.gep(builder.extract_value(sp_view.data, 0), [data_start])
str_size = builder.sext(builder.sub(data_end, data_start), lir.IntType(64))
str_obj = c.pyapi.string_from_string_and_size(data_ptr, str_size)
c.pyapi.list_setitem(list_obj, loop.index, str_obj)
arr_ptr = builder.call(arr_get_fn, [out_arr, str_ind])
builder.call(arr_setitem_fn, [out_arr, arr_ptr, list_obj])
c.pyapi.decref(np_class_obj)
return out_arr
@intrinsic
def pre_alloc_str_arr_view(typingctx, num_items_t, num_offsets_t, data_t=None):
assert num_items_t == types.intp and num_offsets_t == types.intp
def codegen(context, builder, sig, args):
num_items, num_offsets, data_ptr = args
meminfo, meminfo_data_ptr = construct_str_arr_split_view(
context, builder)
# (str_arr_split_view_payload* out_view, int64_t num_items,
# int64_t num_offsets)
fnty = lir.FunctionType(
lir.VoidType(),
[meminfo_data_ptr.type, lir.IntType(64), lir.IntType(64)])
fn_impl = builder.module.get_or_insert_function(
fnty, name="str_arr_split_view_alloc")
builder.call(fn_impl,
[meminfo_data_ptr, num_items, num_offsets])
view_payload = cgutils.create_struct_proxy(
str_arr_split_view_payload_type)(
context, builder, value=builder.load(meminfo_data_ptr))
out_view = context.make_helper(builder, string_array_split_view_type)
out_view.num_items = num_items
out_view.index_offsets = view_payload.index_offsets
out_view.data_offsets = view_payload.data_offsets
# TODO: incref?
out_view.data = data_ptr
if context.enable_nrt:
context.nrt.incref(builder, data_t, data_ptr)
# out_view.null_bitmap = view_payload.null_bitmap
out_view.meminfo = meminfo
ret = out_view._getvalue()
return impl_ret_new_ref(
context, builder, string_array_split_view_type, ret)
return string_array_split_view_type(
types.intp, types.intp, data_t), codegen
@intrinsic
def get_c_arr_ptr(typingctx, c_arr, ind_t=None):
assert isinstance(c_arr, (types.CPointer, types.ArrayCTypes))
def codegen(context, builder, sig, args):
in_arr, ind = args
if isinstance(sig.args[0], types.ArrayCTypes):
in_arr = builder.extract_value(in_arr, 0)
return builder.bitcast(
builder.gep(in_arr, [ind]), lir.IntType(8).as_pointer())
return types.voidptr(c_arr, ind_t), codegen
@intrinsic
def getitem_c_arr(typingctx, c_arr, ind_t=None):
def codegen(context, builder, sig, args):
in_arr, ind = args
return builder.load(builder.gep(in_arr, [ind]))
return c_arr.dtype(c_arr, ind_t), codegen
@intrinsic
def setitem_c_arr(typingctx, c_arr, ind_t, item_t=None):
def codegen(context, builder, sig, args):
in_arr, ind, item = args
ptr = builder.gep(in_arr, [ind])
builder.store(item, ptr)
return types.void(c_arr, ind_t, c_arr.dtype), codegen
@intrinsic
def get_array_ctypes_ptr(typingctx, arr_ctypes_t, ind_t=None):
def codegen(context, builder, sig, args):
in_arr_ctypes, ind = args
arr_ctypes = context.make_helper(
builder, arr_ctypes_t, in_arr_ctypes)
out = context.make_helper(builder, arr_ctypes_t)
out.data = builder.gep(arr_ctypes.data, [ind])
out.meminfo = arr_ctypes.meminfo
res = out._getvalue()
return impl_ret_borrowed(context, builder, arr_ctypes_t, res)
return arr_ctypes_t(arr_ctypes_t, ind_t), codegen
@numba.njit(no_cpython_wrapper=True)
def get_split_view_index(arr, item_ind, str_ind):
start_index = getitem_c_arr(arr._index_offsets, item_ind)
# TODO: check num strings and support NAN
# end_index = getitem_c_arr(arr._index_offsets, item_ind+1)
data_start = getitem_c_arr(
arr._data_offsets, start_index + str_ind)
data_start += 1
# get around -1 storage in uint32 problem
if start_index + str_ind == 0:
data_start = 0
data_end = getitem_c_arr(
arr._data_offsets, start_index + str_ind + 1)
return data_start, (data_end - data_start)
@numba.njit(no_cpython_wrapper=True)
def get_split_view_data_ptr(arr, data_start):
return get_array_ctypes_ptr(arr._data, data_start)
@overload(len)
def str_arr_split_view_len_overload(arr):
if arr == string_array_split_view_type:
return lambda arr: arr._num_items
@overload_method(SplitViewStringMethodsType, 'len')
def hpat_pandas_spliview_stringmethods_len(self):
"""
Pandas Series method :meth:`pandas.core.strings.StringMethods.len()` implementation.
Note: Unicode type of list elements are supported only. Numpy.NaN is not supported as elements.
.. only:: developer
Test: python -m sdc.runtests sdc.tests.test_hiframes.TestHiFrames.test_str_split_filter
Parameters
----------
self: :class:`pandas.core.strings.StringMethods`
input arg
Returns
-------
:obj:`pandas.Series`
returns :obj:`pandas.Series` object
"""
if not isinstance(self, SplitViewStringMethodsType):
msg = 'Method len(). The object must be a pandas.core.strings. Given: {}'
raise TypingError(msg.format(self))
def hpat_pandas_spliview_stringmethods_len_impl(self):
item_count = len(self._data)
result = numpy.empty(item_count, numba.types.int64)
local_data = self._data._data
for i in range(len(local_data)):
result[i] = len(local_data[i])
return
|
pandas.Series(result, self._data._index, name=self._data._name)
|
pandas.Series
|
"""
tests the pysat meta object and code
"""
import pysat
import pandas as pds
from nose.tools import assert_raises, raises
import nose.tools
from functools import partial
import tempfile
import pysat.instruments.pysat_testing
# import pysat.instruments as instruments
import numpy as np
# import os
import sys
import importlib
exclude_list = ['champ_star', 'superdarn_grdex', 'cosmic_gps', 'cosmic2013_gps',
'icon_euv', 'icon_ivm']
# dict, keyed by pysat instrument, with a list of usernames and passwords
user_download_dict = {'supermag_magnetometer':['rstoneback', None]}
if sys.version_info[0] >= 3:
# TODO Remove when pyglow works in python 3
exclude_list.append('pysat_sgp4')
def safe_data_dir():
saved_path = pysat.data_dir
if saved_path is '':
saved_path = '.'
return saved_path
def init_func_external(self):
"""Iterate through and create all of the test Instruments needed.
Only want to do this once.
"""
# names of all the instrument modules
instrument_names = pysat.instruments.__all__
temp = []
for name in instrument_names:
if name not in exclude_list:
temp.append(name)
instrument_names = temp
self.instruments = []
self.instrument_modules = []
# create temporary directory
dir_name = tempfile.mkdtemp()
saved_path = safe_data_dir()
pysat.utils.set_data_dir(dir_name, store=False)
for name in instrument_names:
try:
module = importlib.import_module(''.join(('.', name)), package='pysat.instruments')
except ImportError:
print ("Couldn't import instrument module")
pass
else:
# try and grab basic information about the module so we
# can iterate over all of the options
try:
info = module.test_dates
except AttributeError:
info = {}
info[''] = {'':pysat.datetime(2009,1,1)}
module.test_dates = info
for sat_id in info.keys() :
for tag in info[sat_id].keys():
try:
inst = pysat.Instrument(inst_module=module,
tag=tag,
sat_id=sat_id,
temporary_file_list=True)
inst.test_dates = module.test_dates
self.instruments.append(inst)
self.instrument_modules.append(module)
except:
pass
pysat.utils.set_data_dir(saved_path, store=False)
init_inst = None
init_mod = None
class TestInstrumentQualifier():
def __init__(self):
"""Iterate through and create all of the test Instruments needed"""
global init_inst
global init_mod
if init_inst is None:
init_func_external(self)
init_inst = self.instruments
init_mod = self.instrument_modules
else:
self.instruments = init_inst
self.instrument_modules = init_mod
def setup(self):
"""Runs before every method to create a clean testing setup."""
pass
def teardown(self):
"""Runs after every method to clean up previous testing."""
pass
def check_module_loadable(self, module, tag, sat_id):
a = pysat.Instrument(inst_module=module, tag=tag, sat_id=sat_id)
assert True
def check_module_importable(self, name):
module = importlib.import_module(''.join(('.', name)), package='pysat.instruments')
assert True
def check_module_info(self, module):
platform = module.platform
name = module.name
tags = module.tags
sat_ids = module.sat_ids
check = []
# check tags is a dict
check.append(isinstance(tags, dict))
# that contains strings
# check sat_ids is a dict
check.append(isinstance(sat_ids, dict))
# that contains lists
assert np.all(check)
def test_modules_loadable(self):
instrument_names = pysat.instruments.__all__
self.instruments = []
for name in instrument_names:
f = partial(self.check_module_importable, name)
f.description = ' '.join(('Checking importability for module:', name))
yield (f,)
try:
module = importlib.import_module(''.join(('.', name)), package='pysat.instruments')
except ImportError:
pass
else:
# try and grab basic information about the module so we
# can iterate over all of the options
f = partial(self.check_module_info, module)
f.description = ' '.join(('Checking module has platform, name, tags, sat_ids. Testing module:', name))
yield (f,)
try:
info = module.test_dates
except AttributeError:
info = {}
info[''] = {'':'failsafe'}
for sat_id in info.keys() :
for tag in info[sat_id].keys():
f = partial(self.check_module_loadable, module, tag, sat_id)
f.description = ' '.join(('Checking pysat.Instrument instantiation for module:', name, 'tag:', tag, 'sat id:', sat_id))
yield (f, )
def check_load_presence(self, inst):
_ = inst.load
assert True
def test_load_presence(self):
for module in self.instrument_modules:
f = partial(self.check_load_presence, module)
f.description = ' '.join(('Checking for load routine for module: ', module.platform, module.name))
yield (f,)
def check_list_files_presence(self, module):
_ = module.list_files
assert True
def test_list_files_presence(self):
for module in self.instrument_modules:
f = partial(self.check_list_files_presence, module)
f.description = ' '.join(('Checking for list_files routine for module: ', module.platform, module.name))
yield (f,)
def check_download_presence(self, inst):
_ = inst.download
assert True
def test_download_presence(self):
for module in self.instrument_modules:
yield (self.check_download_presence, module)
def check_module_tdates(self, module):
info = module.test_dates
check = []
for sat_id in info.keys():
for tag in info[sat_id].keys():
check.append(isinstance(info[sat_id][tag], pysat.datetime))
assert np.all(check)
def check_download(self, inst):
from unittest.case import SkipTest
import os
start = inst.test_dates[inst.sat_id][inst.tag]
# print (start)
try:
# check for username
inst_name = '_'.join((inst.platform, inst.name))
if inst_name in user_download_dict:
inst.download(start, start, user=user_download_dict[inst_name][0],
password=user_download_dict[inst_name][1])
else:
inst.download(start, start)
except Exception as e:
# couldn't run download, try to find test data instead
print("Couldn't download data, trying to find test data.")
saved_path = safe_data_dir()
new_path = os.path.join(pysat.__path__[0],'tests', 'test_data')
pysat.utils.set_data_dir(new_path, store=False)
test_dates = inst.test_dates
inst = pysat.Instrument(platform=inst.platform,
name=inst.name,
tag=inst.tag,
sat_id=inst.sat_id,
temporary_file_list=True)
inst.test_dates = test_dates
pysat.utils.set_data_dir(saved_path, store=False)
if len(inst.files.files) > 0:
print("Found test data.")
raise SkipTest
else:
print("No test data found.")
raise e
assert True
def check_load(self, inst, fuzzy=False):
# set ringer data
inst.data = pds.DataFrame([0])
start = inst.test_dates[inst.sat_id][inst.tag]
inst.load(date=start)
if not fuzzy:
assert not inst.empty
else:
try:
assert inst.data !=
|
pds.DataFrame([0])
|
pandas.DataFrame
|
import IMLearn.learners.regressors.linear_regression
from IMLearn.learners.regressors import PolynomialFitting
from IMLearn.utils import split_train_test
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
import plotly.io as pio
pio.templates.default = "simple_white"
DEGREE = 6
def load_data(filename: str) -> pd.DataFrame:
"""
Load city daily temperature dataset and preprocess data.
Parameters
----------
filename: str
Path to house prices dataset
Returns
-------
Design matrix and response vector (Temp)
"""
df = pd.read_csv(filename, parse_dates=["Date"]).dropna().drop_duplicates()
df = df.drop("City", 1)
df =
|
pd.get_dummies(df)
|
pandas.get_dummies
|
# Loading packages here
import sys
import argparse
import numpy as np
# import skbio as sb # Use this for ANOSIM
import pandas as pd # Use this for working with dataframes
import os
import networkx
import scipy.stats as stats
# import scipy.spatial.distance as distance # conda install scipy
# from skbio.diversity import beta_diversity # for bray curtis conditioning
from sklearn.decomposition import PCA # Use for PCA
import matplotlib.pyplot as plt # Use this for plotting
# from skbio.stats.distance import anosim
import math
import csv
import minepy # pip install minepy
import time
import seaborn as sb
global min_count
global window_size
global outdir
global disjoint
global connectedness
global detailed_
def remove_min_count(df, min_count):
"""
Function remove_min_count: This function removes data that is all zeros in a column
best used once merging has taken place to get rid of all features that are zero in both conditions
:param df: @type pandas dataframe: The data to remove counts below min_count
:return: @type pandas dataframe: The resulting dataframe after removal
"""
return (df.loc[:, (df > min_count).any(axis=0)])
def add_one_smoothing(df):
"""
Function add_one_smoothing: Add one accounts for the possibility of unseen events (0s) occurring in the future.
:param df: @type pandas dataframe: The data to smooth
:return: @type pandas dataframe: The smoothed data
"""
temp = df.copy() + 1
temp = temp / temp.sum()
return temp
def bray_curtis(df):
"""
Function bray_curtis: Performs a bray-curtis dissimilarity
:param df: @type pandas dataframe: The data to do the dissimilarity on
:return: @type pandas dataframe: The bray-curtis'ed data
Computes the Bray-Curtis distance between two 1-D arrays.
"""
temp = df.copy()
ids = df.columns.values.tolist()
bc = beta_diversity("braycurtis", temp.transpose(), ids)
bc_df = pd.DataFrame(data=bc.data, index=bc.ids, columns=bc.ids)
return bc_df
def hellinger(df):
"""
Function hellinger: The hellinger transformation deals with the double zero problem in ecology.
The hellinger transformation is the square root of the result of the current row
divided by the sum of all rows. This is done for each element in the dataframe.
:param df: @type pandas dataframe: The data to do the transformation on.
:return: @type pandas dataframe: A dataframe of the hellinger transformed data.
"""
temp = df.copy()
hellinger_data = np.sqrt(temp.div(temp.sum(axis=1), axis=0)) # Hellinger transformation
return hellinger_data
def condition(df, cond_type):
"""
Function condition: A preprocessing step to condition the data based on the type specidied
:param data: @type pandas dataframe - The data to be conditioned
:param cond_type: @type string - The type of conditioning to run. Valid values: add_one, hellinger
:return: @type pandas dataframe - The conditioned dataframe.
"""
# print('conditioning type', cond_type)
temp = df.copy()
temp = temp.loc[(temp != 0).any(axis=1)]
if cond_type == 'add_one':
conditioned_data = add_one_smoothing(temp)
elif cond_type == 'hellinger':
conditioned_data = hellinger(temp)
elif cond_type == 'bray_curtis':
conditioned_data = bray_curtis(temp)
else:
conditioned_data = temp
return conditioned_data
def smooth(df, type):
"""
Function smooth: Smoothing function to filter out noise
:param df: @type pandas dataframe: The data to be smoothed
:param type: @type string: The type of smoothing to do (currently sliding_window is the only option)
:return: @type pandas dataframe: A dataframe of the smoothed data
"""
temp = df.copy()
if type == 'sliding_window':
result = temp.rolling(window_size, min_periods=1, center=True).mean()
else:
result = temp
return result
def pca_abundance(df, num_pca_components=4, cond_type='hellinger'):
"""
Function pca_abundance: running PCA iteratively on the data, removing the highest/lowest abundance features
(based on sorting of abundances array). The gradient is used to find the greatest change in inertia when
features are removed. Then we select all the features up to that point. These are the most important features
:param data: @type pandas dataframe: The data to run pca on
:param num_pca_components: @type integer: The number of components to use for pca
:param cond_type: @type string: The conditioning type to use for pca (eg. hellinger, add_one)
:param smoothing_type: @type string: The type of smoothing to do on the dataframe of total eigenvalues found by PCA
:return: important_features - a list of the most important features as found by running the PCA
"""
pca = PCA(n_components=num_pca_components) # Run a PCA with n components
data = df.copy() # copy the data into a dataframe to manipulate
eigen_df = pd.DataFrame() # create a dataframe to hold the eigenvalues from the pca
abundances_arr = pd.unique(data.sum(axis=0)) # get the set of unique values
abundances_arr = np.sort(abundances_arr)[::-1] # sort highest to lowest
# now we want to loop through all the abundances and find those with the most variance
# once we find those we'll have to match them back up to the features with those abundances
# so that we can send back the list of sorted features
for i in range(len(abundances_arr)):
if len(abundances_arr) - i == num_pca_components:
break
conditioned_df = condition(data, cond_type) # condition data
result = pca.fit(conditioned_df) # Run the PCA on the conditioned data here
variance_arr = result.explained_variance_ratio_ # Output the variance associated with each eigenvector
drop_list = list(
data.columns[data.sum(axis=0) == abundances_arr[i]]) # Find all features with the current abundance
components = result.components_
variance_df = pd.DataFrame(variance_arr, columns=[
str(abundances_arr[i])]).transpose() # Convert the eigenvalues to a data frame of OTU rows x N components
# variance_df = pd.DataFrame(variance_arr).transpose() # Convert the eigenvalues to a data frame of OTU rows x N components
eigen_df = eigen_df.append(variance_df) # Append to the eigenvalue df
data.drop(drop_list, inplace=True, axis=1) # Drop all the features with the current abundance
# You can only iterate over the number of features minus the number of components.
if len(abundances_arr) - i == num_pca_components:
break
eigen_df['Total'] = eigen_df.sum(axis=1) # sum up the eigenvalues to get the total variance of all components
# print('eigen df', eigen_df)
total_eigen = eigen_df.copy().iloc[:, [-1]]
total_eigen.sort_values(by='Total', ascending=0,
inplace=True) # order the values in descending order, since we want to remove the highest eigenvalues
# loop through each row and get the feature name and the abundance.
# Match the feature name to the eigenvector variance from the total_eigen dataframe.
# Then we'll return a dataframe with the feature as an index and the variance as the value
ordered_features = pd.DataFrame(columns=['variance'])
for index, row in df.sum(axis=0).iteritems():
if str(row) in total_eigen.index:
# print('variance = ',total_eigen['Total'].loc[str(row)])
ordered_features.loc[index] = total_eigen['Total'].loc[str(row)]
ordered_features.sort_values(by='variance', ascending=0, inplace=True)
return ordered_features
def pca_importance(df, num_pca_components=4, cond_type='hellinger'):
"""
Function pca_importance: running PCA and selecting the most important features as found
by the eigenvectors.
:param data: @type pandas dataframe: The data to run pca on
:param num_pca_components: @type integer: The number of components to use for pca
:param select_n: @type integer: The number of important features to return
:param cond_type: @type string: The conditioning type to use for pca (eg. hellinger, add_one)
:param smoothing_type: @type string: The type of smoothing to do on the dataframe of total eigenvalues found by PCA
:return: ordered_features - a numpy array of the features ordered from most important to least, as found by running the PCA
"""
pca = PCA(n_components=num_pca_components) # Run a PCA with n components
data = df.copy() # copy the data into a dataframe to manipulate
conditioned_df = condition(data, cond_type) # condition data
result = pca.fit(conditioned_df) # Run the PCA on the conditioned data here
components = result.components_ # the eigenvectors/components
eigenvectors = pd.DataFrame(components, columns=[data.columns])
abs_eigens = np.absolute(eigenvectors) # element wise absolute value to get rid of negatives
variance = pd.DataFrame({'metric': abs_eigens.sum(
axis=0)}) # sum up the components to get the amount of variance across all components for each feature
variance['pca1'], variance['pca2'] = eigenvectors.iloc[0], eigenvectors.iloc[1]
# order the features from largest to smallest to return as our sorted dataframe
ordered_features = variance.sort_values(by='metric', ascending=0)
# print('ordered_features columns', ordered_features.index.values[0])
if( type( ordered_features.index.values[0] ) is tuple ):
# this means that a function has covereted indecis to sparse series, must convert this back to
# a dense dataframe. This should be able to be removed after Qiime updates
ordered_feature = pd.DataFrame(columns=["OTU","metric","pca1","pca2"])
for index, row in ordered_features.iterrows():
ordered_feature = ordered_feature.append( {"OTU": index[0], "metric": row["metric"],
"pca1": row["pca1"], "pca2": row["pca2"] }, ignore_index=True )
ordered_feature = ordered_feature.set_index("OTU")
return ordered_feature
else:
return ordered_features
def pca_legendre(df, num_pca_components, cond_type='hellinger'):
return 0
def abundance(df):
data = df.copy()
summed_vals = data.sum(axis=0)
sorted_abundances = summed_vals.sort_values(ascending=0)
return sorted_abundances
def find_correlation(df, corr_type='spearman'):
df_r = 0
data = df.copy()
if corr_type == 'MIC':
# the pstats output for the mic and tic are condensed 1D arrays
# we need to turn the output into a 2D upper triangular matrix and then mirror it to get the
# full correlation matrix
micp, ticp = minepy.pstats(data.T, alpha=0.6, c=15, est="mic_approx")
num_features = data.shape[1]
tri = np.zeros((num_features, num_features))
tri[np.triu_indices(num_features, 1)] = micp
full_corr = tri + tri.T
df_r =
|
pd.DataFrame(full_corr)
|
pandas.DataFrame
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pandas as pd
import json
from matplotlib import pyplot as plt
import numpy as np
from numpy.fft import fft, fftfreq
# Configuration
anomaly_color = 'sandybrown'
prediction_color = 'yellowgreen'
training_color = 'yellowgreen'
validation_color = 'gold'
test_color = 'coral'
figsize=(9, 3)
autoclose = True
def load_series(file_name, data_folder):
# Load the input data
data_path = f'{data_folder}/data/{file_name}'
data = pd.read_csv(data_path)
data['timestamp'] = pd.to_datetime(data['timestamp'])
data.set_index('timestamp', inplace=True)
# Load the labels
label_path = f'{data_folder}/labels/combined_labels.json'
with open(label_path) as fp:
labels = pd.Series(json.load(fp)[file_name])
labels = pd.to_datetime(labels)
# Load the windows
window_path = f'{data_folder}/labels/combined_windows.json'
window_cols = ['begin', 'end']
with open(window_path) as fp:
windows = pd.DataFrame(columns=window_cols,
data=json.load(fp)[file_name])
windows['begin'] = pd.to_datetime(windows['begin'])
windows['end'] = pd.to_datetime(windows['end'])
# Return data
return data, labels, windows
def plot_series(data, labels=None,
windows=None,
predictions=None,
highlights=None,
val_start=None,
test_start=None,
figsize=figsize,
show_sampling_points=False,
show_markers=False,
filled_version=None):
# Open a new figure
if autoclose: plt.close('all')
plt.figure(figsize=figsize)
# Plot data
if not show_markers:
plt.plot(data.index, data.values, zorder=0)
else:
plt.plot(data.index, data.values, zorder=0,
marker='.', markersize=3)
if filled_version is not None:
filled = filled_version.copy()
filled[~data['value'].isnull()] = np.nan
plt.scatter(filled.index, filled,
marker='.', c='tab:orange', s=5);
if show_sampling_points:
vmin = data.min()
lvl = np.full(len(data.index), vmin)
plt.scatter(data.index, lvl, marker='.',
c='tab:red', s=5)
# Rotated x ticks
plt.xticks(rotation=45)
# Plot labels
if labels is not None:
plt.scatter(labels.values, data.loc[labels],
color=anomaly_color, zorder=2, s=5)
# Plot windows
if windows is not None:
for _, wdw in windows.iterrows():
plt.axvspan(wdw['begin'], wdw['end'],
color=anomaly_color, alpha=0.3, zorder=1)
# Plot training data
if val_start is not None:
plt.axvspan(data.index[0], val_start,
color=training_color, alpha=0.1, zorder=-1)
if val_start is None and test_start is not None:
plt.axvspan(data.index[0], test_start,
color=training_color, alpha=0.1, zorder=-1)
if val_start is not None:
plt.axvspan(val_start, test_start,
color=validation_color, alpha=0.1, zorder=-1)
if test_start is not None:
plt.axvspan(test_start, data.index[-1],
color=test_color, alpha=0.3, zorder=0)
# Predictions
if predictions is not None:
plt.scatter(predictions.values, data.loc[predictions],
color=prediction_color, alpha=.4, zorder=3,
s=5)
plt.tight_layout()
def plot_autocorrelation(data, max_lag=100, figsize=figsize):
# Open a new figure
if autoclose: plt.close('all')
plt.figure(figsize=figsize)
# Autocorrelation plot
pd.plotting.autocorrelation_plot(data['value'])
# Customized x limits
plt.xlim(0, max_lag)
# Rotated x ticks
plt.xticks(rotation=45)
plt.tight_layout()
def plot_histogram(data, bins=10, vmin=None, vmax=None, figsize=figsize):
# Build a new figure
if autoclose: plt.close('all')
plt.figure(figsize=figsize)
# Plot a histogram
plt.hist(data, density=True, bins=bins)
# Update limits
lims = plt.xlim()
if vmin is not None:
lims = (vmin, lims[1])
if vmax is not None:
lims = (lims[0], vmax)
plt.xlim(lims)
plt.tight_layout()
def plot_histogram2d(xdata, ydata, bins=10, figsize=figsize):
# Build a new figure
if autoclose: plt.close('all')
plt.figure(figsize=figsize)
# Plot a histogram
plt.hist2d(xdata, ydata, density=True, bins=bins)
plt.tight_layout()
def plot_density_estimator_1D(estimator, xr, figsize=figsize):
# Build a new figure
if autoclose: plt.close('all')
plt.figure(figsize=figsize)
# Plot the estimated density
xvals = xr.reshape((-1, 1))
dvals = np.exp(estimator.score_samples(xvals))
plt.plot(xvals, dvals)
plt.tight_layout()
def plot_density_estimator_2D(estimator, xr, yr, figsize=figsize):
# Plot the estimated density
nx = len(xr)
ny = len(yr)
xc = np.repeat(xr, ny)
yc = np.tile(yr, nx)
data = np.vstack((xc, yc)).T
dvals = np.exp(estimator.score_samples(data))
dvals = dvals.reshape((nx, ny))
# Build a new figure
if autoclose: plt.close('all')
plt.figure(figsize=figsize)
plt.pcolor(dvals)
plt.tight_layout()
# plt.xticks(np.arange(0, len(xr)), xr)
# plt.yticks(np.arange(0, len(xr)), yr)
def plot_distribution_2D(f, xr, yr, figsize=figsize):
# Build the input
nx = len(xr)
ny = len(yr)
xc = np.repeat(xr, ny)
yc = np.tile(yr, nx)
data = np.vstack((xc, yc)).T
dvals = np.exp(f.pdf(data))
dvals = dvals.reshape((nx, ny))
# Build a new figure
if autoclose: plt.close('all')
plt.figure(figsize=figsize)
plt.pcolor(dvals)
plt.tight_layout()
xticks = np.linspace(0, len(xr), 6)
xlabels = np.linspace(xr[0], xr[-1], 6)
plt.xticks(xticks, xlabels)
yticks = np.linspace(0, len(yr), 6)
ylabels = np.linspace(yr[0], yr[-1], 6)
plt.yticks(yticks, ylabels)
def get_pred(signal, thr):
return pd.Series(signal.index[signal >= thr])
def get_metrics(pred, labels, windows):
tp = [] # True positives
fp = [] # False positives
fn = [] # False negatives
advance = [] # Time advance, for true positives
# Loop over all windows
used_pred = set()
for idx, w in windows.iterrows():
# Search for the earliest prediction
pmin = None
for p in pred:
if p >= w['begin'] and p < w['end']:
used_pred.add(p)
if pmin is None or p < pmin:
pmin = p
# Compute true pos. (incl. advance) and false neg.
l = labels[idx]
if pmin is None:
fn.append(l)
else:
tp.append(l)
advance.append(l-pmin)
# Compute false positives
for p in pred:
if p not in used_pred:
fp.append(p)
# Return all metrics as pandas series
return pd.Series(tp), \
pd.Series(fp), \
|
pd.Series(fn)
|
pandas.Series
|
# -*- coding: utf-8 -*-
"""
Created 2020.05.22.
Script for doing group level analysis of fidelity and true/false positive rates.
@author: rouhinen
"""
import numpy as np
import os
import glob
import matplotlib.pyplot as plt
from tqdm import tqdm
import pandas as pd
from fidelityOpMinimal import fidelity_estimation, make_series_paired, source_fid_to_weights
"""Load source identities, forward and inverse operators from npy. """
subjectsPath = 'C:\\temp\\fWeighting\\fwSubjects_p\\'
sourceIdPattern = '\\sourceIdentities_parc2018yeo7_XYZ.npy' # XYZ is replaced below.
sourceFidPattern = '\\sourceFidelities_MEEG_parc2018yeo7_XYZ.npy'
savePathBase = "C:\\temp\\fWeighting\\plotDump\\schaeferXYZ "
forwardPattern = '\\forwardOperatorMEEG.npy'
inversePattern = '\\inverseOperatorMEEG.npy'
XYZto = '100'
n_samples = 10000
n_cut_samples = 40
widths = np.arange(5, 6)
# Source fidelity to weights settings
exponent = 2
normalize = True
flips = False
# Save and plotting settings
savePDFs = True
tightLayout = True
""" Replace XYZ """
sourceIdPattern = sourceIdPattern.replace('XYZ', XYZto)
sourceFidPattern = sourceFidPattern.replace('XYZ', XYZto)
savePathBase = savePathBase.replace('XYZ', XYZto)
def get_tp_fp_rates(cp_PLV, truth_matrix):
# Set thresholds from the data. Get about 200 thresholds.
maxVal = np.max(cp_PLV)
thresholds = np.sort(np.ravel(cp_PLV))
distance = int(len(thresholds) // 200) + (len(thresholds) % 200 > 0) # To int, round up.
thresholds = thresholds[0:-1:distance]
thresholds = np.append(thresholds, maxVal)
tpRate = np.zeros(len(thresholds), dtype=float)
fpRate = np.zeros(len(thresholds), dtype=float)
for i, threshold in enumerate(thresholds):
estTrueMat = cp_PLV > threshold
tPos = np.sum(estTrueMat * truth_matrix)
fPos = np.sum(estTrueMat * np.logical_not(truth_matrix))
tNeg = np.sum(np.logical_not(estTrueMat) * np.logical_not(truth_matrix))
fNeg = np.sum(truth_matrix) - tPos
tpRate[i] = tPos / (tPos + fNeg)
fpRate[i] = fPos / (fPos + tNeg)
return tpRate, fpRate
def find_nearest_index(array, value):
array = np.asarray(array)
idx = (np.abs(array - value)).argmin()
return idx
def get_nearest_tp_semi_bin(binArray, tpRate, fpRate):
nearestTP = np.zeros(len(binArray))
for i, fpval in enumerate(binArray):
index = find_nearest_index(fpRate, fpval)
nearestTP[i] = tpRate[index]
return nearestTP
def delete_diagonal(symm_matrix):
symm_matrix = symm_matrix[~np.eye(symm_matrix.shape[0],dtype=bool)].reshape(
symm_matrix.shape[0],-1)
return symm_matrix
def get_n_parcels(identities):
idSet = set(identities) # Get unique IDs
idSet = [item for item in idSet if item >= 0] # Remove negative values (should have only -1 if any)
n_parcels = len(idSet)
return n_parcels
## Create "bins" for X-Axis.
n_bins = 101
binArray = np.logspace(-2, 0, n_bins-1, endpoint=True) # Values from 0.01 to 1
binArray = np.concatenate(([0], binArray)) # Add 0 to beginning
## Get subjects list, and first subject's number of parcels.
subjects = next(os.walk(subjectsPath))[1]
if any('_Population' in s for s in subjects):
subjects.remove('_Population')
subjectFolder = os.path.join(subjectsPath, subjects[0])
sourceIdFile = glob.glob(subjectFolder + sourceIdPattern)[0]
identities = np.load(sourceIdFile) # Source length vector. Expected ids for parcels are 0 to n-1, where n is number of parcels, and -1 for sources that do not belong to any parcel.
n_parcels = get_n_parcels(identities)
## Initialize arrays
fidWArray = np.zeros((len(subjects), n_parcels), dtype=float)
fidOArray = np.zeros((len(subjects), n_parcels), dtype=float)
tpWArray = np.zeros((len(subjects), n_bins), dtype=float)
tpOArray = np.zeros((len(subjects), n_bins), dtype=float)
sizeArray = []
### Loop over subjects. Insert values to subject x parcels/bins arrays.
for run_i, subject in enumerate(tqdm(subjects)):
## Load files
subjectFolder = os.path.join(subjectsPath, subject)
fileSourceIdentities = glob.glob(subjectFolder + sourceIdPattern)[0]
fileForwardOperator = glob.glob(subjectFolder + forwardPattern)[0]
fileInverseOperator = glob.glob(subjectFolder + inversePattern)[0]
fileSourceFidelities = glob.glob(subjectFolder + sourceFidPattern)[0]
identities = np.load(fileSourceIdentities) # Source length vector. Expected ids for parcels are 0 to n-1, where n is number of parcels, and -1 for sources that do not belong to any parcel.
forward = np.matrix(np.load(fileForwardOperator)) # sensors x sources
inverse = np.matrix(np.load(fileInverseOperator)) # sources x sensors
sourceFids = np.load(fileSourceFidelities) # sources
# identities = np.genfromtxt(fileSourceIdentities, dtype='int32', delimiter=delimiter) # Source length vector. Expected ids for parcels are 0 to n-1, where n is number of parcels, and -1 for sources that do not belong to any parcel.
# forward = np.matrix(np.genfromtxt(fileForwardOperator, dtype='float', delimiter=delimiter)) # sensors x sources
# inverse = np.matrix(np.genfromtxt(fileInverseOperator, dtype='float', delimiter=delimiter)) # sources x sensors
# sourceFids = np.genfromtxt(fileSourceFidelities, dtype='float', delimiter=delimiter) # sources
weights = source_fid_to_weights(sourceFids, exponent=exponent, normalize=normalize,
inverse=inverse, identities=identities, flips=flips)
inverse_w = np.einsum('ij,i->ij', inverse, weights)
n_parcels = get_n_parcels(identities)
if run_i == 0:
prior_n_parcels = n_parcels
else:
if prior_n_parcels == n_parcels:
print('Running subject ' + subject)
else:
print('Mismatch in number of parcels between subjects!')
""" Get fidelities from unpaired data. """
# inverse_w, _ = _compute_weights(sourceSeries, parcelSeries, identities, inverse)
fidelityW, _ = fidelity_estimation(forward, inverse_w, identities)
fidelityO, _ = fidelity_estimation(forward, inverse, identities)
""" Do network estimation. Get cross-patch PLV values from paired data"""
parcelSeriesPairs, pairs = make_series_paired(n_parcels, n_samples)
_, cp_PLVPW = fidelity_estimation(forward, inverse_w, identities, parcel_series=parcelSeriesPairs)
_, cp_PLVPO = fidelity_estimation(forward, inverse, identities, parcel_series=parcelSeriesPairs)
# Do the cross-patch PLV estimation for unmodeled series
cp_PLVU = np.zeros([n_parcels, n_parcels], dtype=np.complex128)
for t in range(n_samples):
parcelPLVn = parcelSeriesPairs[:,t] / np.abs(parcelSeriesPairs[:,t])
cp_PLVU += np.outer(parcelPLVn, np.conjugate(parcelPLVn)) /n_samples
cp_PLVUim = np.abs(np.imag(cp_PLVU))
# Build truth matrix from pairs.
truthMatrix = np.zeros((n_parcels, n_parcels), dtype=bool)
for i, pair in enumerate(pairs):
truthMatrix[pair[0], pair[1]] = True
truthMatrix[pair[1], pair[0]] = True
# Delete diagonal from truth and estimated matrices
truthMatrix = delete_diagonal(truthMatrix)
cp_PLVPW = delete_diagonal(cp_PLVPW)
cp_PLVPO = delete_diagonal(cp_PLVPO)
# Use imaginary PLV for the estimation.
cp_PLVWim = np.abs(np.imag(cp_PLVPW))
cp_PLVOim = np.abs(np.imag(cp_PLVPO))
## True positive and false positive rate estimation.
tpRateW, fpRateW = get_tp_fp_rates(cp_PLVWim, truthMatrix)
tpRateO, fpRateO = get_tp_fp_rates(cp_PLVOim, truthMatrix)
# Get nearest TP values closest to the FP pair at the "bin" values.
nearTPW = get_nearest_tp_semi_bin(binArray, tpRateW, fpRateW)
nearTPO = get_nearest_tp_semi_bin(binArray, tpRateO, fpRateO)
fidWArray[run_i,:] = fidelityW
fidOArray[run_i,:] = fidelityO
tpWArray[run_i,:] = nearTPW
tpOArray[run_i,:] = nearTPO
sizeArray.append(len(identities)) # Approximate head size with number of sources.
print(f'gain of fidelities. Mean/mean {np.mean(fidWArray)/np.mean(fidOArray)}')
print(f'gain of fidelities. Mean(fidelityW/fidelityO) {np.mean(fidWArray/fidOArray)}')
### Statistics.
fidWAverage = np.average(fidWArray, axis=0)
fidWStd = np.std(fidWArray, axis=0)
fidOAverage = np.average(fidOArray, axis=0)
fidOStd = np.std(fidOArray, axis=0)
tpWAverage = np.average(tpWArray, axis=0)
tpWStd = np.std(tpWArray, axis=0)
tpOAverage = np.average(tpOArray, axis=0)
tpOStd = np.std(tpOArray, axis=0)
### TEMP testing for sort first, then average and SD.
fidWArraySorted = np.sort(fidWArray, axis=1)
fidWAverageSorted = np.average(fidWArraySorted, axis=0)
fidWStdSorted = np.std(fidWArraySorted, axis=0)
fidOArraySorted = np.sort(fidOArray, axis=1)
fidOAverageSorted = np.average(fidOArraySorted, axis=0)
fidOStdSorted = np.std(fidOArraySorted, axis=0)
""" Plots """
# Set global figure parameters, including CorelDraw compatibility (.fonttype)
import matplotlib.pylab as pylab
if tightLayout == True:
params = {'legend.fontsize':'7',
'figure.figsize':(1.6, 1),
'axes.labelsize':'7',
'axes.titlesize':'7',
'xtick.labelsize':'7',
'ytick.labelsize':'7',
'lines.linewidth':'0.5',
'pdf.fonttype':42,
'ps.fonttype':42,
'font.family':'Arial'}
else: # Looks nice on the screen parameters
params = {'legend.fontsize':'7',
'figure.figsize':(3, 2),
'axes.labelsize':'7',
'axes.titlesize':'7',
'xtick.labelsize':'7',
'ytick.labelsize':'7',
'lines.linewidth':'0.5',
'pdf.fonttype':42,
'ps.fonttype':42,
'font.family':'Arial'}
pylab.rcParams.update(params)
parcelList = list(range(0, n_parcels))
""" Plot Fidelities. """
# Sort according to original fidelity
sorting = np.argsort(fidOAverage)
meansWF =
|
pd.DataFrame(fidWAverage[sorting])
|
pandas.DataFrame
|
import warnings
import itertools
from copy import copy
from functools import partial
from collections.abc import Iterable, Sequence, Mapping
from numbers import Number
from datetime import datetime
from distutils.version import LooseVersion
import numpy as np
import pandas as pd
import matplotlib as mpl
from ._decorators import (
share_init_params_with_map,
)
from .palettes import (
QUAL_PALETTES,
color_palette,
cubehelix_palette,
_parse_cubehelix_args,
)
from .utils import (
get_color_cycle,
remove_na,
)
class SemanticMapping:
"""Base class for mapping data values to plot attributes."""
# -- Default attributes that all SemanticMapping subclasses must set
# Whether the mapping is numeric, categorical, or datetime
map_type = None
# Ordered list of unique values in the input data
levels = None
# A mapping from the data values to corresponding plot attributes
lookup_table = None
def __init__(self, plotter):
# TODO Putting this here so we can continue to use a lot of the
# logic that's built into the library, but the idea of this class
# is to move towards semantic mappings that are agnositic about the
# kind of plot they're going to be used to draw.
# Fully achieving that is going to take some thinking.
self.plotter = plotter
def map(cls, plotter, *args, **kwargs):
# This method is assigned the __init__ docstring
method_name = "_{}_map".format(cls.__name__[:-7].lower())
setattr(plotter, method_name, cls(plotter, *args, **kwargs))
return plotter
def _lookup_single(self, key):
"""Apply the mapping to a single data value."""
return self.lookup_table[key]
def __call__(self, key, *args, **kwargs):
"""Get the attribute(s) values for the data key."""
if isinstance(key, (list, np.ndarray, pd.Series)):
return [self._lookup_single(k, *args, **kwargs) for k in key]
else:
return self._lookup_single(key, *args, **kwargs)
@share_init_params_with_map
class HueMapping(SemanticMapping):
"""Mapping that sets artist colors according to data values."""
# A specification of the colors that should appear in the plot
palette = None
# An object that normalizes data values to [0, 1] range for color mapping
norm = None
# A continuous colormap object for interpolating in a numeric context
cmap = None
def __init__(
self, plotter, palette=None, order=None, norm=None,
):
"""Map the levels of the `hue` variable to distinct colors.
Parameters
----------
# TODO add generic parameters
"""
super().__init__(plotter)
data = plotter.plot_data.get("hue",
|
pd.Series(dtype=float)
|
pandas.Series
|
import pandas as pd
import yaml
import requests
import sys
import urllib.parse
from datetime import datetime
from typing import TypeVar, Type
sys.path.append("")
T = TypeVar('T')
from .twitter_objects import TweetQuery
from .tweepy_functions import tweepy_connect, tweepy_get_tweets
from crawler_associated_files.mongodb_conn.connect_mongo import mongo_connect, mongo_insert
def read_auth(auth_path: str) -> str:
with open(auth_path) as f:
key_data = yaml.safe_load(f)
bearer_token = key_data['the-tweet-catcher']['bearer-token']
return bearer_token
def read_mongo_auth(auth_path: str) -> (str, str):
with open(auth_path) as f:
key_data = yaml.safe_load(f)
username = key_data['mongo-db']['username']
passwd = key_data['mongo-db']['passwd']
return (username, passwd)
def get_attr_list(obj: Type[T]):
return [a for a in dir(obj) if not a.startswith('__') and not a.startswith('_')]
def create_url(query: TweetQuery):
# Create attribute list of TweetQuery
base_query = ''
attr_list = get_attr_list(query)
for attribute in attr_list:
attr_value = getattr(query, attribute)
if attr_value is not None and len(base_query) == 0:
base_query += (str(attr_value))
elif attr_value is not None and len(base_query) > 0:
base_query += (' ' + str(attr_value))
base_query += ' lang:en'
parsed_query = urllib.parse.quote(base_query)
url = (f'https://api.twitter.com/2/tweets/search/recent?query={parsed_query}'
f'&max_results={urllib.parse.quote(str(query.max_results))}'
'&tweet.fields=author_id,created_at,lang,conversation_id'
'&expansions=author_id,referenced_tweets.id'
)
print(url)
return url
def create_headers(bearer_token: str):
return {'Authorization': f'Bearer {bearer_token}'}
def connect_to_endpoint(url: str, headers: dict):
response = requests.request("GET", url, headers=headers)
print(response.status_code)
if response.status_code != 200:
raise Exception(response.status_code, response.text)
return response.json()
def get_tweets(username_query: str, auth_path: str, max_result_count: int = 10, next_token: str = None):
bearer_token = read_auth(auth_path)
headers = create_headers(bearer_token)
# Create query
query = TweetQuery()
query.author_username = username_query
# query.text_query = username_query
query.max_results = int(max_result_count)
full_url = create_url(query)
if next_token is not None:
full_url += '&next_token=' + str(next_token)
json_response = connect_to_endpoint(full_url, headers)
return json_response
def process_tweets(json_file):
tweet_list = pd.DataFrame(columns=["username", "text", "created_at"])
if json_file["meta"]["result_count"] == 0:
pass
else:
data_part = pd.DataFrame(json_file["data"])
#data_part = pd.DataFrame(json_file["includes"]["tweets"])
user_part =
|
pd.DataFrame(json_file["includes"]["users"])
|
pandas.DataFrame
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 18 15:52:01 2020
modeling operation.
requirements = [
'matplotlib>=3.1.3',
'sklearn>=0.22.1',
'seaborn>=0.10.0',
'factor_analyzer>=0.3.2',
'joblib>=0.14.1',
]
@author: zoharslong
"""
from numpy import max as np_max, min as np_min, ravel as np_ravel, argsort as np_argsort, abs as np_abs
from numpy import array as np_array, int32 as np_int32, int64 as np_int64, float64 as np_float64
from pandas import DataFrame, concat as pd_concat
from re import findall as re_find
from random import sample as rnd_smp
from os.path import join as os_join
from pyzohar.sub_slt_bsc.bsz import lsz
from pyzohar.sub_slt_bsc.dfz import dfz
import seaborn as sns # plot on factor analysis
from factor_analyzer import FactorAnalyzer, calculate_kmo, calculate_bartlett_sphericity, Rotator
from sklearn import metrics
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.cluster import KMeans
from sklearn.svm import SVC, SVR
from sklearn.svm._classes import SVC as typ_svc, SVR as typ_svr
from sklearn.manifold import TSNE
from matplotlib import pyplot as plt
from joblib import dump as jb_dump, load as jb_load
class mdz_nit(dfz):
"""
modeling class initiation
>>> mdl = mdz_nit(DataFrame(),dfz_mpt=dfz(),dct_mdl={'_id':'','fld':'','clm_x':[],'clm_y':[],'drp':None,'kep':None})
>>> mdl.mdl_nit()
"""
def __init__(self, dts=None, lcn=None, *, spr=False, dfz_mpt=None, dct_mdl=None):
"""
more param of self is available, in [clm_x, clm_y, _x, _y, mdl]
:param dts: self.dts, premier than dfz_mpt
:param lcn: self.lcn, premier than dfz_mpt
:param spr: let self = self.dts
:param dfz_mpt: a dfz for inserted
:param dct_mdl: a dict of params, keys in ['_id', 'fld', 'clm_y', 'clm_x', 'drp', 'kep']
:param dct_mdl: more params are auto generated, in ['fls', 'smp_raw/_y_0/_y_1/_trn/_tst']
"""
if dfz_mpt is not None:
dts = dts if dts is not None else dfz_mpt.dts.copy()
lcn = lcn if lcn is not None else dfz_mpt.lcn.copy()
super(mdz_nit, self).__init__(dts, lcn, spr=spr)
self.clm_x, self.clm_y, self._x, self._y, self.mdl = None, None, None, None, None
self.mdl_nit(dct_mdl=dct_mdl)
def mdl_nit(self, dct_mdl=None, rst=True):
"""
针对model的初始化, 会使用self.dts对self.lcn.mdl的一系列params进行刷新, 通常在self.dts发生变化的时候必须调用
:param dct_mdl: a dict of params, keys in ['_id', 'fld', 'clm_y', 'clm_x', 'drp', 'kep']
:param rst: reset self.lcn.mdl or not, default True
:return: None
"""
if dct_mdl is not None:
mch_tmp = [self.lcn['mdl']['_id'], self.lcn['mdl']['clm_y'], self.lcn['mdl']['clm_x']] if \
'mdl' in self.lcn.keys() else None
dct_mdl['clm_x'] = lsz(dct_mdl['clm_x']).typ_to_lst(rtn=True)
dct_mdl['clm_y'] = lsz(dct_mdl['clm_y']).typ_to_lst(rtn=True)
self.lcn.update({'mdl': dct_mdl})
self.clm_x = self.lcn['mdl']['clm_x']
self.clm_y = self.lcn['mdl']['clm_y']
self.lcn['mdl']['fls'] = 'mdl_' + self.lcn['mdl']['_id'] + '_' + self.lcn['mdl']['clm_y'][0] + '.pkl'
if mch_tmp != [self.lcn['mdl']['_id'], self.lcn['mdl']['clm_y'], self.lcn['mdl']['clm_x']]:
self.mdl, self._x, self._y = None, None, None # 当参数发生较大改变时, 删除已经存在的self.mdl
if rst:
self.mdl_smp_trc()
def mdl_smp_trc(self):
"""
basic sample trace
"""
tmp = dfz(self.dts.copy(), self.lcn.copy())
if tmp.len > 0:
# 标记数据集筛选
if self.lcn['mdl']['drp']:
tmp.drp_dcm_ctt(self.lcn['mdl']['drp'], prm='drop', ndx_rst=False)
if self.lcn['mdl']['kep']:
tmp.drp_dcm_ctt(self.lcn['mdl']['kep'], prm='keep', ndx_rst=False)
# 生成样本参数
self.lcn['mdl']['smp_raw'] = {'ndx': tmp.dts.index.tolist(), 'clm_x': self.clm_x, 'clm_y': self.clm_y}
tmp.drp_dcm_ctt({self.clm_y[0]: 1}, prm='keep', ndx_rst=False)
self.lcn['mdl']['smp_y_1'] = {'ndx': tmp.dts.index.tolist(), 'clm_x': self.clm_x, 'clm_y': self.clm_y}
dff_ndx = lsz().mrg('differ', self.lcn['mdl']['smp_raw']['ndx'], self.lcn['mdl']['smp_y_1']['ndx'],
rtn=True)
self.lcn['mdl']['smp_y_0'] = {'ndx': dff_ndx, 'clm_x': self.clm_x, 'clm_y': self.clm_y}
self._dl_smp_blc() # generate smp_trn, smp_tst
def _dl_smp_blc(self):
"""
train/test sample balanced; 样本平衡策略, 以标志变量中较少的一方为基准, 保持标志平衡, 测试集占比10%
>>> # 另一种既有的训练集划分方法
>>> x_trn, x_tst, y_trn, y_tst = train_test_split(self._x, self._y, test_size=0.2, random_state=2)
"""
smp_min = min(len(self.lcn['mdl']['smp_y_1']['ndx']), len(self.lcn['mdl']['smp_y_0']['ndx']))
ndx_y_0 = rnd_smp(self.lcn['mdl']['smp_y_0']['ndx'], int(smp_min * 0.9))
ndx_y_1 = rnd_smp(self.lcn['mdl']['smp_y_1']['ndx'], int(smp_min * 0.9))
self.lcn['mdl']['smp_trn'] = {'ndx': ndx_y_0 + ndx_y_1, 'clm_x': self.clm_x, 'clm_y': self.clm_y}
ndx_t_0 = lsz().mrg('differ', self.lcn['mdl']['smp_y_0']['ndx'], ndx_y_0, rtn=True)
ndx_t_1 = lsz().mrg('differ', self.lcn['mdl']['smp_y_1']['ndx'], ndx_y_1, rtn=True)
if len(self.lcn['mdl']['smp_y_1']['ndx']) < len(self.lcn['mdl']['smp_y_0']['ndx']):
ndx_t_0 = rnd_smp(ndx_t_0, int(smp_min * 0.1))
else:
ndx_t_1 = rnd_smp(ndx_t_1, int(smp_min * 0.1))
self.lcn['mdl']['smp_tst'] = {'ndx': ndx_t_0 + ndx_t_1, 'clm_x': self.clm_x, 'clm_y': self.clm_y}
def mdl_smp_mpt(self, tgt=None, *, rtn=False):
"""
model sample from param to real datasets, saved in self._x and self._y
:param tgt: in [None, 'smp_raw', 'smp_trn', 'smp_tst']
:param rtn: if return (dtf_y, dtf_x) or not, default False; if return, self._x/_y will not change
:return: if rtn is True, return (dtf_y, dtf_x)
"""
tmp, y, x = dfz(self.dts, self.lcn), None, None
if tmp.len > 0:
if tgt is None: # 无样本集条件,则默认导入self.dts
y, x = tmp.dts[self.clm_y], tmp.dts[self.clm_x]
else: # 否则根据样本集参数选择样本集
tmp.drp_dcm(self.lcn['mdl'][tgt]['ndx'], prm='keep', ndx_rst=False)
y, x = tmp.dts[self.lcn['mdl'][tgt]['clm_y']], tmp.dts[self.lcn['mdl'][tgt]['clm_x']]
if rtn:
return y, x
self._y, self._x = y, x
def mdl_sav(self, *, fld=None, fls=None):
"""
save model into .pkl file
:param fld: default None, get fold location from self.lcn
:param fls: default None, get file location from self.lcn
:return: None
"""
fld = self.lcn['mdl']['fld'] if fld is None else fld
fls = self.lcn['mdl']['fls'] if fls is None else fls
jb_dump(self.mdl, os_join(fld, fls))
def mdl_lod(self, *, fld=None, fls=None):
"""
import model from .pkl file
:param fld: default None, get fold location from self.lcn
:param fls: default None, get file location from self.lcn
:return: None
"""
fld = self.lcn['mdl']['fld'] if fld is None else fld
fls = self.lcn['mdl']['fls'] if fls is None else fls
self.mdl = jb_load(os_join(fld, fls))
str_tmp = self.lcn['mdl']['_id']
self.lcn['mdl']['_id'] = re_find('mdl_(.*?)_' + self.lcn['mdl']['clm_y'][0], self.lcn['mdl']['fls'])[0]
if str_tmp != self.lcn['mdl']['_id']:
print('info: _id switch from %s to %s' % (str_tmp, self.lcn['mdl']['_id']))
def drp_dcm_for_bly(self, flt_smp=2):
"""
drop documents for the balance of Target label. 使用self.clm_y进行样本数量平衡, 会直接导致self.dts的改变
:param flt_smp: 选择数量较多的label进行抽样,使其数量达到flt_smp倍于数量较少的label
:return: None
"""
# 不同分类的样本数量控制
stm_1 = self.dts.loc[self.dts[self.clm_y[0]] == 1]
stm_0 = self.dts.loc[self.dts[self.clm_y[0]] == 0]
shp_0, shp_1 = stm_0.shape[0], stm_1.shape[0]
try:
stm_0 = stm_0.sample(int(shp_1 * flt_smp)) if shp_1*flt_smp < shp_0 else stm_0
stm_1 = stm_1.sample(int(shp_0 * flt_smp)) if shp_0*flt_smp < shp_1 else stm_1
except ValueError:
pass
self.dts = pd_concat([stm_1, stm_0])
self.mdl_nit()
class mdz_fct(mdz_nit):
"""
model factor analysis
聚类的验证 https://blog.csdn.net/u010159842/article/details/78624135
>>> mdl = mdz(DataFrame(),dfz_mpt=dfz(),dct_mdl={'_id':'','fld':'','clm_x':[],'clm_y':[],'drp':None,'kep':None})
>>> mdl.drp_dcm_na(mdl.clm_x) # 删除为空的数据行
>>> mdl.mdl_nit() # 刷新参数集状态, 需要在self.dts发生行列变动时执行
>>> mdl.mdl_smp_mpt() # 根据参数集生成数据集 [None, 'smp_trn', 'smp_tst', 'smp_raw']
>>> mdl.rnd_frs_clf() # 随机森林变量重要性检验
>>> mdl.fct_fit(10, prm='chksav') # 拟合模型 ['chk', 'sav']
>>> mdl.fct_transform(['电话积极','带看高效','上线稳定','电话稳定','在岗稳定','带看稳定']) # 应用模型
"""
def __init__(self, dts=None, lcn=None, *, spr=False, dfz_mpt=None, dct_mdl=None):
"""
more param of self is available, in [clm_x, clm_y, _x, _y, mdl]
:param dts: self.dts, premier than dfz_mpt
:param lcn: self.lcn, premier than dfz_mpt
:param spr: let self = self.dts
:param dfz_mpt: a dfz for inserted
:param dct_mdl: a dict of params, keys in ['_id', 'fld', 'clm_y', 'clm_x', 'drp', 'kep']
:param dct_mdl: more params are auto generated, in ['fls', 'smp_raw/_y_0/_y_1/_trn/_tst']
"""
super(mdz_fct, self).__init__(dts, lcn, spr=spr, dfz_mpt=dfz_mpt, dct_mdl=dct_mdl)
def fct_fit(self, nfc=3, mtd='principal', rtt='varimax', *, prm='chksav'):
"""
factor fit step, to check or save model
:param nfc: number of factors, default 3
:param mtd: method, default 'principal'
:param rtt: rotation method, default 'varimax'
:param prm: in ['chk', 'sav', ''] for [model check, save to file, import self.mdl only]
:return: None
"""
self.mdl = FactorAnalyzer(n_factors=nfc, method=mtd, rotation=rtt)
self.mdl.fit(self._x)
if re_find('chk', prm):
self._ct_fit_chk()
if re_find('sav', prm):
self.mdl_sav()
def _ct_fit_chk(self, prm='kmocmmegnvrnlod'):
"""
几种常见的factor检查方法
:param prm: ['kmo/cmm/egn/vrn/lod'] for kmo, communalities, eigenvalues, variance, load matrix
:return: indicators and pictures in prm
"""
if re_find('kmo', prm):
print('kmo %.4f; bartlett %.4f.' % (self._ct_fit_chk_kmo())) # kmo
if re_find('cmm', prm):
print('communalities: %s' % self.mdl.get_communalities()) # 公因子方差
if re_find('egn', prm):
self._ct_fit_chk_egn() # egn图
if re_find('vrn', prm):
self._ct_fit_chk_vrn() # 因子代表性
if re_find('lod', prm):
self._ct_fit_chk_lod() # 载荷矩阵重要性和命名
def _ct_fit_chk_kmo(self):
"""
kmo检验和巴特利特, 前者要求尽可能大, 后者要求<0.05
:return: [kmo_model, bartlett]
"""
kmo_all, kmo_model = calculate_kmo(self._x)
bartlett = round(calculate_bartlett_sphericity(self._x)[1], 4)
return kmo_model, bartlett
def _ct_fit_chk_egn(self):
"""
eigenvalues to check factor number
:return: a picture of eigenvalues
"""
ev, v = self.mdl.get_eigenvalues() # eigen values 特征值; 通常要求大于1
plt.scatter(range(1, ev.shape[0] + 1), ev)
plt.plot(range(1, ev.shape[0] + 1), ev)
plt.title('Scree Plot')
plt.xlabel('Factors')
plt.ylabel('Eigenvalue')
plt.grid()
plt.show()
def _ct_fit_chk_vrn(self):
"""
variance plot to check factor number
:return: a picture of variance
"""
vrn = self.mdl.get_factor_variance() # 因子的累积贡献度
plt.scatter(range(1, vrn[2].shape[0] + 1), vrn[2])
plt.plot(range(1, vrn[2].shape[0] + 1), vrn[2])
plt.title('Scree Plot')
plt.xlabel('Factors')
plt.ylabel('variance')
plt.grid()
plt.show()
def _ct_fit_chk_lod(self, *, prn=False):
"""
load plot to check factor number
:param prn: save the picture or not, default False
:return: a picture of load matrix
"""
rtr = Rotator()
load_matrix = rtr.fit_transform(self.mdl.loadings_)
sns.set(font="simhei")
df_cm = DataFrame(np_abs(load_matrix), index=self._x.columns)
plt.figure(figsize=(8, 8))
ax = sns.heatmap(df_cm, annot=True, cmap="BuPu")
ax.yaxis.set_tick_params(labelsize=10) # 设置y轴的字体的大小
plt.title('Factor Analysis', fontsize='xx-large')
plt.ylabel('Sepal Width', fontsize='xx-large') # Set y-axis label
plt.show()
if prn:
plt.savefig('factorAnalysis.png', dpi=300)
def fct_transform(self, rnm=None, *, rtn=False):
"""
factor analysis transform by self.mdl, merge factors on the left side of self.dts.
:param rnm: new name of factors in list
:param rtn: if return factors or not, default False
:return: if rtn is True, return factors in type dataframe
"""
if self.mdl is None:
self.mdl_lod()
vrn = self.mdl.get_factor_variance()
dtf_fct = self.mdl.transform(self._x)
# 构造命名
dct_fct = {i: 'fct_' + str(i) for i in range(len(vrn[0]))}
if rnm is not None:
dct_tmp = {i: rnm[i] for i in range(len(rnm))} if type(rnm) in [list] else rnm.copy()
dct_fct.update(dct_tmp)
# 计算总分
lst = []
for i in dtf_fct:
lst.append(sum([i[j] * vrn[1][j] for j in range(len(i))]))
dtf_fnl = DataFrame(dtf_fct, index=self._x.index).rename(columns=dct_fct)
dtf_fnl['scr'] = lst
# 将结果附加的根源数据集self.dts中
self.mrg_dtf(dtf_fnl, prm='outer_index')
if rtn:
return dtf_fnl
class mdz_kmn(mdz_nit):
"""
model factor analysis
>>> mdl = mdz(DataFrame(),dfz_mpt=dfz(),dct_mdl={'_id':'','fld':'','clm_x':[],'clm_y':[],'drp':None,'kep':None})
>>> mdl.mdl_nit({'_id':''}) # 切换某些dct_mdl中的参数需要使用这个句子
>>> mdl.mdl_smp_mpt() # 根据参数集生成数据集 [None, 'smp_trn', 'smp_tst', 'smp_raw']
>>> mdl.kmn_fit([2,6]) # 测试二到六个聚类的效果
>>> mdl.kmn_fit(3, prm='sav') # 经过测试, 确定3格局类最好时对模型进行保存
>>> mdl.kmn_transform('类型') # 应用上一步存档的模型, 对分类变量命名为'类型'
"""
def __init__(self, dts=None, lcn=None, *, spr=False, dfz_mpt=None, dct_mdl=None):
"""
more param of self is available, in [clm_x, clm_y, _x, _y, mdl]
:param dts: self.dts, premier than dfz_mpt
:param lcn: self.lcn, premier than dfz_mpt
:param spr: let self = self.dts
:param dfz_mpt: a dfz for inserted
:param dct_mdl: a dict of params, keys in ['_id', 'fld', 'clm_y', 'clm_x', 'drp', 'kep']
:param dct_mdl: more params are auto generated, in ['fls', 'smp_raw/_y_0/_y_1/_trn/_tst']
"""
super(mdz_kmn, self).__init__(dts, lcn, spr=spr, dfz_mpt=dfz_mpt, dct_mdl=dct_mdl)
def kmn_fit(self, ncl=None, *, prm='sav'):
"""
function the best clusters for k-menas.
:param ncl: iter clusters, default [2,6]
:param prm: in ['sav'] for save .pkl file to local path
@return: None
"""
ncl = lsz(ncl).typ_to_lst(rtn=True) if ncl is not None else [2, 6]
ncl = range(ncl[0], ncl[1]) if len(ncl) == 2 else ncl # [None, [2,4], 3] to [[2,6], [2,4], [3]]
for i in ncl:
self.mdl = KMeans(n_clusters=i, max_iter=1000)
self.mdl.fit(self._x)
y_lbl = self.mdl.labels_
print('cluster %i; inertia %i; silhouette %.4f; calinski_harabasz %i;' % (
i, # cluster number
self.mdl.inertia_, # 距离越小说明簇分的越好
metrics.silhouette_score(self._x, y_lbl, metric='euclidean'), # 越接近1越好, range[-1, 1]
metrics.calinski_harabasz_score(self._x, y_lbl) # 越大越好
))
if prm in ['sav', 'save'] and len(ncl) == 1: # 只有ncl唯一, 非测试环节时方进行保存
self.mdl_sav()
def kmn_transform(self, rnm=None, *, rtn=False):
"""
K-means transform
:param rnm: rename in type str, only one new column need this rename param
:param rtn: return a dataframe or not, default False
:return: if rtn is True, return a dataframe of cluster label
"""
rnm = 'clr' if rnm is None else rnm
if self.mdl is None:
self.mdl_lod()
self.mdl.fit(self._x)
y_lbl = self.mdl.labels_
self.mrg_dtf(DataFrame(y_lbl, columns=[rnm], index=self._x.index), prm='outer_index')
if rtn:
return DataFrame(y_lbl, columns=[rnm], index=self._x.index)
class mdz_tsn(mdz_nit):
"""
model factor analysis
>>> mdl = mdz(DataFrame(),dfz_mpt=dfz(),dct_mdl={'_id':'','fld':'','clm_x':[],'clm_y':[],'drp':None,'kep':None})
>>> mdl.mdl_nit({})
>>> mdl.mdl_smp_mpt('smp_trn') # 根据参数集生成数据集 [None, 'smp_trn', 'smp_tst', 'smp_raw']
>>> mdl.tsn_fit_transform(rnm=['a','b'], prm='savplt')
"""
def __init__(self, dts=None, lcn=None, *, spr=False, dfz_mpt=None, dct_mdl=None):
"""
more param of self is available, in [clm_x, clm_y, _x, _y, mdl]
:param dts: self.dts, premier than dfz_mpt
:param lcn: self.lcn, premier than dfz_mpt
:param spr: let self = self.dts
:param dfz_mpt: a dfz for inserted
:param dct_mdl: a dict of params, keys in ['_id', 'fld', 'clm_y', 'clm_x', 'drp', 'kep']
:param dct_mdl: more params are auto generated, in ['fls', 'smp_raw/_y_0/_y_1/_trn/_tst']
"""
super(mdz_tsn, self).__init__(dts, lcn, spr=spr, dfz_mpt=dfz_mpt, dct_mdl=dct_mdl)
def tsn_fit_transform(self, ncl=None, rnm=None, *, prm='savplt', rtn=False, tsn_init='random', tsn_random_state=0):
"""
t-SNE fit and transform in one step
:param ncl: number of components(factors)
:param rnm: rename new factors in type list,
:param prm: when find 'sav', save local .pkl file; when find 'plt', draw a 2D plot for the result
:param rtn: if return the components in DataFrame or not, default False
:param tsn_init: TSNE param
:param tsn_random_state: TSNE paran
:return: if rtn is True, return the result in a DataFrame
"""
ncl = 2 if ncl is None else ncl
# 构造命名
dct_rnm = {i: 'tsn_' + str(i) for i in range(ncl)}
if rnm is not None:
dct_tmp = {i: rnm[i] for i in range(ncl)} if type(rnm) in [list] else rnm.copy()
dct_rnm.update(dct_tmp)
# 建模环节
self.mdl = TSNE(n_components=ncl, init=tsn_init, random_state=tsn_random_state)
y_ncl = self.mdl.fit_transform(self._x)
y_dtf = DataFrame(y_ncl, index=self._x.index).rename(columns=dct_rnm)
self.mrg_dtf(y_dtf, prm='outer_index')
if re_find('sav', prm): # 保存
self.mdl_sav()
if re_find('plt', prm) and ncl == 2: # 当降维2时输出散点图
self._sn_plt(y_dtf)
if rtn:
return y_dtf
def _sn_plt(self, y_dtf, y_lbl=None):
"""
t-SNE plot in 2D
"""
y_ncl = dfz(y_dtf).dtf_to_typ(typ='list', rtn=True, prm='split')['data']
x_min, x_max = np_min(y_ncl, 0), np_max(y_ncl, 0)
y_tsn = (y_ncl - x_min) / (x_max - x_min) # 范围标准化
y_lbl =
|
DataFrame(self._y)
|
pandas.DataFrame
|
import streamlit as st
import pandas as pd
import numpy as np
import seaborn as sns
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import chi2
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import RobustScaler
from lightgbm import LGBMClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.metrics import f1_score
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
import pickle
st.set_option('deprecation.showPyplotGlobalUse', False)
st.title("Churn Prediction")
st.header('Dataset Selection and Loading')
dataset_name = st.selectbox("Select Datasets", ['Telco_Churn'])
st.write('You selected:', dataset_name, 'dataset')
def get_dataset():
df = pd.read_csv("telecom.csv")
target_column = "Churn"
df["SeniorCitizen"] = df["SeniorCitizen"].replace([0, 1], ['No', 'Yes'])
df["TotalCharges"] = pd.to_numeric(df['TotalCharges'], errors='coerce')
return df, target_column
df, target_column = get_dataset()
df1 = df.copy()
st.subheader('Checking the Dataset')
st.table(df.head())
st.subheader('Types of Variables')
pd.DataFrame(df.dtypes, columns = ["Col"])
st.subheader('Exploratory Data Analysis')
visualization = st.selectbox('Select Visualization Type', ('Pairplot', 'Heatmap'))
if visualization == 'Pairplot':
fig = sns.pairplot(df, hue=target_column)
st.pyplot(fig=fig)
elif visualization == 'Heatmap':
fig, ax = plt.subplots()
sns.heatmap(df.corr(), vmin=-1, cmap='coolwarm', annot=True)
st.pyplot(fig)
st.header('Columns Selection for Analysis')
st.cache()
columns_select = st.selectbox("Select All Columns or Select Columns You Want to Drop",
("All Columns", "Select Columns to Drop"))
if columns_select == "Select Columns to Drop":
d_list = st.multiselect("Please select columns to be dropped", df.columns)
df = df.drop(d_list, axis=1)
if st.button("Generate Codes for Columns to be Dropped"):
if columns_select == "Select Columns to Drop":
st.code(f"""df = df.drop({d_list},axis=1)""")
st.header('Multicollinearity Checking')
threshold = st.selectbox("Select threshold for multicollinearity", (1, 0.9, 0.8, 0.7))
Corr_Columns = []
numeric_cols = df.select_dtypes(exclude=["object"]).columns
def multicollinearity(dataset, threshold):
corr_matrix = dataset.corr()
for i in range(len(corr_matrix.columns)):
for j in range(i):
if abs(corr_matrix.iloc[i, j]) > threshold:
colname = corr_matrix.columns[i]
Corr_Columns.append(colname)
return Corr_Columns
multicollinearity(df, threshold=threshold)
df.drop(Corr_Columns, axis=1, inplace=True)
if len(Corr_Columns) > 0:
st.write(f"{Corr_Columns} columns having correlation value more than {threshold} and therefore dropped")
else:
st.write("No columns found exceeding the threshold")
st.header('Checking Missing Values')
threshold_value = st.selectbox("Select Threshold for Missing Value Checking", (70, 60, 50, 40, 30, 20, 10))
drop_list = []
def missing_drop(df, threshold_value):
for variable in df.columns:
percentage = round((df[variable].isnull().sum() / df[variable].count()) * 10)
if percentage > threshold_value:
st.write(f"The percentage of missing variable for {variable} is % {percentage}")
drop_list.append(variable)
if len(drop_list) == 0:
st.write("No Columns exceeding the Threshold")
missing_drop(df, threshold_value)
st.header('Missing Value Handling')
missing_values = st.selectbox("Select one method for missing value imputation ",
("Drop All Missing Values", "Filling with Either Median or Mode"))
def impute_with_median(df, variable):
if df[variable].isnull().sum() > 0:
st.write(
f"{variable} column has {df[variable].isnull().sum()} missing value and replaced with median:{df[variable].median()}")
df[variable + "NAN"] = np.where(df[variable].isnull(), 1, 0)
df[variable] = df[variable].fillna(df[variable].median())
def impute_with_mode(df, variable):
if df[variable].isnull().sum() > 0:
st.write(
f"{variable} column has {df[variable].isnull().sum()} missing value and replaced {df[variable].mode()[0]}")
df[variable + "NAN"] = np.where(df[variable].isnull(), 1, 0)
frequent = df[variable].mode()[0]
df[variable].fillna(frequent, inplace=True)
if missing_values == "Drop All Missing Values":
for variable in df.columns:
if df[variable].isnull().sum() > 0:
st.write(f"{variable} column has {df[variable].isnull().sum()} missing value")
st.write(f" percentages of total missing data :% {(df.isnull().sum().sum() / df.shape[0]) * 10}")
df.dropna(inplace=True)
else:
for i in df.columns:
if np.dtype(df[i]) == "object":
impute_with_mode(df, i)
else:
impute_with_median(df, i)
st.header('Outliers Detection and Handling')
Handling_Outliers = st.selectbox("Select One Option for Outlier Handling ", ("Keep Outliers", "Handle Outliers"))
numeric_cols = df.select_dtypes(exclude=["object"]).columns
def outliers_detection_handling(df, variable):
IQR = df[variable].quantile(0.75) - df[variable].quantile(0.25)
lower_bound = df[variable].quantile(0.25) - (IQR * 1.5)
upper_bound = df[variable].quantile(0.75) + (IQR * 1.5)
df[variable] = np.where(df[variable] > upper_bound, upper_bound, df[variable])
df[variable] = np.where(df[variable] < lower_bound, lower_bound, df[variable])
return df[variable]
if Handling_Outliers == "Handle Outliers":
for i in numeric_cols:
IQR = df[i].quantile(0.75) - df[i].quantile(0.25)
lower_bound = df[i].quantile(0.25) - (IQR * 1.5)
upper_bound = df[i].quantile(0.75) + (IQR * 1.5)
num_outliers = df[~df[i].between(lower_bound, upper_bound)].value_counts().sum()
if (df[i].max() > upper_bound) | (df[i].min() < lower_bound):
outliers_detection_handling(df, i)
st.write(f"{i} column has {num_outliers} outliers and set to either upper or lower bound.")
else:
st.write("You are keeping all outliers")
st.header('One Hot Encoding')
y = df[target_column]
X = df.drop(target_column, axis=1)
df = X
encode_list = []
def one_hot_encoder(df):
for i in X.columns:
if (np.dtype(df[i]) == "object"):
unique_value = len(df[i].value_counts().sort_values(ascending=False).head(10).index)
if unique_value > 10:
for categories in (df[i].value_counts().sort_values(ascending=False).head(10).index):
df[i + "_" + categories] = np.where(df[i] == categories, 1, 0)
encode_list.append(i + "_" + categories)
else:
for categories in (df[i].value_counts().sort_values(ascending=False).head(unique_value - 1).index):
df[i + "_" + categories] = np.where(df[i] == categories, 1, 0)
encode_list.append(i + "_" + categories)
return df, encode_list
num_cat_col = len(df.select_dtypes(include=["object"]).columns)
one_hot_encoder(df)
for i in df.columns:
if (np.dtype(df[i]) == "object"):
df = df.drop([i], axis=1)
col_after_endoded_all = df.columns
st.write(f"One hot encoding : {num_cat_col} columns are encoded and {len(encode_list)} new columns are added")
st.header('Feature Engineering')
feature_selection = st.selectbox("Feature Selection", ("Keep all Features", "Select Features"))
def feature_importance(endogenous, exogenous, n):
selected_feat = SelectKBest(score_func=chi2, k=10)
selected = selected_feat.fit(endogenous, exogenous)
feature_score = pd.DataFrame(selected.scores_, index=endogenous.columns, columns=["Score"])["Score"].sort_values(
ascending=False).reset_index()
st.write("Table: Feature Importance")
st.table(feature_score.head(n))
st.write("Feature Importance")
plt.figure(figsize=(20, 12))
sns.barplot(data=feature_score.sort_values(by='Score', ascending=False).head(n), x='Score', y='index')
st.pyplot()
X_Selected.extend(feature_score["index"].head(n))
if feature_selection == "Select Features":
st.write()
feature_number = st.slider("Select Number of Features You Want to Observe by Using Slider", 1, df.shape[1])
X_Selected = []
feature_importance(df, y, feature_number)
df = df[X_Selected]
else:
st.write(f"You selected all features and the number of selected features is: {len(df.columns)}")
st.header('Standardization')
standardization = st.selectbox("Standardization", ("No Need to Apply Standardization", "Apply Standardization"))
if standardization == 'Apply Standardization':
methods = st.selectbox("Select one of the Standardization Methods: ",
("StandardScaler", "MinMaxScaler", "RobustScaler"))
num_cols = []
df_new = df1.drop(target_column, axis=1)
numeric_cols = df_new.select_dtypes(exclude=["object"]).columns
for i in numeric_cols:
if i not in df.columns:
pass
else:
num_cols.append(i)
for i in num_cols:
if methods == "StandardScaler":
scaler = StandardScaler()
df[num_cols] = scaler.fit_transform(df[num_cols])
elif methods == "MinMaxScaler":
scaler = MinMaxScaler()
df[num_cols] = scaler.fit_transform(df[num_cols])
else:
scaler = RobustScaler()
df[num_cols] = scaler.fit_transform(df[num_cols])
st.write(f"{num_cols} are scaled by using {methods}")
st.header('Model Evaluation')
models_name = st.sidebar.selectbox("Select Model for ML", ("LightGBM", "Random Forest"))
params = dict()
def parameter_selection(clf_name):
if clf_name == "LightGBM":
st.sidebar.write("Select Parameters")
n_estimators = st.sidebar.slider("n_estimators", 10, 1000, 100, 10)
max_depth = st.sidebar.slider("max_depth", 3, 20,1,1)
learning_rate = st.sidebar.slider('learning_rate', 0.01, 1.0, 0.1, 0.1)
num_leaves = st.sidebar.slider('num_leaves', 10, 300, 31, 10)
params["n_estimators"] = n_estimators
params["max_depth"] = max_depth
params["num_leaves"] = num_leaves
params["learning_rate"] = learning_rate
else:
st.sidebar.write("Select Parameters")
max_depth = st.sidebar.slider("max_depth", 2, 100, 1, 2)
n_estimators = st.sidebar.slider("n_estimators", 50, 1000, 100, 10)
criterion = st.sidebar.selectbox("criterion", ('gini','entropy'))
max_features = st.sidebar.selectbox("max_features", ('auto', 'sqrt', 'log2'))
min_samples_leaf = st.sidebar.slider("min_samples_leaf", 1, 10, 5)
min_samples_split = st.sidebar.slider("min_samples_split", 2, 10)
params["max_depth"] = max_depth
params["n_estimators"] = n_estimators
params["criterion"] = criterion
params["max_features"] = max_features
params["min_samples_leaf"] = min_samples_leaf
params["min_samples_split"] = min_samples_split
a = RandomForestClassifier()
return params
parameter_selection(models_name)
def get_classifier(classifier_name, params):
if classifier_name == "LightGBM":
clf_model = LGBMClassifier(num_leaves=params["num_leaves"], n_estimators=params["n_estimators"], max_depth=params["max_depth"], learning_rate=params["learning_rate"], random_state=42)
else:
clf_model = RandomForestClassifier(n_estimators=params["n_estimators"], max_depth=params["max_depth"],
criterion=params["criterion"], max_features=params["max_features"],
min_samples_leaf=params["min_samples_leaf"],
min_samples_split=params["min_samples_split"], random_state=42)
return clf_model
clf_model = get_classifier(models_name, params)
st.cache()
X_train, X_test, y_train, y_test = train_test_split(df, y, test_size=0.2, random_state=42)
clf_model.fit(X_train, y_train)
y_pred = clf_model.predict(X_test)
acc = accuracy_score(y_test, y_pred)
f1_scr = f1_score(y_test, y_pred, average='macro')
cls_report = classification_report(y_test, y_pred)
cnf_matrix = confusion_matrix(y_test, y_pred)
st.sidebar.write(f"Selected Classifier = {models_name}")
st.sidebar.write(f"Accuracy Score = {acc}")
st.write(f"Selected Classifier = {models_name}")
st.write(f"Accuracy Score = {acc}")
st.subheader('Confusion Matrix')
st.table(cnf_matrix)
st.subheader('Classification Report')
st.text('Classification Report:\n ' + cls_report)
st.header('Model Download')
st.cache()
def download_model(model):
pickle.dump(clf_model, open("final_model", 'wb'))
download_model(clf_model)
st.write(f'Trained model is saved as final_model for later use')
st.header('Churn Probability of Customers')
if st.button("Prediction Probality of Top 10 Churned Customers"):
col_val = ['0', '1']
a = clf_model.predict_proba(X_test)
b = pd.DataFrame(data=a, columns=col_val)
sorted_val = b.sort_values(by='0', ascending=False)
st.table(sorted_val.head(10))
if st.button("Prediction Probality of Top 20 Loyal Customers"):
col_val = ['0', '1']
a = clf_model.predict_proba(X_test)
b = pd.DataFrame(data=a, columns=col_val)
sorted_val = b.sort_values(by='0')
st.table(sorted_val.head(20))
st.header('Prediction')
st.subheader("Please select your variables to predict")
st.write('Please **do not leave** Tenure, Montly Charges, and Total Charges columns **empty**')
df1.drop(target_column, axis=1, inplace=True)
df1.drop('customerID', axis=1, inplace=True)
columns = df1.columns
cat_columns = df1.select_dtypes(include=["object"]).columns
dftest =
|
pd.DataFrame()
|
pandas.DataFrame
|
import json
import pandas as pd
# weather Stations
with open("data\demokritos\\raw\weather_station.json") as f:
data = json.load(f)
columns = data["results"][0]["series"][0]["columns"]
values = data["results"][0]["series"][0]["values"]
df = pd.DataFrame(values, columns=columns)
df = df.drop(["packets"], axis=1)
dfs = dict(tuple(df.groupby("id")))
my_dict = {}
for id in df.id.unique():
my_dict[id] = dfs[id]
my_dict[id]["time"] = pd.to_datetime(my_dict[id]["time"], utc=True)
my_dict[id]["time"] = my_dict[id]["time"].dt.tz_convert("Europe/Athens")
my_dict[id]["time"] = my_dict[id]["time"].dt.round("1min")
my_dict[id]["time"] = pd.to_datetime(my_dict[id]["time"])
my_dict[id].set_index("time", inplace=True)
my_dict[id].to_csv(
"data\demokritos\\refined\weather_station_" + id + ".csv"
)
my_dict[id] = my_dict[id].resample("1H").sum()
my_dict[id].to_csv(
"data\demokritos\\resampled\weather_station_" + id + ".csv"
)
# HM_LHLM06 Controller
with open("data\demokritos\\raw\HM_LHLM06.json") as f:
data = json.load(f)
columns = data["results"][0]["series"][0]["columns"]
values = data["results"][0]["series"][0]["values"]
df = pd.DataFrame(values, columns=columns)
dfs = dict(tuple(df.groupby("id")))
my_dict = {}
for id in df.id.unique():
my_dict[id] = dfs[id]
my_dict[id]["time"] =
|
pd.to_datetime(my_dict[id]["time"], utc=True)
|
pandas.to_datetime
|
import pandas
import numpy
import warnings
import scipy.stats
from sklearn.linear_model import LinearRegression as _LinearRegression
from sklearn.feature_selection import mutual_info_regression
from sklearn.base import clone
from sklearn.metrics import r2_score
from .frameable import FrameableMixin
from .model_selection import CrossValMixin
class LinearRegression(_LinearRegression, FrameableMixin, CrossValMixin):
"""
Ordinary least squares Linear Regression.
This class extends the LinearRegression provided in scikit-learn.
Parameters
----------
fit_intercept : boolean, optional, default True
whether to calculate the intercept for this model. If set
to False, no intercept will be used in calculations
(e.g. data is expected to be already centered).
normalize : boolean, optional, default False
This parameter is ignored when ``fit_intercept`` is set to False.
If True, the regressors X will be normalized before regression by
subtracting the mean and dividing by the l2-norm.
If you wish to standardize, please use
:class:`sklearn.preprocessing.StandardScaler` before calling ``fit`` on
an estimator with ``normalize=False``.
copy_X : boolean, optional, default True
If True, X will be copied; else, it may be overwritten.
n_jobs : int or None, optional (default=None)
The number of jobs to use for the computation. This will only provide
speedup for n_targets > 1 and sufficient large problems.
``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
``-1`` means using all processors. See :term:`Glossary <n_jobs>`
for more details.
Attributes
----------
coef_ : array, shape (n_features, ) or (n_targets, n_features)
Estimated coefficients for the linear regression problem.
If multiple targets are passed during the fit (y 2D), this
is a 2D array of shape (n_targets, n_features), while if only
one target is passed, this is a 1D array of length n_features.
intercept_ : array
Independent term in the linear model.
"""
def __init__(
self,
fit_intercept=True,
normalize=False,
copy_X=True,
n_jobs=None,
stats_on_fit=True,
):
super().__init__(
fit_intercept=fit_intercept,
normalize=normalize,
copy_X=copy_X,
n_jobs=n_jobs
)
self.stats_on_fit = stats_on_fit
def fit(self, X, y, sample_weight=None):
self._pre_fit(X, y)
super().fit(X, y, sample_weight=sample_weight)
if self.stats_on_fit:
if isinstance(X, pandas.DataFrame):
self._X_columns = list(X.columns)
elif isinstance(X, pandas.Series):
self._X_columns = [str(X.name),]
else:
self._X_columns = None
sse = numpy.sum((self.predict(X) - y) ** 2, axis=0) / float(X.shape[0] - X.shape[1])
if sse.shape == ():
sse = sse.reshape(1,)
self.sse_ = sse
if self.fit_intercept:
if not isinstance(X, pandas.DataFrame):
X1 = pandas.DataFrame(X)
else:
X1 = X.copy(deep=True)
X1['__constant__'] = 1.0
else:
X1 = X
try:
inv_X_XT = numpy.linalg.inv(numpy.dot(X1.T, X1))
except numpy.linalg.LinAlgError:
inv_X_XT = numpy.full_like(numpy.dot(X1.T, X1), fill_value=numpy.nan)
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=RuntimeWarning)
try:
se = numpy.array([
numpy.sqrt(numpy.diagonal(sse[i] * inv_X_XT))
for i in range(sse.shape[0])
])
except:
print("sse.shape",sse.shape)
print(sse)
raise
if self.fit_intercept:
self.stderr_ = se[:,:-1]
self.t_ = self.coef_ / se[:,:-1]
self.stderr_intercept_ = se[:,-1]
self.t_intercept_ = self.intercept_ / se[:,-1]
else:
self.stderr_ = se
self.t_ = self.coef_ / se
self.p_ = 2 * (1 - scipy.stats.t.cdf(numpy.abs(self.t_), y.shape[0] - X.shape[1]))
if self.fit_intercept:
self.p_intercept_ = 2 * (1 - scipy.stats.t.cdf(numpy.abs(self.t_intercept_), y.shape[0] - X.shape[1]))
r2 = r2_score(y, self.predict(X), sample_weight=sample_weight, multioutput='raw_values')
if isinstance(self._Y_columns, str):
self.r2 = pandas.Series(r2, index=[self._Y_columns,])
elif isinstance(self._Y_columns, list):
self.r2 =
|
pandas.Series(r2, index=self._Y_columns)
|
pandas.Series
|
from arche import arche, SH_URL
from arche.arche import Arche
from arche.rules.result import Level
from conftest import create_result
import pandas as pd
import pytest
def test_target_equals_source():
with pytest.raises(ValueError) as excinfo:
Arche(source="0/0/1", target="0/0/1")
assert (
str(excinfo.value)
== "'target' is equal to 'source'. Data to compare should have different sources."
)
def test_target_items(mocker, get_job_items):
mocker.patch("arche.Arche.get_items", return_value=get_job_items)
arche = Arche("source", target="target")
assert arche.target_items is get_job_items
assert arche._target_items is get_job_items
assert arche.target_items is get_job_items
def test_target_items_none(mocker):
arche = Arche("source")
assert arche.target_items is None
def test_arche_df(get_df):
a = Arche(source=get_df, target=get_df)
|
pd.testing.assert_frame_equal(a.source_items.df, get_df)
|
pandas.testing.assert_frame_equal
|
from flask import render_template, flash, redirect, url_for, request, Flask, jsonify, send_from_directory
from app import app, db, ImmigrationToolBox, DataWizardTools
from app.models import User, Post
from app.forms import PostForm
from werkzeug.urls import url_parse
from datetime import datetime
import pandas as pd
@app.route("/IOIimmQuarterly", methods=['GET', 'POST'])
def upload_IOIimmQuarterly():
if request.method == 'POST':
print(request.files['file'])
f = request.files['file']
test = pd.read_excel(f)
test.fillna('',inplace=True)
#Cleaning
if test.iloc[0][0] == '':
df = pd.read_excel(f,skiprows=2)
else:
df =
|
pd.read_excel(f)
|
pandas.read_excel
|
'''
Backtest the strategies.
'''
import os
import sys
import argparse
import pandas as pd
import numpy as np
import util
from strategy import *
def print_orders(orders, stock_data, indent=1):
'''
Print the order in human-readable format. For debug purpose
'''
for code, quantity in orders.items():
price = stock_data[code]['CLOSE']
if quantity > 0:
print('\t' * indent + f"Bought {quantity} shares of {code} @ {price}")
elif quantity < 0:
quantity = -quantity
print('\t' * indent + f"Sold/shorted {quantity} shares of {code} @ {price}")
def print_config(config):
'''
Print the key configurations for backtesting.
'''
backtesting_start = config.get('BACKTESTING_START', '?')
backtesting_end = config.get('BACKTESTING_END', '?')
exit_threshold = config.get('EXIT_THRESHOLD', '?')
enter_threshold = config.get('ENTER_THRESHOLD', '?')
enter2_threshold = config.get('ENTER2_THRESHOLD', '?')
enter3_threshold = config.get('ENTER3_THRESHOLD', '?')
stop_threshold = config.get('STOP_THRESHOLD', '?')
enter_allocation = config.get('ENTER_ALLOCATION', '?')
enter2_allocation = config.get('ENTER2_ALLOCATION', '?')
enter3_allocation = config.get('ENTER3_ALLOCATION', '?')
max_leverage = config.get('MAX_LEVERAGE', '?')
print(f"Back-testing period=from {backtesting_start} to {backtesting_end}")
print(f"enter={enter_threshold}, {enter2_threshold}, {enter3_threshold}, stop={stop_threshold}, exit={exit_threshold}")
print(f"max_leverage={max_leverage}, allocations={enter_allocation}, {enter2_allocation}, {enter3_allocation}")
def cash_change(orders, stock_data, tx_cost_per_share=0, tx_cost_per_dollar=0):
'''
Calculate the change of cash as a result of a series of orders.
Use the latest daily close price of the stocks as the settlement price.
For now, accept any order with no margin requirement (you can buy/short however much you want).
'''
change = 0
for code, quantity in orders.items():
if not code in stock_data:
raise Exception("Stock data not found for " + code)
settlement_price = stock_data[code]['CLOSE']
# If quantity > 0, it means buying the instrument, so cash goes down. Vice versa.
tx_amount = -settlement_price * int(quantity)
change += tx_amount
# Apply SEC's fee (per dollar amount)
change -= abs(tx_amount) * tx_cost_per_dollar
# Apply broker's fee (per share)
change -= quantity * tx_cost_per_share
return round(change, 2)
def net_worth(positions, stock_data):
'''
Calculate the network of the positions.
'''
worth = 0
for code, quantity in positions.items():
if not code in stock_data:
raise Exception("Stock data not found for " + code)
settlement_price = stock_data[code]['CLOSE']
worth += settlement_price * int(quantity)
return round(worth, 2)
def evaluate(strategy, config):
'''
Evaluate the strategy.
Returns a dict of performace metrics
'''
training_start = config['TRAINING_START']
training_end = config['TRAINING_END']
backtesting_start = config['BACKTESTING_START']
backtesting_end = config['BACKTESTING_END']
initial_cash = float(config['INITIAL_CASH'])
max_leverage = float(config['MAX_LEVERAGE'])
tx_cost_per_share = float(config['TX_COST_PER_SHARE'])
tx_cost_per_dollar = float(config['TX_COST_PER_DOLLAR'])
risk_free_rate = float(config['RISK_FREE_RATE']) * (pd.to_datetime(backtesting_end) - pd.to_datetime(backtesting_start)).days / 360
# Prepare the data for the strategy
stock_codes = set()
for pair in strategy.pairs:
stock_codes.add(pair.X)
stock_codes.add(pair.Y)
stock_data = util.load_stock_data(config['STOCK_DATA_FOLDER'], list(stock_codes))
strategy.feed(stock_data)
strategy.analyze_spread(training_start, training_end)
strategy.allocate_money(initial_cash * max_leverage)
cash = initial_cash
daily_tnw = []
leverages = []
# Advance the timeline day by day
testing_dates = [d for d in list(stock_data.values())[0].index if backtesting_start <= d and d <= backtesting_end]
testing_dates.sort()
for date in testing_dates:
strategy.now(date)
# Get and execute orders for the day
orders = strategy.decide()
stock_data_single_day = {}
for code, df in stock_data.items():
stock_data_single_day[code] = df.loc[date]
cash += cash_change(orders, stock_data_single_day)
# Update the orders in strategy
strategy.positions(orders, incremental=True)
# Record the net worth and return
total_net_worth = cash + net_worth(strategy.positions(), stock_data_single_day)
# Calculate the leverage
market_value = cash
for stock, quantity in strategy.positions().items():
if quantity > 0:
market_value += quantity * stock_data_single_day[stock]['CLOSE']
leverage = market_value / total_net_worth
leverages.append(leverage)
daily_tnw.append(total_net_worth)
# Calculate the values for the performance metrics
daily_return = []
prev_tnw = initial_cash
for tnw in daily_tnw:
daily_return.append(tnw / prev_tnw - 1)
prev_tnw = tnw
df_metrics = pd.DataFrame({
"tnw": daily_tnw,
"ret": daily_return
})
final_return = daily_tnw[-1] / initial_cash - 1
daily_tnw_aug = [initial_cash] + daily_tnw
ret_std = df_metrics['ret'].std()
performance_metrics = {
"Final Return": final_return,
"Volatility": ret_std,
"Sharpe Ratio": (final_return - risk_free_rate) / ret_std if ret_std > 0 else np.nan,
"Up Percentage": len([r for r in daily_return if r > 0]) / len(daily_return),
"Max Drawdown": (min(daily_tnw_aug) - max(daily_tnw_aug)) / max(daily_tnw_aug),
"Skewness": df_metrics['ret'].skew(),
"Kurtosis": df_metrics['ret'].kurt(),
"Avg Leverage": sum(leverages) / len(leverages),
"Max Leverage": max(leverages)
}
return performance_metrics
def evaluate_cumulative_pairs(pairs, config, lower=None, upper=None, tx_log=False):
'''
Evaluate pairs cumulatively of a portfolio.
Returns a pandas DataFrame Object contains the evaluation result.
'''
thresholds = [
float(config["EXIT_THRESHOLD"]),
float(config["ENTER_THRESHOLD"]),
float(config["ENTER2_THRESHOLD"]),
float(config["ENTER3_THRESHOLD"]),
float(config["STOP_THRESHOLD"])
]
allocations = [
float(config["ENTER_ALLOCATION"]),
float(config["ENTER2_ALLOCATION"]),
float(config["ENTER3_ALLOCATION"])
]
if lower is None:
lower = [1, 1]
lower_start = int(lower[0])
lower_end = int(lower[1]) if len(lower) > 1 else lower_start
if upper is None:
upper = [len(pairs), len(pairs)]
upper_start = int(upper[0])
upper_end = int(upper[1]) if len(upper) > 1 else upper_start
pairs_original = pairs
columns = None
df_result = pd.DataFrame()
for s in range(lower_start - 1, lower_end):
for e in range(upper_start, upper_end + 1):
pairs = pairs_original[s : e]
strategy = PairTradeStrategy(pairs, thresholds, allocations)
results = evaluate(strategy, config)
if tx_log:
results = strategy.transaction_history()
if columns is None:
columns = ['Start Pair', 'End Pair'] + list(results.keys())
if not tx_log:
print(*columns, sep='\t')
df_result =
|
pd.DataFrame(columns=columns)
|
pandas.DataFrame
|
#Based on https://www.kaggle.com/tezdhar/wordbatch-with-memory-test
import gc
import time
import numpy as np
import pandas as pd
from scipy.sparse import csr_matrix, hstack
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.preprocessing import LabelBinarizer
from sklearn.model_selection import train_test_split
import psutil
import os
import wordbatch
from wordbatch.extractors import WordBag
from wordbatch.models import FTRL, FM_FTRL
from nltk.corpus import stopwords
import re
def rmsle(y, y0):
assert len(y) == len(y0)
return np.sqrt(np.mean(np.power(np.log1p(y) - np.log1p(y0), 2)))
def handle_missing_inplace(dataset):
dataset['description'].fillna(value='na', inplace=True)
dataset["image"].fillna("noinformation", inplace=True)
dataset["param_1"].fillna("nicapotato", inplace=True)
dataset["param_2"].fillna("nicapotato", inplace=True)
dataset["param_3"].fillna("nicapotato", inplace=True)
dataset['image_top_1'].fillna(value=-1, inplace=True)
dataset['price'].fillna(value=0, inplace=True)
def to_categorical(dataset):
dataset['param_1'] = dataset['param_1'].astype('category')
dataset['param_2'] = dataset['param_2'].astype('category')
dataset['param_3'] = dataset['param_3'].astype('category')
dataset['image_top_1'] = dataset['image_top_1'].astype('category')
dataset['image'] = dataset['image'].astype('category')
dataset['price'] = dataset['price'].astype('category')
#counting
dataset['num_desc_punct'] = dataset['num_desc_punct'].astype('category')
dataset['num_desc_capE'] = dataset['num_desc_capE'].astype('category')
dataset['num_desc_capP'] = dataset['num_desc_capP'].astype('category')
dataset['num_title_punct'] = dataset['num_title_punct'].astype('category')
dataset['num_title_capE'] = dataset['num_title_capE'].astype('category')
dataset['num_title_capP'] = dataset['num_title_capP'].astype('category')
dataset['is_in_desc_хорошо'] = dataset['is_in_desc_хорошо'].astype('category')
dataset['is_in_desc_Плохо'] = dataset['is_in_desc_Плохо'].astype('category')
dataset['is_in_desc_новый'] = dataset['is_in_desc_новый'].astype('category')
dataset['is_in_desc_старый'] = dataset['is_in_desc_старый'].astype('category')
dataset['is_in_desc_используемый'] = dataset['is_in_desc_используемый'].astype('category')
dataset['is_in_desc_есплатная_доставка'] = dataset['is_in_desc_есплатная_доставка'].astype('category')
dataset['is_in_desc_есплатный_возврат'] = dataset['is_in_desc_есплатный_возврат'].astype('category')
dataset['is_in_desc_идеально'] = dataset['is_in_desc_идеально'].astype('category')
dataset['is_in_desc_подержанный'] = dataset['is_in_desc_подержанный'].astype('category')
dataset['is_in_desc_пСниженные_цены'] = dataset['is_in_desc_пСниженные_цены'].astype('category')
#region
dataset['region'] = dataset['region'].astype('category')
dataset['city'] = dataset['city'].astype('category')
dataset['user_type'] = dataset['user_type'].astype('category')
dataset['category_name'] = dataset['category_name'].astype('category')
dataset['parent_category_name'] = dataset['parent_category_name'].astype('category')
# dataset['price+'] = dataset['price+'].astype('category')
# dataset['desc_len'] = dataset['desc_len'].astype('category')
# dataset['title_len'] = dataset['title_len'].astype('category')
# dataset['title_desc_len_ratio'] = dataset['title_desc_len_ratio'].astype('category')
# dataset['desc_word_count'] = dataset['desc_word_count'].astype('category')
# dataset['mean_des'] = dataset['mean_des'].astype('category')
# Define helpers for text normalization
stopwords = {x: 1 for x in stopwords.words('russian')}
non_alphanums = re.compile(u'[^A-Za-z0-9]+')
def normalize_text(text):
# if np.isnan(text): text='na'
return u" ".join(
[x for x in [y for y in non_alphanums.sub(' ', text).lower().strip().split(" ")] \
if len(x) > 1 and x not in stopwords])
develop = True
# develop= False
if __name__ == '__main__':
start_time = time.time()
from time import gmtime, strftime
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
import re
from scipy.sparse import hstack
from nltk.corpus import stopwords
from contextlib import contextmanager
@contextmanager
def timer(name):
t0 = time.time()
yield
print('[{}] done in {:.0f} s'.format(name, (time.time() - t0)))
import string
print(strftime("%Y-%m-%d %H:%M:%S", gmtime()))
print("\nData Load Stage")
# , nrows = nrows
nrows=10000*1
training = pd.read_csv('../input/train.csv', index_col="item_id", parse_dates=["activation_date"])
len_train = len(training)
traindex = training.index
testing = pd.read_csv('../input/test.csv', index_col="item_id", parse_dates=["activation_date"])
testdex = testing.index
# labels = training['deal_probability'].values
y = training.deal_probability.copy()
training.drop("deal_probability", axis=1, inplace=True)
# suppl
# used_cols = ["item_id", "user_id"]
# train_active = pd.read_csv("../input/train_active.csv", usecols=used_cols)
# test_active = pd.read_csv("../input/test_active.csv", usecols=used_cols)
# train_periods = pd.read_csv("../input/periods_train.csv", parse_dates=["date_from", "date_to"])
# test_periods = pd.read_csv("../input/periods_test.csv", parse_dates=["date_from", "date_to"])
# =============================================================================
# Add region-income
# =============================================================================
tmp = pd.read_csv("../input/region_income.csv", sep=";", names=["region", "income"])
training = training.merge(tmp, on="region", how="left")
testing = testing.merge(tmp, on="region", how="left")
del tmp;
gc.collect()
# =============================================================================
# Add region-income
# =============================================================================
tmp = pd.read_csv("../input/city_population_wiki_v3.csv",)
training = training.merge(tmp, on="city", how="left")
testing = testing.merge(tmp, on="city", how="left")
del tmp;
gc.collect()
import pickle
with open('../input/train_image_features.p', 'rb') as f:
x = pickle.load(f)
train_blurinesses = x['blurinesses']
train_ids = x['ids']
with open('../input/test_image_features.p', 'rb') as f:
x = pickle.load(f)
test_blurinesses = x['blurinesses']
test_ids = x['ids']
del x;
gc.collect()
incep_train_image_df = pd.DataFrame(train_blurinesses, columns=['blurinesses'])
incep_test_image_df = pd.DataFrame(test_blurinesses, columns=[f'blurinesses'])
incep_train_image_df['image'] = (train_ids)
incep_test_image_df['image'] = (test_ids)
training = training.join(incep_train_image_df.set_index('image'), on='image')
testing = testing.join(incep_test_image_df.set_index('image'), on='image')
print('adding whitenesses ...')
with open('../input/train_image_features.p', 'rb') as f:
x = pickle.load(f)
train_whitenesses = x['whitenesses']
train_ids = x['ids']
with open('../input/test_image_features.p', 'rb') as f:
x = pickle.load(f)
test_whitenesses = x['whitenesses']
test_ids = x['ids']
del x;
gc.collect()
incep_train_image_df = pd.DataFrame(train_whitenesses, columns=['whitenesses'])
incep_test_image_df = pd.DataFrame(test_whitenesses, columns=[f'whitenesses'])
incep_train_image_df['image'] = (train_ids)
incep_test_image_df['image'] = (test_ids)
training = training.join(incep_train_image_df.set_index('image'), on='image')
testing = testing.join(incep_test_image_df.set_index('image'), on='image')
print('adding dullnesses ...')
with open('../input/train_image_features.p', 'rb') as f:
x = pickle.load(f)
train_dullnesses = x['dullnesses']
train_ids = x['ids']
with open('../input/test_image_features.p', 'rb') as f:
x = pickle.load(f)
test_dullnesses = x['dullnesses']
test_ids = x['ids']
del x;
gc.collect()
incep_train_image_df = pd.DataFrame(train_dullnesses, columns=['dullnesses'])
incep_test_image_df = pd.DataFrame(test_dullnesses, columns=[f'dullnesses'])
incep_train_image_df['image'] = (train_ids)
incep_test_image_df['image'] = (test_ids)
training = training.join(incep_train_image_df.set_index('image'), on='image')
testing = testing.join(incep_test_image_df.set_index('image'), on='image')
print('adding average_pixel_width ...')
with open('../input/train_image_features_1.p', 'rb') as f:
x = pickle.load(f)
train_average_pixel_width = x['average_pixel_width']
train_ids = x['ids']
with open('../input/test_image_features_1.p', 'rb') as f:
x = pickle.load(f)
test_average_pixel_width = x['average_pixel_width']
test_ids = x['ids']
del x;
gc.collect()
incep_train_image_df = pd.DataFrame(train_average_pixel_width, columns=['average_pixel_width'])
incep_test_image_df = pd.DataFrame(test_average_pixel_width, columns=[f'average_pixel_width'])
incep_train_image_df['image'] = (train_ids)
incep_test_image_df['image'] = (test_ids)
training = training.join(incep_train_image_df.set_index('image'), on='image')
testing = testing.join(incep_test_image_df.set_index('image'), on='image')
print('adding average_reds ...')
with open('../input/train_image_features_1.p', 'rb') as f:
x = pickle.load(f)
train_average_reds = x['average_reds']
train_ids = x['ids']
with open('../input/test_image_features_1.p', 'rb') as f:
x = pickle.load(f)
test_average_reds = x['average_reds']
test_ids = x['ids']
del x;
gc.collect()
incep_train_image_df = pd.DataFrame(train_average_reds, columns=['average_reds'])
incep_test_image_df = pd.DataFrame(test_average_reds, columns=[f'average_reds'])
incep_train_image_df['image'] = (train_ids)
incep_test_image_df['image'] = (test_ids)
training = training.join(incep_train_image_df.set_index('image'), on='image')
testing = testing.join(incep_test_image_df.set_index('image'), on='image')
print('adding average_blues ...')
with open('../input/train_image_features_1.p', 'rb') as f:
x = pickle.load(f)
train_average_blues = x['average_blues']
train_ids = x['ids']
with open('../input/test_image_features_1.p', 'rb') as f:
x = pickle.load(f)
test_average_blues = x['average_blues']
test_ids = x['ids']
del x;
gc.collect()
incep_train_image_df =
|
pd.DataFrame(train_average_blues, columns=['average_blues'])
|
pandas.DataFrame
|
import math
import queue
from datetime import datetime, timedelta, timezone
import pandas as pd
from storey import build_flow, SyncEmitSource, Reduce, Table, AggregateByKey, FieldAggregator, NoopDriver, \
DataframeSource
from storey.dtypes import SlidingWindows, FixedWindows, EmitAfterMaxEvent, EmitEveryEvent
test_base_time = datetime.fromisoformat("2020-07-21T21:40:00+00:00")
def append_return(lst, x):
lst.append(x)
return lst
def test_sliding_window_simple_aggregation_flow():
controller = build_flow([
SyncEmitSource(),
AggregateByKey([FieldAggregator("number_of_stuff", "col1", ["sum", "avg", "min", "max"],
SlidingWindows(['1h', '2h', '24h'], '10m'))],
Table("test", NoopDriver())),
Reduce([], lambda acc, x: append_return(acc, x)),
]).run()
for i in range(10):
data = {'col1': i}
controller.emit(data, 'tal', test_base_time + timedelta(minutes=25 * i))
controller.terminate()
actual = controller.await_termination()
expected_results = [
{'col1': 0, 'number_of_stuff_sum_1h': 0, 'number_of_stuff_sum_2h': 0, 'number_of_stuff_sum_24h': 0, 'number_of_stuff_min_1h': 0,
'number_of_stuff_min_2h': 0, 'number_of_stuff_min_24h': 0, 'number_of_stuff_max_1h': 0, 'number_of_stuff_max_2h': 0,
'number_of_stuff_max_24h': 0, 'number_of_stuff_avg_1h': 0.0, 'number_of_stuff_avg_2h': 0.0, 'number_of_stuff_avg_24h': 0.0},
{'col1': 1, 'number_of_stuff_sum_1h': 1, 'number_of_stuff_sum_2h': 1, 'number_of_stuff_sum_24h': 1, 'number_of_stuff_min_1h': 0,
'number_of_stuff_min_2h': 0, 'number_of_stuff_min_24h': 0, 'number_of_stuff_max_1h': 1, 'number_of_stuff_max_2h': 1,
'number_of_stuff_max_24h': 1, 'number_of_stuff_avg_1h': 0.5, 'number_of_stuff_avg_2h': 0.5, 'number_of_stuff_avg_24h': 0.5},
{'col1': 2, 'number_of_stuff_sum_1h': 3, 'number_of_stuff_sum_2h': 3, 'number_of_stuff_sum_24h': 3, 'number_of_stuff_min_1h': 0,
'number_of_stuff_min_2h': 0, 'number_of_stuff_min_24h': 0, 'number_of_stuff_max_1h': 2, 'number_of_stuff_max_2h': 2,
'number_of_stuff_max_24h': 2, 'number_of_stuff_avg_1h': 1.0, 'number_of_stuff_avg_2h': 1.0, 'number_of_stuff_avg_24h': 1.0},
{'col1': 3, 'number_of_stuff_sum_1h': 6, 'number_of_stuff_sum_2h': 6, 'number_of_stuff_sum_24h': 6, 'number_of_stuff_min_1h': 1,
'number_of_stuff_min_2h': 0, 'number_of_stuff_min_24h': 0, 'number_of_stuff_max_1h': 3, 'number_of_stuff_max_2h': 3,
'number_of_stuff_max_24h': 3, 'number_of_stuff_avg_1h': 2.0, 'number_of_stuff_avg_2h': 1.5, 'number_of_stuff_avg_24h': 1.5},
{'col1': 4, 'number_of_stuff_sum_1h': 9, 'number_of_stuff_sum_2h': 10, 'number_of_stuff_sum_24h': 10, 'number_of_stuff_min_1h': 2,
'number_of_stuff_min_2h': 0, 'number_of_stuff_min_24h': 0, 'number_of_stuff_max_1h': 4, 'number_of_stuff_max_2h': 4,
'number_of_stuff_max_24h': 4, 'number_of_stuff_avg_1h': 3.0, 'number_of_stuff_avg_2h': 2.0, 'number_of_stuff_avg_24h': 2.0},
{'col1': 5, 'number_of_stuff_sum_1h': 12, 'number_of_stuff_sum_2h': 15, 'number_of_stuff_sum_24h': 15, 'number_of_stuff_min_1h': 3,
'number_of_stuff_min_2h': 1, 'number_of_stuff_min_24h': 0, 'number_of_stuff_max_1h': 5, 'number_of_stuff_max_2h': 5,
'number_of_stuff_max_24h': 5, 'number_of_stuff_avg_1h': 4.0, 'number_of_stuff_avg_2h': 3.0, 'number_of_stuff_avg_24h': 2.5},
{'col1': 6, 'number_of_stuff_sum_1h': 15, 'number_of_stuff_sum_2h': 20, 'number_of_stuff_sum_24h': 21, 'number_of_stuff_min_1h': 4,
'number_of_stuff_min_2h': 2, 'number_of_stuff_min_24h': 0, 'number_of_stuff_max_1h': 6, 'number_of_stuff_max_2h': 6,
'number_of_stuff_max_24h': 6, 'number_of_stuff_avg_1h': 5.0, 'number_of_stuff_avg_2h': 4.0, 'number_of_stuff_avg_24h': 3.0},
{'col1': 7, 'number_of_stuff_sum_1h': 18, 'number_of_stuff_sum_2h': 25, 'number_of_stuff_sum_24h': 28, 'number_of_stuff_min_1h': 5,
'number_of_stuff_min_2h': 3, 'number_of_stuff_min_24h': 0, 'number_of_stuff_max_1h': 7, 'number_of_stuff_max_2h': 7,
'number_of_stuff_max_24h': 7, 'number_of_stuff_avg_1h': 6.0, 'number_of_stuff_avg_2h': 5.0, 'number_of_stuff_avg_24h': 3.5},
{'col1': 8, 'number_of_stuff_sum_1h': 21, 'number_of_stuff_sum_2h': 30, 'number_of_stuff_sum_24h': 36, 'number_of_stuff_min_1h': 6,
'number_of_stuff_min_2h': 4, 'number_of_stuff_min_24h': 0, 'number_of_stuff_max_1h': 8, 'number_of_stuff_max_2h': 8,
'number_of_stuff_max_24h': 8, 'number_of_stuff_avg_1h': 7.0, 'number_of_stuff_avg_2h': 6.0, 'number_of_stuff_avg_24h': 4.0},
{'col1': 9, 'number_of_stuff_sum_1h': 24, 'number_of_stuff_sum_2h': 35, 'number_of_stuff_sum_24h': 45, 'number_of_stuff_min_1h': 7,
'number_of_stuff_min_2h': 5, 'number_of_stuff_min_24h': 0, 'number_of_stuff_max_1h': 9, 'number_of_stuff_max_2h': 9,
'number_of_stuff_max_24h': 9, 'number_of_stuff_avg_1h': 8.0, 'number_of_stuff_avg_2h': 7.0, 'number_of_stuff_avg_24h': 4.5}
]
assert actual == expected_results, \
f'actual did not match expected. \n actual: {actual} \n expected: {expected_results}'
def test_sliding_window_sparse_data():
controller = build_flow([
SyncEmitSource(),
AggregateByKey(
[FieldAggregator("number_of_stuff1", "col1", ["sum", "avg", "min", "max"], SlidingWindows(['1h', '2h', '24h'], '10m')),
FieldAggregator("number_of_stuff2", "col2", ["sum", "avg", "min", "max"], SlidingWindows(['1h', '2h', '24h'], '10m'))],
Table("test", NoopDriver())),
Reduce([], lambda acc, x: append_return(acc, x)),
]).run()
for i in range(10):
controller.emit({'col1': i}, 'tal', test_base_time + timedelta(minutes=25 * i))
controller.emit({'col2': i}, 'tal', test_base_time + timedelta(minutes=25 * i))
controller.terminate()
actual = controller.await_termination()
expected_results = [{'col1': 0, 'number_of_stuff1_avg_1h': 0.0, 'number_of_stuff1_avg_24h': 0.0, 'number_of_stuff1_avg_2h': 0.0,
'number_of_stuff1_max_1h': 0, 'number_of_stuff1_max_24h': 0, 'number_of_stuff1_max_2h': 0,
'number_of_stuff1_min_1h': 0, 'number_of_stuff1_min_24h': 0, 'number_of_stuff1_min_2h': 0,
'number_of_stuff1_sum_1h': 0, 'number_of_stuff1_sum_24h': 0, 'number_of_stuff1_sum_2h': 0,
'number_of_stuff2_avg_1h': math.nan, 'number_of_stuff2_avg_24h': math.nan, 'number_of_stuff2_avg_2h': math.nan,
'number_of_stuff2_max_1h': math.nan, 'number_of_stuff2_max_24h': math.nan, 'number_of_stuff2_max_2h': math.nan,
'number_of_stuff2_min_1h': math.nan, 'number_of_stuff2_min_24h': math.nan, 'number_of_stuff2_min_2h': math.nan,
'number_of_stuff2_sum_1h': 0, 'number_of_stuff2_sum_24h': 0, 'number_of_stuff2_sum_2h': 0},
{'col2': 0, 'number_of_stuff1_avg_1h': 0.0, 'number_of_stuff1_avg_24h': 0.0, 'number_of_stuff1_avg_2h': 0.0,
'number_of_stuff1_max_1h': 0, 'number_of_stuff1_max_24h': 0, 'number_of_stuff1_max_2h': 0,
'number_of_stuff1_min_1h': 0, 'number_of_stuff1_min_24h': 0, 'number_of_stuff1_min_2h': 0,
'number_of_stuff1_sum_1h': 0, 'number_of_stuff1_sum_24h': 0, 'number_of_stuff1_sum_2h': 0,
'number_of_stuff2_avg_1h': 0.0, 'number_of_stuff2_avg_24h': 0.0, 'number_of_stuff2_avg_2h': 0.0,
'number_of_stuff2_max_1h': 0, 'number_of_stuff2_max_24h': 0, 'number_of_stuff2_max_2h': 0,
'number_of_stuff2_min_1h': 0, 'number_of_stuff2_min_24h': 0, 'number_of_stuff2_min_2h': 0,
'number_of_stuff2_sum_1h': 0, 'number_of_stuff2_sum_24h': 0, 'number_of_stuff2_sum_2h': 0},
{'col1': 1, 'number_of_stuff1_avg_1h': 0.5, 'number_of_stuff1_avg_24h': 0.5, 'number_of_stuff1_avg_2h': 0.5,
'number_of_stuff1_max_1h': 1, 'number_of_stuff1_max_24h': 1, 'number_of_stuff1_max_2h': 1,
'number_of_stuff1_min_1h': 0, 'number_of_stuff1_min_24h': 0, 'number_of_stuff1_min_2h': 0,
'number_of_stuff1_sum_1h': 1, 'number_of_stuff1_sum_24h': 1, 'number_of_stuff1_sum_2h': 1,
'number_of_stuff2_avg_1h': 0.0, 'number_of_stuff2_avg_24h': 0.0, 'number_of_stuff2_avg_2h': 0.0,
'number_of_stuff2_max_1h': 0, 'number_of_stuff2_max_24h': 0, 'number_of_stuff2_max_2h': 0,
'number_of_stuff2_min_1h': 0, 'number_of_stuff2_min_24h': 0, 'number_of_stuff2_min_2h': 0,
'number_of_stuff2_sum_1h': 0, 'number_of_stuff2_sum_24h': 0, 'number_of_stuff2_sum_2h': 0},
{'col2': 1, 'number_of_stuff1_avg_1h': 0.5, 'number_of_stuff1_avg_24h': 0.5, 'number_of_stuff1_avg_2h': 0.5,
'number_of_stuff1_max_1h': 1, 'number_of_stuff1_max_24h': 1, 'number_of_stuff1_max_2h': 1,
'number_of_stuff1_min_1h': 0, 'number_of_stuff1_min_24h': 0, 'number_of_stuff1_min_2h': 0,
'number_of_stuff1_sum_1h': 1, 'number_of_stuff1_sum_24h': 1, 'number_of_stuff1_sum_2h': 1,
'number_of_stuff2_avg_1h': 0.5, 'number_of_stuff2_avg_24h': 0.5, 'number_of_stuff2_avg_2h': 0.5,
'number_of_stuff2_max_1h': 1, 'number_of_stuff2_max_24h': 1, 'number_of_stuff2_max_2h': 1,
'number_of_stuff2_min_1h': 0, 'number_of_stuff2_min_24h': 0, 'number_of_stuff2_min_2h': 0,
'number_of_stuff2_sum_1h': 1, 'number_of_stuff2_sum_24h': 1, 'number_of_stuff2_sum_2h': 1},
{'col1': 2, 'number_of_stuff1_avg_1h': 1.0, 'number_of_stuff1_avg_24h': 1.0, 'number_of_stuff1_avg_2h': 1.0,
'number_of_stuff1_max_1h': 2, 'number_of_stuff1_max_24h': 2, 'number_of_stuff1_max_2h': 2,
'number_of_stuff1_min_1h': 0, 'number_of_stuff1_min_24h': 0, 'number_of_stuff1_min_2h': 0,
'number_of_stuff1_sum_1h': 3, 'number_of_stuff1_sum_24h': 3, 'number_of_stuff1_sum_2h': 3,
'number_of_stuff2_avg_1h': 0.5, 'number_of_stuff2_avg_24h': 0.5, 'number_of_stuff2_avg_2h': 0.5,
'number_of_stuff2_max_1h': 1, 'number_of_stuff2_max_24h': 1, 'number_of_stuff2_max_2h': 1,
'number_of_stuff2_min_1h': 0, 'number_of_stuff2_min_24h': 0, 'number_of_stuff2_min_2h': 0,
'number_of_stuff2_sum_1h': 1, 'number_of_stuff2_sum_24h': 1, 'number_of_stuff2_sum_2h': 1},
{'col2': 2, 'number_of_stuff1_avg_1h': 1.0, 'number_of_stuff1_avg_24h': 1.0, 'number_of_stuff1_avg_2h': 1.0,
'number_of_stuff1_max_1h': 2, 'number_of_stuff1_max_24h': 2, 'number_of_stuff1_max_2h': 2,
'number_of_stuff1_min_1h': 0, 'number_of_stuff1_min_24h': 0, 'number_of_stuff1_min_2h': 0,
'number_of_stuff1_sum_1h': 3, 'number_of_stuff1_sum_24h': 3, 'number_of_stuff1_sum_2h': 3,
'number_of_stuff2_avg_1h': 1.0, 'number_of_stuff2_avg_24h': 1.0, 'number_of_stuff2_avg_2h': 1.0,
'number_of_stuff2_max_1h': 2, 'number_of_stuff2_max_24h': 2, 'number_of_stuff2_max_2h': 2,
'number_of_stuff2_min_1h': 0, 'number_of_stuff2_min_24h': 0, 'number_of_stuff2_min_2h': 0,
'number_of_stuff2_sum_1h': 3, 'number_of_stuff2_sum_24h': 3, 'number_of_stuff2_sum_2h': 3},
{'col1': 3, 'number_of_stuff1_avg_1h': 2.0, 'number_of_stuff1_avg_24h': 1.5, 'number_of_stuff1_avg_2h': 1.5,
'number_of_stuff1_max_1h': 3, 'number_of_stuff1_max_24h': 3, 'number_of_stuff1_max_2h': 3,
'number_of_stuff1_min_1h': 1, 'number_of_stuff1_min_24h': 0, 'number_of_stuff1_min_2h': 0,
'number_of_stuff1_sum_1h': 6, 'number_of_stuff1_sum_24h': 6, 'number_of_stuff1_sum_2h': 6,
'number_of_stuff2_avg_1h': 1.0, 'number_of_stuff2_avg_24h': 1.0, 'number_of_stuff2_avg_2h': 1.0,
'number_of_stuff2_max_1h': 2, 'number_of_stuff2_max_24h': 2, 'number_of_stuff2_max_2h': 2,
'number_of_stuff2_min_1h': 0, 'number_of_stuff2_min_24h': 0, 'number_of_stuff2_min_2h': 0,
'number_of_stuff2_sum_1h': 3, 'number_of_stuff2_sum_24h': 3, 'number_of_stuff2_sum_2h': 3},
{'col2': 3, 'number_of_stuff1_avg_1h': 2.0, 'number_of_stuff1_avg_24h': 1.5, 'number_of_stuff1_avg_2h': 1.5,
'number_of_stuff1_max_1h': 3, 'number_of_stuff1_max_24h': 3, 'number_of_stuff1_max_2h': 3,
'number_of_stuff1_min_1h': 1, 'number_of_stuff1_min_24h': 0, 'number_of_stuff1_min_2h': 0,
'number_of_stuff1_sum_1h': 6, 'number_of_stuff1_sum_24h': 6, 'number_of_stuff1_sum_2h': 6,
'number_of_stuff2_avg_1h': 2.0, 'number_of_stuff2_avg_24h': 1.5, 'number_of_stuff2_avg_2h': 1.5,
'number_of_stuff2_max_1h': 3, 'number_of_stuff2_max_24h': 3, 'number_of_stuff2_max_2h': 3,
'number_of_stuff2_min_1h': 1, 'number_of_stuff2_min_24h': 0, 'number_of_stuff2_min_2h': 0,
'number_of_stuff2_sum_1h': 6, 'number_of_stuff2_sum_24h': 6, 'number_of_stuff2_sum_2h': 6},
{'col1': 4, 'number_of_stuff1_avg_1h': 3.0, 'number_of_stuff1_avg_24h': 2.0, 'number_of_stuff1_avg_2h': 2.0,
'number_of_stuff1_max_1h': 4, 'number_of_stuff1_max_24h': 4, 'number_of_stuff1_max_2h': 4,
'number_of_stuff1_min_1h': 2, 'number_of_stuff1_min_24h': 0, 'number_of_stuff1_min_2h': 0,
'number_of_stuff1_sum_1h': 9, 'number_of_stuff1_sum_24h': 10, 'number_of_stuff1_sum_2h': 10,
'number_of_stuff2_avg_1h': 2.0, 'number_of_stuff2_avg_24h': 1.5, 'number_of_stuff2_avg_2h': 1.5,
'number_of_stuff2_max_1h': 3, 'number_of_stuff2_max_24h': 3, 'number_of_stuff2_max_2h': 3,
'number_of_stuff2_min_1h': 1, 'number_of_stuff2_min_24h': 0, 'number_of_stuff2_min_2h': 0,
'number_of_stuff2_sum_1h': 6, 'number_of_stuff2_sum_24h': 6, 'number_of_stuff2_sum_2h': 6},
{'col2': 4, 'number_of_stuff1_avg_1h': 3.0, 'number_of_stuff1_avg_24h': 2.0, 'number_of_stuff1_avg_2h': 2.0,
'number_of_stuff1_max_1h': 4, 'number_of_stuff1_max_24h': 4, 'number_of_stuff1_max_2h': 4,
'number_of_stuff1_min_1h': 2, 'number_of_stuff1_min_24h': 0, 'number_of_stuff1_min_2h': 0,
'number_of_stuff1_sum_1h': 9, 'number_of_stuff1_sum_24h': 10, 'number_of_stuff1_sum_2h': 10,
'number_of_stuff2_avg_1h': 3.0, 'number_of_stuff2_avg_24h': 2.0, 'number_of_stuff2_avg_2h': 2.0,
'number_of_stuff2_max_1h': 4, 'number_of_stuff2_max_24h': 4, 'number_of_stuff2_max_2h': 4,
'number_of_stuff2_min_1h': 2, 'number_of_stuff2_min_24h': 0, 'number_of_stuff2_min_2h': 0,
'number_of_stuff2_sum_1h': 9, 'number_of_stuff2_sum_24h': 10, 'number_of_stuff2_sum_2h': 10},
{'col1': 5, 'number_of_stuff1_avg_1h': 4.0, 'number_of_stuff1_avg_24h': 2.5, 'number_of_stuff1_avg_2h': 3.0,
'number_of_stuff1_max_1h': 5, 'number_of_stuff1_max_24h': 5, 'number_of_stuff1_max_2h': 5,
'number_of_stuff1_min_1h': 3, 'number_of_stuff1_min_24h': 0, 'number_of_stuff1_min_2h': 1,
'number_of_stuff1_sum_1h': 12, 'number_of_stuff1_sum_24h': 15, 'number_of_stuff1_sum_2h': 15,
'number_of_stuff2_avg_1h': 3.0, 'number_of_stuff2_avg_24h': 2.0, 'number_of_stuff2_avg_2h': 2.0,
'number_of_stuff2_max_1h': 4, 'number_of_stuff2_max_24h': 4, 'number_of_stuff2_max_2h': 4,
'number_of_stuff2_min_1h': 2, 'number_of_stuff2_min_24h': 0, 'number_of_stuff2_min_2h': 0,
'number_of_stuff2_sum_1h': 9, 'number_of_stuff2_sum_24h': 10, 'number_of_stuff2_sum_2h': 10},
{'col2': 5, 'number_of_stuff1_avg_1h': 4.0, 'number_of_stuff1_avg_24h': 2.5, 'number_of_stuff1_avg_2h': 3.0,
'number_of_stuff1_max_1h': 5, 'number_of_stuff1_max_24h': 5, 'number_of_stuff1_max_2h': 5,
'number_of_stuff1_min_1h': 3, 'number_of_stuff1_min_24h': 0, 'number_of_stuff1_min_2h': 1,
'number_of_stuff1_sum_1h': 12, 'number_of_stuff1_sum_24h': 15, 'number_of_stuff1_sum_2h': 15,
'number_of_stuff2_avg_1h': 4.0, 'number_of_stuff2_avg_24h': 2.5, 'number_of_stuff2_avg_2h': 3.0,
'number_of_stuff2_max_1h': 5, 'number_of_stuff2_max_24h': 5, 'number_of_stuff2_max_2h': 5,
'number_of_stuff2_min_1h': 3, 'number_of_stuff2_min_24h': 0, 'number_of_stuff2_min_2h': 1,
'number_of_stuff2_sum_1h': 12, 'number_of_stuff2_sum_24h': 15, 'number_of_stuff2_sum_2h': 15},
{'col1': 6, 'number_of_stuff1_avg_1h': 5.0, 'number_of_stuff1_avg_24h': 3.0, 'number_of_stuff1_avg_2h': 4.0,
'number_of_stuff1_max_1h': 6, 'number_of_stuff1_max_24h': 6, 'number_of_stuff1_max_2h': 6,
'number_of_stuff1_min_1h': 4, 'number_of_stuff1_min_24h': 0, 'number_of_stuff1_min_2h': 2,
'number_of_stuff1_sum_1h': 15, 'number_of_stuff1_sum_24h': 21, 'number_of_stuff1_sum_2h': 20,
'number_of_stuff2_avg_1h': 4.0, 'number_of_stuff2_avg_24h': 2.5, 'number_of_stuff2_avg_2h': 3.0,
'number_of_stuff2_max_1h': 5, 'number_of_stuff2_max_24h': 5, 'number_of_stuff2_max_2h': 5,
'number_of_stuff2_min_1h': 3, 'number_of_stuff2_min_24h': 0, 'number_of_stuff2_min_2h': 1,
'number_of_stuff2_sum_1h': 12, 'number_of_stuff2_sum_24h': 15, 'number_of_stuff2_sum_2h': 15},
{'col2': 6, 'number_of_stuff1_avg_1h': 5.0, 'number_of_stuff1_avg_24h': 3.0, 'number_of_stuff1_avg_2h': 4.0,
'number_of_stuff1_max_1h': 6, 'number_of_stuff1_max_24h': 6, 'number_of_stuff1_max_2h': 6,
'number_of_stuff1_min_1h': 4, 'number_of_stuff1_min_24h': 0, 'number_of_stuff1_min_2h': 2,
'number_of_stuff1_sum_1h': 15, 'number_of_stuff1_sum_24h': 21, 'number_of_stuff1_sum_2h': 20,
'number_of_stuff2_avg_1h': 5.0, 'number_of_stuff2_avg_24h': 3.0, 'number_of_stuff2_avg_2h': 4.0,
'number_of_stuff2_max_1h': 6, 'number_of_stuff2_max_24h': 6, 'number_of_stuff2_max_2h': 6,
'number_of_stuff2_min_1h': 4, 'number_of_stuff2_min_24h': 0, 'number_of_stuff2_min_2h': 2,
'number_of_stuff2_sum_1h': 15, 'number_of_stuff2_sum_24h': 21, 'number_of_stuff2_sum_2h': 20},
{'col1': 7, 'number_of_stuff1_avg_1h': 6.0, 'number_of_stuff1_avg_24h': 3.5, 'number_of_stuff1_avg_2h': 5.0,
'number_of_stuff1_max_1h': 7, 'number_of_stuff1_max_24h': 7, 'number_of_stuff1_max_2h': 7,
'number_of_stuff1_min_1h': 5, 'number_of_stuff1_min_24h': 0, 'number_of_stuff1_min_2h': 3,
'number_of_stuff1_sum_1h': 18, 'number_of_stuff1_sum_24h': 28, 'number_of_stuff1_sum_2h': 25,
'number_of_stuff2_avg_1h': 5.0, 'number_of_stuff2_avg_24h': 3.0, 'number_of_stuff2_avg_2h': 4.0,
'number_of_stuff2_max_1h': 6, 'number_of_stuff2_max_24h': 6, 'number_of_stuff2_max_2h': 6,
'number_of_stuff2_min_1h': 4, 'number_of_stuff2_min_24h': 0, 'number_of_stuff2_min_2h': 2,
'number_of_stuff2_sum_1h': 15, 'number_of_stuff2_sum_24h': 21, 'number_of_stuff2_sum_2h': 20},
{'col2': 7, 'number_of_stuff1_avg_1h': 6.0, 'number_of_stuff1_avg_24h': 3.5, 'number_of_stuff1_avg_2h': 5.0,
'number_of_stuff1_max_1h': 7, 'number_of_stuff1_max_24h': 7, 'number_of_stuff1_max_2h': 7,
'number_of_stuff1_min_1h': 5, 'number_of_stuff1_min_24h': 0, 'number_of_stuff1_min_2h': 3,
'number_of_stuff1_sum_1h': 18, 'number_of_stuff1_sum_24h': 28, 'number_of_stuff1_sum_2h': 25,
'number_of_stuff2_avg_1h': 6.0, 'number_of_stuff2_avg_24h': 3.5, 'number_of_stuff2_avg_2h': 5.0,
'number_of_stuff2_max_1h': 7, 'number_of_stuff2_max_24h': 7, 'number_of_stuff2_max_2h': 7,
'number_of_stuff2_min_1h': 5, 'number_of_stuff2_min_24h': 0, 'number_of_stuff2_min_2h': 3,
'number_of_stuff2_sum_1h': 18, 'number_of_stuff2_sum_24h': 28, 'number_of_stuff2_sum_2h': 25},
{'col1': 8, 'number_of_stuff1_avg_1h': 7.0, 'number_of_stuff1_avg_24h': 4.0, 'number_of_stuff1_avg_2h': 6.0,
'number_of_stuff1_max_1h': 8, 'number_of_stuff1_max_24h': 8, 'number_of_stuff1_max_2h': 8,
'number_of_stuff1_min_1h': 6, 'number_of_stuff1_min_24h': 0, 'number_of_stuff1_min_2h': 4,
'number_of_stuff1_sum_1h': 21, 'number_of_stuff1_sum_24h': 36, 'number_of_stuff1_sum_2h': 30,
'number_of_stuff2_avg_1h': 6.0, 'number_of_stuff2_avg_24h': 3.5, 'number_of_stuff2_avg_2h': 5.0,
'number_of_stuff2_max_1h': 7, 'number_of_stuff2_max_24h': 7, 'number_of_stuff2_max_2h': 7,
'number_of_stuff2_min_1h': 5, 'number_of_stuff2_min_24h': 0, 'number_of_stuff2_min_2h': 3,
'number_of_stuff2_sum_1h': 18, 'number_of_stuff2_sum_24h': 28, 'number_of_stuff2_sum_2h': 25},
{'col2': 8, 'number_of_stuff1_avg_1h': 7.0, 'number_of_stuff1_avg_24h': 4.0, 'number_of_stuff1_avg_2h': 6.0,
'number_of_stuff1_max_1h': 8, 'number_of_stuff1_max_24h': 8, 'number_of_stuff1_max_2h': 8,
'number_of_stuff1_min_1h': 6, 'number_of_stuff1_min_24h': 0, 'number_of_stuff1_min_2h': 4,
'number_of_stuff1_sum_1h': 21, 'number_of_stuff1_sum_24h': 36, 'number_of_stuff1_sum_2h': 30,
'number_of_stuff2_avg_1h': 7.0, 'number_of_stuff2_avg_24h': 4.0, 'number_of_stuff2_avg_2h': 6.0,
'number_of_stuff2_max_1h': 8, 'number_of_stuff2_max_24h': 8, 'number_of_stuff2_max_2h': 8,
'number_of_stuff2_min_1h': 6, 'number_of_stuff2_min_24h': 0, 'number_of_stuff2_min_2h': 4,
'number_of_stuff2_sum_1h': 21, 'number_of_stuff2_sum_24h': 36, 'number_of_stuff2_sum_2h': 30},
{'col1': 9, 'number_of_stuff1_avg_1h': 8.0, 'number_of_stuff1_avg_24h': 4.5, 'number_of_stuff1_avg_2h': 7.0,
'number_of_stuff1_max_1h': 9, 'number_of_stuff1_max_24h': 9, 'number_of_stuff1_max_2h': 9,
'number_of_stuff1_min_1h': 7, 'number_of_stuff1_min_24h': 0, 'number_of_stuff1_min_2h': 5,
'number_of_stuff1_sum_1h': 24, 'number_of_stuff1_sum_24h': 45, 'number_of_stuff1_sum_2h': 35,
'number_of_stuff2_avg_1h': 7.0, 'number_of_stuff2_avg_24h': 4.0, 'number_of_stuff2_avg_2h': 6.0,
'number_of_stuff2_max_1h': 8, 'number_of_stuff2_max_24h': 8, 'number_of_stuff2_max_2h': 8,
'number_of_stuff2_min_1h': 6, 'number_of_stuff2_min_24h': 0, 'number_of_stuff2_min_2h': 4,
'number_of_stuff2_sum_1h': 21, 'number_of_stuff2_sum_24h': 36, 'number_of_stuff2_sum_2h': 30},
{'col2': 9, 'number_of_stuff1_avg_1h': 8.0, 'number_of_stuff1_avg_24h': 4.5, 'number_of_stuff1_avg_2h': 7.0,
'number_of_stuff1_max_1h': 9, 'number_of_stuff1_max_24h': 9, 'number_of_stuff1_max_2h': 9,
'number_of_stuff1_min_1h': 7, 'number_of_stuff1_min_24h': 0, 'number_of_stuff1_min_2h': 5,
'number_of_stuff1_sum_1h': 24, 'number_of_stuff1_sum_24h': 45, 'number_of_stuff1_sum_2h': 35,
'number_of_stuff2_avg_1h': 8.0, 'number_of_stuff2_avg_24h': 4.5, 'number_of_stuff2_avg_2h': 7.0,
'number_of_stuff2_max_1h': 9, 'number_of_stuff2_max_24h': 9, 'number_of_stuff2_max_2h': 9,
'number_of_stuff2_min_1h': 7, 'number_of_stuff2_min_24h': 0, 'number_of_stuff2_min_2h': 5,
'number_of_stuff2_sum_1h': 24, 'number_of_stuff2_sum_24h': 45, 'number_of_stuff2_sum_2h': 35}]
assert actual == expected_results, \
f'actual did not match expected. \n actual: {actual} \n expected: {expected_results}'
def test_sliding_window_sparse_data_uneven_feature_occurrence():
controller = build_flow([
SyncEmitSource(),
AggregateByKey(
[FieldAggregator("number_of_stuff1", "col1", ["sum", "avg", "min", "max"], SlidingWindows(['1h', '2h', '24h'], '10m')),
FieldAggregator("number_of_stuff2", "col2", ["sum", "avg", "min", "max"], SlidingWindows(['1h', '2h', '24h'], '10m'))],
Table("test", NoopDriver())),
Reduce([], lambda acc, x: append_return(acc, x)),
]).run()
controller.emit({'col1': 0}, 'tal', test_base_time)
for i in range(10):
controller.emit({'col2': i}, 'tal', test_base_time + timedelta(minutes=25 * i))
controller.terminate()
actual = controller.await_termination()
expected_results = [{'col1': 0, 'number_of_stuff1_avg_1h': 0.0, 'number_of_stuff1_avg_24h': 0.0, 'number_of_stuff1_avg_2h': 0.0,
'number_of_stuff1_max_1h': 0, 'number_of_stuff1_max_24h': 0, 'number_of_stuff1_max_2h': 0,
'number_of_stuff1_min_1h': 0, 'number_of_stuff1_min_24h': 0, 'number_of_stuff1_min_2h': 0,
'number_of_stuff1_sum_1h': 0, 'number_of_stuff1_sum_24h': 0, 'number_of_stuff1_sum_2h': 0,
'number_of_stuff2_avg_1h': math.nan, 'number_of_stuff2_avg_24h': math.nan, 'number_of_stuff2_avg_2h': math.nan,
'number_of_stuff2_max_1h': math.nan, 'number_of_stuff2_max_24h': math.nan, 'number_of_stuff2_max_2h': math.nan,
'number_of_stuff2_min_1h': math.nan, 'number_of_stuff2_min_24h': math.nan, 'number_of_stuff2_min_2h': math.nan,
'number_of_stuff2_sum_1h': 0, 'number_of_stuff2_sum_24h': 0, 'number_of_stuff2_sum_2h': 0},
{'col2': 0, 'number_of_stuff1_avg_1h': 0.0, 'number_of_stuff1_avg_24h': 0.0, 'number_of_stuff1_avg_2h': 0.0,
'number_of_stuff1_max_1h': 0, 'number_of_stuff1_max_24h': 0, 'number_of_stuff1_max_2h': 0,
'number_of_stuff1_min_1h': 0, 'number_of_stuff1_min_24h': 0, 'number_of_stuff1_min_2h': 0,
'number_of_stuff1_sum_1h': 0, 'number_of_stuff1_sum_24h': 0, 'number_of_stuff1_sum_2h': 0,
'number_of_stuff2_avg_1h': 0.0, 'number_of_stuff2_avg_24h': 0.0, 'number_of_stuff2_avg_2h': 0.0,
'number_of_stuff2_max_1h': 0, 'number_of_stuff2_max_24h': 0, 'number_of_stuff2_max_2h': 0,
'number_of_stuff2_min_1h': 0, 'number_of_stuff2_min_24h': 0, 'number_of_stuff2_min_2h': 0,
'number_of_stuff2_sum_1h': 0, 'number_of_stuff2_sum_24h': 0, 'number_of_stuff2_sum_2h': 0},
{'col2': 1, 'number_of_stuff1_avg_1h': 0.0, 'number_of_stuff1_avg_24h': 0.0, 'number_of_stuff1_avg_2h': 0.0,
'number_of_stuff1_max_1h': 0, 'number_of_stuff1_max_24h': 0, 'number_of_stuff1_max_2h': 0,
'number_of_stuff1_min_1h': 0, 'number_of_stuff1_min_24h': 0, 'number_of_stuff1_min_2h': 0,
'number_of_stuff1_sum_1h': 0, 'number_of_stuff1_sum_24h': 0, 'number_of_stuff1_sum_2h': 0,
'number_of_stuff2_avg_1h': 0.5, 'number_of_stuff2_avg_24h': 0.5, 'number_of_stuff2_avg_2h': 0.5,
'number_of_stuff2_max_1h': 1, 'number_of_stuff2_max_24h': 1, 'number_of_stuff2_max_2h': 1,
'number_of_stuff2_min_1h': 0, 'number_of_stuff2_min_24h': 0, 'number_of_stuff2_min_2h': 0,
'number_of_stuff2_sum_1h': 1, 'number_of_stuff2_sum_24h': 1, 'number_of_stuff2_sum_2h': 1},
{'col2': 2, 'number_of_stuff1_avg_1h': 0.0, 'number_of_stuff1_avg_24h': 0.0, 'number_of_stuff1_avg_2h': 0.0,
'number_of_stuff1_max_1h': 0, 'number_of_stuff1_max_24h': 0, 'number_of_stuff1_max_2h': 0,
'number_of_stuff1_min_1h': 0, 'number_of_stuff1_min_24h': 0, 'number_of_stuff1_min_2h': 0,
'number_of_stuff1_sum_1h': 0, 'number_of_stuff1_sum_24h': 0, 'number_of_stuff1_sum_2h': 0,
'number_of_stuff2_avg_1h': 1.0, 'number_of_stuff2_avg_24h': 1.0, 'number_of_stuff2_avg_2h': 1.0,
'number_of_stuff2_max_1h': 2, 'number_of_stuff2_max_24h': 2, 'number_of_stuff2_max_2h': 2,
'number_of_stuff2_min_1h': 0, 'number_of_stuff2_min_24h': 0, 'number_of_stuff2_min_2h': 0,
'number_of_stuff2_sum_1h': 3, 'number_of_stuff2_sum_24h': 3, 'number_of_stuff2_sum_2h': 3},
{'col2': 3, 'number_of_stuff1_avg_1h': 0.0, 'number_of_stuff1_avg_24h': 0.0, 'number_of_stuff1_avg_2h': 0.0,
'number_of_stuff1_max_1h': 0, 'number_of_stuff1_max_24h': 0, 'number_of_stuff1_max_2h': 0,
'number_of_stuff1_min_1h': 0, 'number_of_stuff1_min_24h': 0, 'number_of_stuff1_min_2h': 0,
'number_of_stuff1_sum_1h': 0, 'number_of_stuff1_sum_24h': 0, 'number_of_stuff1_sum_2h': 0,
'number_of_stuff2_avg_1h': 2.0, 'number_of_stuff2_avg_24h': 1.5, 'number_of_stuff2_avg_2h': 1.5,
'number_of_stuff2_max_1h': 3, 'number_of_stuff2_max_24h': 3, 'number_of_stuff2_max_2h': 3,
'number_of_stuff2_min_1h': 1, 'number_of_stuff2_min_24h': 0, 'number_of_stuff2_min_2h': 0,
'number_of_stuff2_sum_1h': 6, 'number_of_stuff2_sum_24h': 6, 'number_of_stuff2_sum_2h': 6},
{'col2': 4, 'number_of_stuff1_avg_1h': 0.0, 'number_of_stuff1_avg_24h': 0.0, 'number_of_stuff1_avg_2h': 0.0,
'number_of_stuff1_max_1h': 0, 'number_of_stuff1_max_24h': 0, 'number_of_stuff1_max_2h': 0,
'number_of_stuff1_min_1h': 0, 'number_of_stuff1_min_24h': 0, 'number_of_stuff1_min_2h': 0,
'number_of_stuff1_sum_1h': 0, 'number_of_stuff1_sum_24h': 0, 'number_of_stuff1_sum_2h': 0,
'number_of_stuff2_avg_1h': 3.0, 'number_of_stuff2_avg_24h': 2.0, 'number_of_stuff2_avg_2h': 2.0,
'number_of_stuff2_max_1h': 4, 'number_of_stuff2_max_24h': 4, 'number_of_stuff2_max_2h': 4,
'number_of_stuff2_min_1h': 2, 'number_of_stuff2_min_24h': 0, 'number_of_stuff2_min_2h': 0,
'number_of_stuff2_sum_1h': 9, 'number_of_stuff2_sum_24h': 10, 'number_of_stuff2_sum_2h': 10},
{'col2': 5, 'number_of_stuff1_avg_1h': 0.0, 'number_of_stuff1_avg_24h': 0.0, 'number_of_stuff1_avg_2h': 0.0,
'number_of_stuff1_max_1h': 0, 'number_of_stuff1_max_24h': 0, 'number_of_stuff1_max_2h': 0,
'number_of_stuff1_min_1h': 0, 'number_of_stuff1_min_24h': 0, 'number_of_stuff1_min_2h': 0,
'number_of_stuff1_sum_1h': 0, 'number_of_stuff1_sum_24h': 0, 'number_of_stuff1_sum_2h': 0,
'number_of_stuff2_avg_1h': 4.0, 'number_of_stuff2_avg_24h': 2.5, 'number_of_stuff2_avg_2h': 3.0,
'number_of_stuff2_max_1h': 5, 'number_of_stuff2_max_24h': 5, 'number_of_stuff2_max_2h': 5,
'number_of_stuff2_min_1h': 3, 'number_of_stuff2_min_24h': 0, 'number_of_stuff2_min_2h': 1,
'number_of_stuff2_sum_1h': 12, 'number_of_stuff2_sum_24h': 15, 'number_of_stuff2_sum_2h': 15},
{'col2': 6, 'number_of_stuff1_avg_1h': 0.0, 'number_of_stuff1_avg_24h': 0.0, 'number_of_stuff1_avg_2h': 0.0,
'number_of_stuff1_max_1h': 0, 'number_of_stuff1_max_24h': 0, 'number_of_stuff1_max_2h': 0,
'number_of_stuff1_min_1h': 0, 'number_of_stuff1_min_24h': 0, 'number_of_stuff1_min_2h': 0,
'number_of_stuff1_sum_1h': 0, 'number_of_stuff1_sum_24h': 0, 'number_of_stuff1_sum_2h': 0,
'number_of_stuff2_avg_1h': 5.0, 'number_of_stuff2_avg_24h': 3.0, 'number_of_stuff2_avg_2h': 4.0,
'number_of_stuff2_max_1h': 6, 'number_of_stuff2_max_24h': 6, 'number_of_stuff2_max_2h': 6,
'number_of_stuff2_min_1h': 4, 'number_of_stuff2_min_24h': 0, 'number_of_stuff2_min_2h': 2,
'number_of_stuff2_sum_1h': 15, 'number_of_stuff2_sum_24h': 21, 'number_of_stuff2_sum_2h': 20},
{'col2': 7, 'number_of_stuff1_avg_1h': 0.0, 'number_of_stuff1_avg_24h': 0.0, 'number_of_stuff1_avg_2h': 0.0,
'number_of_stuff1_max_1h': 0, 'number_of_stuff1_max_24h': 0, 'number_of_stuff1_max_2h': 0,
'number_of_stuff1_min_1h': 0, 'number_of_stuff1_min_24h': 0, 'number_of_stuff1_min_2h': 0,
'number_of_stuff1_sum_1h': 0, 'number_of_stuff1_sum_24h': 0, 'number_of_stuff1_sum_2h': 0,
'number_of_stuff2_avg_1h': 6.0, 'number_of_stuff2_avg_24h': 3.5, 'number_of_stuff2_avg_2h': 5.0,
'number_of_stuff2_max_1h': 7, 'number_of_stuff2_max_24h': 7, 'number_of_stuff2_max_2h': 7,
'number_of_stuff2_min_1h': 5, 'number_of_stuff2_min_24h': 0, 'number_of_stuff2_min_2h': 3,
'number_of_stuff2_sum_1h': 18, 'number_of_stuff2_sum_24h': 28, 'number_of_stuff2_sum_2h': 25},
{'col2': 8, 'number_of_stuff1_avg_1h': 0.0, 'number_of_stuff1_avg_24h': 0.0, 'number_of_stuff1_avg_2h': 0.0,
'number_of_stuff1_max_1h': 0, 'number_of_stuff1_max_24h': 0, 'number_of_stuff1_max_2h': 0,
'number_of_stuff1_min_1h': 0, 'number_of_stuff1_min_24h': 0, 'number_of_stuff1_min_2h': 0,
'number_of_stuff1_sum_1h': 0, 'number_of_stuff1_sum_24h': 0, 'number_of_stuff1_sum_2h': 0,
'number_of_stuff2_avg_1h': 7.0, 'number_of_stuff2_avg_24h': 4.0, 'number_of_stuff2_avg_2h': 6.0,
'number_of_stuff2_max_1h': 8, 'number_of_stuff2_max_24h': 8, 'number_of_stuff2_max_2h': 8,
'number_of_stuff2_min_1h': 6, 'number_of_stuff2_min_24h': 0, 'number_of_stuff2_min_2h': 4,
'number_of_stuff2_sum_1h': 21, 'number_of_stuff2_sum_24h': 36, 'number_of_stuff2_sum_2h': 30},
{'col2': 9, 'number_of_stuff1_avg_1h': 0.0, 'number_of_stuff1_avg_24h': 0.0, 'number_of_stuff1_avg_2h': 0.0,
'number_of_stuff1_max_1h': 0, 'number_of_stuff1_max_24h': 0, 'number_of_stuff1_max_2h': 0,
'number_of_stuff1_min_1h': 0, 'number_of_stuff1_min_24h': 0, 'number_of_stuff1_min_2h': 0,
'number_of_stuff1_sum_1h': 0, 'number_of_stuff1_sum_24h': 0, 'number_of_stuff1_sum_2h': 0,
'number_of_stuff2_avg_1h': 8.0, 'number_of_stuff2_avg_24h': 4.5, 'number_of_stuff2_avg_2h': 7.0,
'number_of_stuff2_max_1h': 9, 'number_of_stuff2_max_24h': 9, 'number_of_stuff2_max_2h': 9,
'number_of_stuff2_min_1h': 7, 'number_of_stuff2_min_24h': 0, 'number_of_stuff2_min_2h': 5,
'number_of_stuff2_sum_1h': 24, 'number_of_stuff2_sum_24h': 45, 'number_of_stuff2_sum_2h': 35}]
assert actual == expected_results, \
f'actual did not match expected. \n actual: {actual} \n expected: {expected_results}'
def test_sliding_window_multiple_keys_aggregation_flow():
controller = build_flow([
SyncEmitSource(),
AggregateByKey([FieldAggregator("number_of_stuff", "col1", ["sum", "avg"],
SlidingWindows(['1h', '2h', '24h'], '10m'))],
Table("test", NoopDriver())),
Reduce([], lambda acc, x: append_return(acc, x)),
]).run()
for i in range(10):
data = {'col1': i}
controller.emit(data, f'{i % 2}', test_base_time + timedelta(minutes=i))
controller.terminate()
actual = controller.await_termination()
expected_results = [
{'col1': 0, 'number_of_stuff_sum_1h': 0, 'number_of_stuff_sum_2h': 0, 'number_of_stuff_sum_24h': 0,
'number_of_stuff_avg_1h': 0.0, 'number_of_stuff_avg_2h': 0.0, 'number_of_stuff_avg_24h': 0.0},
{'col1': 1, 'number_of_stuff_sum_1h': 1, 'number_of_stuff_sum_2h': 1, 'number_of_stuff_sum_24h': 1,
'number_of_stuff_avg_1h': 1.0, 'number_of_stuff_avg_2h': 1.0, 'number_of_stuff_avg_24h': 1.0},
{'col1': 2, 'number_of_stuff_sum_1h': 2, 'number_of_stuff_sum_2h': 2, 'number_of_stuff_sum_24h': 2,
'number_of_stuff_avg_1h': 1.0, 'number_of_stuff_avg_2h': 1.0, 'number_of_stuff_avg_24h': 1.0},
{'col1': 3, 'number_of_stuff_sum_1h': 4, 'number_of_stuff_sum_2h': 4, 'number_of_stuff_sum_24h': 4,
'number_of_stuff_avg_1h': 2.0, 'number_of_stuff_avg_2h': 2.0, 'number_of_stuff_avg_24h': 2.0},
{'col1': 4, 'number_of_stuff_sum_1h': 6, 'number_of_stuff_sum_2h': 6, 'number_of_stuff_sum_24h': 6,
'number_of_stuff_avg_1h': 2.0, 'number_of_stuff_avg_2h': 2.0, 'number_of_stuff_avg_24h': 2.0},
{'col1': 5, 'number_of_stuff_sum_1h': 9, 'number_of_stuff_sum_2h': 9, 'number_of_stuff_sum_24h': 9,
'number_of_stuff_avg_1h': 3.0, 'number_of_stuff_avg_2h': 3.0, 'number_of_stuff_avg_24h': 3.0},
{'col1': 6, 'number_of_stuff_sum_1h': 12, 'number_of_stuff_sum_2h': 12, 'number_of_stuff_sum_24h': 12,
'number_of_stuff_avg_1h': 3.0, 'number_of_stuff_avg_2h': 3.0, 'number_of_stuff_avg_24h': 3.0},
{'col1': 7, 'number_of_stuff_sum_1h': 16, 'number_of_stuff_sum_2h': 16, 'number_of_stuff_sum_24h': 16,
'number_of_stuff_avg_1h': 4.0, 'number_of_stuff_avg_2h': 4.0, 'number_of_stuff_avg_24h': 4.0},
{'col1': 8, 'number_of_stuff_sum_1h': 20, 'number_of_stuff_sum_2h': 20, 'number_of_stuff_sum_24h': 20,
'number_of_stuff_avg_1h': 4.0, 'number_of_stuff_avg_2h': 4.0, 'number_of_stuff_avg_24h': 4.0},
{'col1': 9, 'number_of_stuff_sum_1h': 25, 'number_of_stuff_sum_2h': 25, 'number_of_stuff_sum_24h': 25,
'number_of_stuff_avg_1h': 5.0, 'number_of_stuff_avg_2h': 5.0, 'number_of_stuff_avg_24h': 5.0}]
assert actual == expected_results, \
f'actual did not match expected. \n actual: {actual} \n expected: {expected_results}'
def test_sliding_window_aggregations_with_filters_flow():
controller = build_flow([
SyncEmitSource(),
AggregateByKey([FieldAggregator("number_of_stuff", "col1", ["sum", "avg"],
SlidingWindows(['1h', '2h', '24h'], '10m'),
aggr_filter=lambda element: element['is_valid'] == 0)],
Table("test", NoopDriver())),
Reduce([], lambda acc, x: append_return(acc, x)),
]).run()
for i in range(10):
data = {'col1': i, 'is_valid': i % 2}
controller.emit(data, 'tal', test_base_time + timedelta(minutes=i))
controller.terminate()
actual = controller.await_termination()
expected_results = [{'col1': 0, 'is_valid': 0, 'number_of_stuff_sum_1h': 0, 'number_of_stuff_sum_2h': 0,
'number_of_stuff_sum_24h': 0, 'number_of_stuff_avg_1h': 0.0, 'number_of_stuff_avg_2h': 0.0,
'number_of_stuff_avg_24h': 0.0},
{'col1': 1, 'is_valid': 1, 'number_of_stuff_sum_1h': 0, 'number_of_stuff_sum_2h': 0,
'number_of_stuff_sum_24h': 0, 'number_of_stuff_avg_1h': 0.0, 'number_of_stuff_avg_2h': 0.0,
'number_of_stuff_avg_24h': 0.0},
{'col1': 2, 'is_valid': 0, 'number_of_stuff_sum_1h': 2, 'number_of_stuff_sum_2h': 2,
'number_of_stuff_sum_24h': 2, 'number_of_stuff_avg_1h': 1.0, 'number_of_stuff_avg_2h': 1.0,
'number_of_stuff_avg_24h': 1.0},
{'col1': 3, 'is_valid': 1, 'number_of_stuff_sum_1h': 2, 'number_of_stuff_sum_2h': 2,
'number_of_stuff_sum_24h': 2, 'number_of_stuff_avg_1h': 1.0, 'number_of_stuff_avg_2h': 1.0,
'number_of_stuff_avg_24h': 1.0},
{'col1': 4, 'is_valid': 0, 'number_of_stuff_sum_1h': 6, 'number_of_stuff_sum_2h': 6,
'number_of_stuff_sum_24h': 6, 'number_of_stuff_avg_1h': 2.0, 'number_of_stuff_avg_2h': 2.0,
'number_of_stuff_avg_24h': 2.0},
{'col1': 5, 'is_valid': 1, 'number_of_stuff_sum_1h': 6, 'number_of_stuff_sum_2h': 6,
'number_of_stuff_sum_24h': 6, 'number_of_stuff_avg_1h': 2.0, 'number_of_stuff_avg_2h': 2.0,
'number_of_stuff_avg_24h': 2.0},
{'col1': 6, 'is_valid': 0, 'number_of_stuff_sum_1h': 12, 'number_of_stuff_sum_2h': 12,
'number_of_stuff_sum_24h': 12, 'number_of_stuff_avg_1h': 3.0, 'number_of_stuff_avg_2h': 3.0,
'number_of_stuff_avg_24h': 3.0},
{'col1': 7, 'is_valid': 1, 'number_of_stuff_sum_1h': 12, 'number_of_stuff_sum_2h': 12,
'number_of_stuff_sum_24h': 12, 'number_of_stuff_avg_1h': 3.0, 'number_of_stuff_avg_2h': 3.0,
'number_of_stuff_avg_24h': 3.0},
{'col1': 8, 'is_valid': 0, 'number_of_stuff_sum_1h': 20, 'number_of_stuff_sum_2h': 20,
'number_of_stuff_sum_24h': 20, 'number_of_stuff_avg_1h': 4.0, 'number_of_stuff_avg_2h': 4.0,
'number_of_stuff_avg_24h': 4.0},
{'col1': 9, 'is_valid': 1, 'number_of_stuff_sum_1h': 20, 'number_of_stuff_sum_2h': 20,
'number_of_stuff_sum_24h': 20, 'number_of_stuff_avg_1h': 4.0, 'number_of_stuff_avg_2h': 4.0,
'number_of_stuff_avg_24h': 4.0}]
assert actual == expected_results, \
f'actual did not match expected. \n actual: {actual} \n expected: {expected_results}'
def test_sliding_window_aggregations_with_max_values_flow():
controller = build_flow([
SyncEmitSource(),
AggregateByKey([FieldAggregator("num_hours_with_stuff_in_the_last_24h", "col1", ["count"],
SlidingWindows(['24h'], '1h'),
max_value=5)],
Table("test", NoopDriver())),
Reduce([], lambda acc, x: append_return(acc, x)),
]).run()
for i in range(10):
data = {'col1': i}
controller.emit(data, 'tal', test_base_time + timedelta(minutes=10 * i))
controller.terminate()
actual = controller.await_termination()
expected_results = [{'col1': 0, 'num_hours_with_stuff_in_the_last_24h_count_24h': 1},
{'col1': 1, 'num_hours_with_stuff_in_the_last_24h_count_24h': 2},
{'col1': 2, 'num_hours_with_stuff_in_the_last_24h_count_24h': 3},
{'col1': 3, 'num_hours_with_stuff_in_the_last_24h_count_24h': 4},
{'col1': 4, 'num_hours_with_stuff_in_the_last_24h_count_24h': 5},
{'col1': 5, 'num_hours_with_stuff_in_the_last_24h_count_24h': 5},
{'col1': 6, 'num_hours_with_stuff_in_the_last_24h_count_24h': 5},
{'col1': 7, 'num_hours_with_stuff_in_the_last_24h_count_24h': 5},
{'col1': 8, 'num_hours_with_stuff_in_the_last_24h_count_24h': 5},
{'col1': 9, 'num_hours_with_stuff_in_the_last_24h_count_24h': 5}]
assert actual == expected_results, \
f'actual did not match expected. \n actual: {actual} \n expected: {expected_results}'
def test_sliding_window_simple_aggregation_flow_multiple_fields():
controller = build_flow([
SyncEmitSource(),
AggregateByKey([FieldAggregator("number_of_stuff", "col1", ["sum", "avg"],
SlidingWindows(['1h', '2h', '24h'], '10m')),
FieldAggregator("number_of_things", "col2", ["count"],
SlidingWindows(['1h', '2h'], '15m')),
FieldAggregator("abc", "col3", ["sum"],
SlidingWindows(['24h'], '10m'))],
Table("test", NoopDriver())),
Reduce([], lambda acc, x: append_return(acc, x)),
]).run()
for i in range(10):
data = {'col1': i, 'col2': i * 1.2, 'col3': i * 2 + 4}
controller.emit(data, 'tal', test_base_time + timedelta(minutes=i))
controller.terminate()
actual = controller.await_termination()
expected_results = [{'col1': 0, 'col2': 0.0, 'col3': 4, 'number_of_stuff_sum_1h': 0, 'number_of_stuff_sum_2h': 0,
'number_of_stuff_sum_24h': 0, 'number_of_things_count_1h': 1, 'number_of_things_count_2h': 1,
'abc_sum_24h': 4, 'number_of_stuff_avg_1h': 0.0, 'number_of_stuff_avg_2h': 0.0, 'number_of_stuff_avg_24h': 0.0},
{'col1': 1, 'col2': 1.2, 'col3': 6, 'number_of_stuff_sum_1h': 1, 'number_of_stuff_sum_2h': 1,
'number_of_stuff_sum_24h': 1, 'number_of_things_count_1h': 2, 'number_of_things_count_2h': 2,
'abc_sum_24h': 10, 'number_of_stuff_avg_1h': 0.5, 'number_of_stuff_avg_2h': 0.5, 'number_of_stuff_avg_24h': 0.5},
{'col1': 2, 'col2': 2.4, 'col3': 8, 'number_of_stuff_sum_1h': 3, 'number_of_stuff_sum_2h': 3,
'number_of_stuff_sum_24h': 3, 'number_of_things_count_1h': 3, 'number_of_things_count_2h': 3,
'abc_sum_24h': 18, 'number_of_stuff_avg_1h': 1.0, 'number_of_stuff_avg_2h': 1.0, 'number_of_stuff_avg_24h': 1.0},
{'col1': 3, 'col2': 3.5999999999999996, 'col3': 10, 'number_of_stuff_sum_1h': 6,
'number_of_stuff_sum_2h': 6, 'number_of_stuff_sum_24h': 6, 'number_of_things_count_1h': 4,
'number_of_things_count_2h': 4, 'abc_sum_24h': 28, 'number_of_stuff_avg_1h': 1.5, 'number_of_stuff_avg_2h': 1.5,
'number_of_stuff_avg_24h': 1.5},
{'col1': 4, 'col2': 4.8, 'col3': 12, 'number_of_stuff_sum_1h': 10, 'number_of_stuff_sum_2h': 10,
'number_of_stuff_sum_24h': 10, 'number_of_things_count_1h': 5, 'number_of_things_count_2h': 5,
'abc_sum_24h': 40, 'number_of_stuff_avg_1h': 2.0, 'number_of_stuff_avg_2h': 2.0, 'number_of_stuff_avg_24h': 2.0},
{'col1': 5, 'col2': 6.0, 'col3': 14, 'number_of_stuff_sum_1h': 15, 'number_of_stuff_sum_2h': 15,
'number_of_stuff_sum_24h': 15, 'number_of_things_count_1h': 6, 'number_of_things_count_2h': 6,
'abc_sum_24h': 54, 'number_of_stuff_avg_1h': 2.5, 'number_of_stuff_avg_2h': 2.5, 'number_of_stuff_avg_24h': 2.5},
{'col1': 6, 'col2': 7.199999999999999, 'col3': 16, 'number_of_stuff_sum_1h': 21,
'number_of_stuff_sum_2h': 21, 'number_of_stuff_sum_24h': 21, 'number_of_things_count_1h': 7,
'number_of_things_count_2h': 7, 'abc_sum_24h': 70, 'number_of_stuff_avg_1h': 3.0,
'number_of_stuff_avg_2h': 3.0, 'number_of_stuff_avg_24h': 3.0},
{'col1': 7, 'col2': 8.4, 'col3': 18, 'number_of_stuff_sum_1h': 28, 'number_of_stuff_sum_2h': 28,
'number_of_stuff_sum_24h': 28, 'number_of_things_count_1h': 8, 'number_of_things_count_2h': 8,
'abc_sum_24h': 88, 'number_of_stuff_avg_1h': 3.5, 'number_of_stuff_avg_2h': 3.5, 'number_of_stuff_avg_24h': 3.5},
{'col1': 8, 'col2': 9.6, 'col3': 20, 'number_of_stuff_sum_1h': 36, 'number_of_stuff_sum_2h': 36,
'number_of_stuff_sum_24h': 36, 'number_of_things_count_1h': 9, 'number_of_things_count_2h': 9,
'abc_sum_24h': 108, 'number_of_stuff_avg_1h': 4.0, 'number_of_stuff_avg_2h': 4.0, 'number_of_stuff_avg_24h': 4.0},
{'col1': 9, 'col2': 10.799999999999999, 'col3': 22, 'number_of_stuff_sum_1h': 45,
'number_of_stuff_sum_2h': 45, 'number_of_stuff_sum_24h': 45,
'number_of_things_count_1h': 10, 'number_of_things_count_2h': 10, 'abc_sum_24h': 130,
'number_of_stuff_avg_1h': 4.5, 'number_of_stuff_avg_2h': 4.5, 'number_of_stuff_avg_24h': 4.5}]
assert actual == expected_results, \
f'actual did not match expected. \n actual: {actual} \n expected: {expected_results}'
def test_fixed_window_simple_aggregation_flow():
controller = build_flow([
SyncEmitSource(),
AggregateByKey([FieldAggregator("number_of_stuff", "col1", ["count"],
FixedWindows(['1h', '2h', '3h', '24h']))],
Table("test", NoopDriver())),
Reduce([], lambda acc, x: append_return(acc, x)),
]).run()
for i in range(10):
data = {'col1': i}
controller.emit(data, 'tal', test_base_time + timedelta(minutes=25 * i))
controller.terminate()
actual = controller.await_termination()
expected_results = [{'col1': 0, 'number_of_stuff_count_1h': 1, 'number_of_stuff_count_2h': 1, 'number_of_stuff_count_3h': 1,
'number_of_stuff_count_24h': 1},
{'col1': 1, 'number_of_stuff_count_1h': 1, 'number_of_stuff_count_2h': 1, 'number_of_stuff_count_3h': 2,
'number_of_stuff_count_24h': 2},
{'col1': 2, 'number_of_stuff_count_1h': 2, 'number_of_stuff_count_2h': 2, 'number_of_stuff_count_3h': 3,
'number_of_stuff_count_24h': 3},
{'col1': 3, 'number_of_stuff_count_1h': 3, 'number_of_stuff_count_2h': 3, 'number_of_stuff_count_3h': 4,
'number_of_stuff_count_24h': 4},
{'col1': 4, 'number_of_stuff_count_1h': 1, 'number_of_stuff_count_2h': 4, 'number_of_stuff_count_3h': 5,
'number_of_stuff_count_24h': 5},
{'col1': 5, 'number_of_stuff_count_1h': 2, 'number_of_stuff_count_2h': 5, 'number_of_stuff_count_3h': 6,
'number_of_stuff_count_24h': 6},
{'col1': 6, 'number_of_stuff_count_1h': 1, 'number_of_stuff_count_2h': 1, 'number_of_stuff_count_3h': 1,
'number_of_stuff_count_24h': 1},
{'col1': 7, 'number_of_stuff_count_1h': 2, 'number_of_stuff_count_2h': 2, 'number_of_stuff_count_3h': 2,
'number_of_stuff_count_24h': 2},
{'col1': 8, 'number_of_stuff_count_1h': 1, 'number_of_stuff_count_2h': 3, 'number_of_stuff_count_3h': 3,
'number_of_stuff_count_24h': 3},
{'col1': 9, 'number_of_stuff_count_1h': 2, 'number_of_stuff_count_2h': 4, 'number_of_stuff_count_3h': 4,
'number_of_stuff_count_24h': 4}]
assert actual == expected_results, \
f'actual did not match expected. \n actual: {actual} \n expected: {expected_results}'
def test_fixed_window_aggregation_with_uncommon_windows_flow():
time_format = '%Y-%m-%d %H:%M:%S.%f'
columns = ['sample_time', 'signal', 'isotope']
data = [[datetime.strptime('2021-05-30 16:42:15.797000', time_format).replace(tzinfo=timezone.utc), 790.235, 'U235'],
[datetime.strptime('2021-05-30 16:45:15.798000', time_format).replace(tzinfo=timezone.utc), 498.491, 'U235'],
[datetime.strptime('2021-05-30 16:48:15.799000', time_format).replace(tzinfo=timezone.utc), 34650.00343, 'U235'],
[datetime.strptime('2021-05-30 16:51:15.800000', time_format).replace(tzinfo=timezone.utc), 189.823, 'U235'],
[datetime.strptime('2021-05-30 16:54:15.801000', time_format).replace(tzinfo=timezone.utc), 379.524, 'U235'],
[datetime.strptime('2021-05-30 16:57:15.802000', time_format).replace(tzinfo=timezone.utc), 2225.4952, 'U235'],
[datetime.strptime('2021-05-30 17:00:15.803000', time_format).replace(tzinfo=timezone.utc), 1049.0903, 'U235'],
[datetime.strptime('2021-05-30 17:03:15.804000', time_format).replace(tzinfo=timezone.utc), 41905.63447, 'U235'],
[datetime.strptime('2021-05-30 17:06:15.805000', time_format).replace(tzinfo=timezone.utc), 4987.6764, 'U235'],
[datetime.strptime('2021-05-30 17:09:15.806000', time_format).replace(tzinfo=timezone.utc), 67657.11975, 'U235'],
[datetime.strptime('2021-05-30 17:12:15.807000', time_format).replace(tzinfo=timezone.utc), 56173.06327, 'U235'],
[datetime.strptime('2021-05-30 17:15:15.808000', time_format).replace(tzinfo=timezone.utc), 14249.67394, 'U235'],
[datetime.strptime('2021-05-30 17:18:15.809000', time_format).replace(tzinfo=timezone.utc), 656.831, 'U235'],
[datetime.strptime('2021-05-30 17:21:15.810000', time_format).replace(tzinfo=timezone.utc), 5768.4822, 'U235'],
[datetime.strptime('2021-05-30 17:24:15.811000', time_format).replace(tzinfo=timezone.utc), 929.028, 'U235'],
[datetime.strptime('2021-05-30 17:27:15.812000', time_format).replace(tzinfo=timezone.utc), 2585.9646, 'U235'],
[datetime.strptime('2021-05-30 17:30:15.813000', time_format).replace(tzinfo=timezone.utc), 358.918, 'U235']]
df = pd.DataFrame(data, columns=columns)
controller = build_flow([
DataframeSource(df, time_field="sample_time", key_field="isotope"),
AggregateByKey([FieldAggregator("samples", "signal", ["count"],
FixedWindows(['15m', '25m', '45m', '1h']))], Table("U235_test", NoopDriver())),
Reduce([], lambda acc, x: append_return(acc, x)),
]).run()
termination_result = controller.await_termination()
expected = [{'samples_count_15m': 1.0, 'samples_count_25m': 1.0, 'samples_count_45m': 1.0, 'samples_count_1h': 1.0,
'sample_time': pd.Timestamp('2021-05-30 16:42:15.797000+0000', tz='UTC'), 'signal': 790.235,
'isotope': 'U235'},
{'samples_count_15m': 1.0, 'samples_count_25m': 2.0, 'samples_count_45m': 2.0, 'samples_count_1h': 2.0,
'sample_time': pd.Timestamp('2021-05-30 16:45:15.798000+0000', tz='UTC'), 'signal': 498.491,
'isotope': 'U235'},
{'samples_count_15m': 2.0, 'samples_count_25m': 3.0, 'samples_count_45m': 3.0, 'samples_count_1h': 3.0,
'sample_time': pd.Timestamp('2021-05-30 16:48:15.799000+0000', tz='UTC'), 'signal': 34650.00343,
'isotope': 'U235'},
{'samples_count_15m': 3.0, 'samples_count_25m': 4.0, 'samples_count_45m': 4.0, 'samples_count_1h': 4.0,
'sample_time': pd.Timestamp('2021-05-30 16:51:15.800000+0000', tz='UTC'), 'signal': 189.823,
'isotope': 'U235'},
{'samples_count_15m': 4.0, 'samples_count_25m': 5.0, 'samples_count_45m': 5.0, 'samples_count_1h': 5.0,
'sample_time': pd.Timestamp('2021-05-30 16:54:15.801000+0000', tz='UTC'), 'signal': 379.524,
'isotope': 'U235'},
{'samples_count_15m': 5.0, 'samples_count_25m': 6.0, 'samples_count_45m': 6.0, 'samples_count_1h': 6.0,
'sample_time': pd.Timestamp('2021-05-30 16:57:15.802000+0000', tz='UTC'), 'signal': 2225.4952,
'isotope': 'U235'},
{'samples_count_15m': 1.0, 'samples_count_25m': 1.0, 'samples_count_45m': 7.0, 'samples_count_1h': 1.0,
'sample_time': pd.Timestamp('2021-05-30 17:00:15.803000+0000', tz='UTC'), 'signal': 1049.0903,
'isotope': 'U235'},
{'samples_count_15m': 2.0, 'samples_count_25m': 2.0, 'samples_count_45m': 8.0, 'samples_count_1h': 2.0,
'sample_time': pd.Timestamp('2021-05-30 17:03:15.804000+0000', tz='UTC'), 'signal': 41905.63447,
'isotope': 'U235'},
{'samples_count_15m': 3.0, 'samples_count_25m': 3.0, 'samples_count_45m': 9.0, 'samples_count_1h': 3.0,
'sample_time': pd.Timestamp('2021-05-30 17:06:15.805000+0000', tz='UTC'), 'signal': 4987.6764,
'isotope': 'U235'},
{'samples_count_15m': 4.0, 'samples_count_25m': 4.0, 'samples_count_45m': 10.0, 'samples_count_1h': 4.0,
'sample_time': pd.Timestamp('2021-05-30 17:09:15.806000+0000', tz='UTC'), 'signal': 67657.11975,
'isotope': 'U235'},
{'samples_count_15m': 5.0, 'samples_count_25m': 5.0, 'samples_count_45m': 11.0, 'samples_count_1h': 5.0,
'sample_time': pd.Timestamp('2021-05-30 17:12:15.807000+0000', tz='UTC'), 'signal': 56173.06327,
'isotope': 'U235'},
{'samples_count_15m': 1.0, 'samples_count_25m': 6.0, 'samples_count_45m': 1.0, 'samples_count_1h': 6.0,
'sample_time': pd.Timestamp('2021-05-30 17:15:15.808000+0000', tz='UTC'), 'signal': 14249.67394,
'isotope': 'U235'},
{'samples_count_15m': 2.0, 'samples_count_25m': 7.0, 'samples_count_45m': 2.0, 'samples_count_1h': 7.0,
'sample_time': pd.Timestamp('2021-05-30 17:18:15.809000+0000', tz='UTC'), 'signal': 656.831,
'isotope': 'U235'},
{'samples_count_15m': 3.0, 'samples_count_25m': 8.0, 'samples_count_45m': 3.0, 'samples_count_1h': 8.0,
'sample_time': pd.Timestamp('2021-05-30 17:21:15.810000+0000', tz='UTC'), 'signal': 5768.4822,
'isotope': 'U235'},
{'samples_count_15m': 4.0, 'samples_count_25m': 9.0, 'samples_count_45m': 4.0, 'samples_count_1h': 9.0,
'sample_time': pd.Timestamp('2021-05-30 17:24:15.811000+0000', tz='UTC'), 'signal': 929.028,
'isotope': 'U235'},
{'samples_count_15m': 5.0, 'samples_count_25m': 1.0, 'samples_count_45m': 5.0, 'samples_count_1h': 10.0,
'sample_time': pd.Timestamp('2021-05-30 17:27:15.812000+0000', tz='UTC'), 'signal': 2585.9646,
'isotope': 'U235'},
{'samples_count_15m': 1.0, 'samples_count_25m': 2.0, 'samples_count_45m': 6.0, 'samples_count_1h': 11.0,
'sample_time': pd.Timestamp('2021-05-30 17:30:15.813000+0000', tz='UTC'), 'signal': 358.918,
'isotope': 'U235'}]
assert termination_result == expected, \
f'actual did not match expected. \n actual: {termination_result} \n expected: {expected}'
def test_fixed_window_aggregation_with_multiple_keys_flow():
time_format = '%Y-%m-%d %H:%M:%S.%f'
columns = ['sample_time', 'signal', 'isotope']
data = [[datetime.strptime('2021-05-30 16:42:15.797000', time_format).replace(tzinfo=timezone.utc), 790.235, 'U235'],
[datetime.strptime('2021-05-30 16:45:15.798000', time_format).replace(tzinfo=timezone.utc), 498.491, 'U235'],
[datetime.strptime('2021-05-30 16:48:15.799000', time_format).replace(tzinfo=timezone.utc), 34650.00343, 'U238'],
[datetime.strptime('2021-05-30 16:51:15.800000', time_format).replace(tzinfo=timezone.utc), 189.823, 'U238'],
[datetime.strptime('2021-05-30 16:54:15.801000', time_format).replace(tzinfo=timezone.utc), 379.524, 'U238'],
[datetime.strptime('2021-05-30 16:57:15.802000', time_format).replace(tzinfo=timezone.utc), 2225.4952, 'U238'],
[datetime.strptime('2021-05-30 17:00:15.803000', time_format).replace(tzinfo=timezone.utc), 1049.0903, 'U235'],
[datetime.strptime('2021-05-30 17:03:15.804000', time_format).replace(tzinfo=timezone.utc), 41905.63447, 'U238'],
[datetime.strptime('2021-05-30 17:06:15.805000', time_format).replace(tzinfo=timezone.utc), 4987.6764, 'U235'],
[datetime.strptime('2021-05-30 17:09:15.806000', time_format).replace(tzinfo=timezone.utc), 67657.11975, 'U235'],
[datetime.strptime('2021-05-30 17:12:15.807000', time_format).replace(tzinfo=timezone.utc), 56173.06327, 'U235'],
[datetime.strptime('2021-05-30 17:15:15.808000', time_format).replace(tzinfo=timezone.utc), 14249.67394, 'U238'],
[datetime.strptime('2021-05-30 17:18:15.809000', time_format).replace(tzinfo=timezone.utc), 656.831, 'U238'],
[datetime.strptime('2021-05-30 17:21:15.810000', time_format).replace(tzinfo=timezone.utc), 5768.4822, 'U235'],
[datetime.strptime('2021-05-30 17:24:15.811000', time_format).replace(tzinfo=timezone.utc), 929.028, 'U235'],
[datetime.strptime('2021-05-30 17:27:15.812000', time_format).replace(tzinfo=timezone.utc), 2585.9646, 'U238'],
[datetime.strptime('2021-05-30 17:30:15.813000', time_format).replace(tzinfo=timezone.utc), 358.918, 'U238']]
df = pd.DataFrame(data, columns=columns)
controller = build_flow([
DataframeSource(df, time_field="sample_time", key_field="isotope"),
AggregateByKey([FieldAggregator("samples", "signal", ["count"],
FixedWindows(['10m', '15m']))], Table("U235_test", NoopDriver())),
Reduce([], lambda acc, x: append_return(acc, x)),
]).run()
termination_result = controller.await_termination()
expected = [
{'samples_count_10m': 1.0, 'samples_count_15m': 1.0,
'sample_time': pd.Timestamp('2021-05-30 16:42:15.797000+0000', tz='UTC'), 'signal': 790.235, 'isotope': 'U235'},
{'samples_count_10m': 2.0, 'samples_count_15m': 1.0,
'sample_time': pd.Timestamp('2021-05-30 16:45:15.798000+0000', tz='UTC'), 'signal': 498.491, 'isotope': 'U235'},
{'samples_count_10m': 1.0, 'samples_count_15m': 1.0,
'sample_time': pd.Timestamp('2021-05-30 16:48:15.799000+0000', tz='UTC'), 'signal': 34650.00343, 'isotope': 'U238'},
{'samples_count_10m': 1.0, 'samples_count_15m': 2.0,
'sample_time': pd.Timestamp('2021-05-30 16:51:15.800000+0000', tz='UTC'), 'signal': 189.823, 'isotope': 'U238'},
{'samples_count_10m': 2.0, 'samples_count_15m': 3.0,
'sample_time': pd.Timestamp('2021-05-30 16:54:15.801000+0000', tz='UTC'), 'signal': 379.524, 'isotope': 'U238'},
{'samples_count_10m': 3.0, 'samples_count_15m': 4.0,
'sample_time': pd.Timestamp('2021-05-30 16:57:15.802000+0000', tz='UTC'), 'signal': 2225.4952, 'isotope': 'U238'},
{'samples_count_10m': 1.0, 'samples_count_15m': 1.0,
'sample_time': pd.Timestamp('2021-05-30 17:00:15.803000+0000', tz='UTC'), 'signal': 1049.0903, 'isotope': 'U235'},
{'samples_count_10m': 1.0, 'samples_count_15m': 1.0,
'sample_time': pd.Timestamp('2021-05-30 17:03:15.804000+0000', tz='UTC'), 'signal': 41905.63447, 'isotope': 'U238'},
{'samples_count_10m': 2.0, 'samples_count_15m': 2.0,
'sample_time': pd.Timestamp('2021-05-30 17:06:15.805000+0000', tz='UTC'), 'signal': 4987.6764, 'isotope': 'U235'},
{'samples_count_10m': 3.0, 'samples_count_15m': 3.0,
'sample_time': pd.Timestamp('2021-05-30 17:09:15.806000+0000', tz='UTC'), 'signal': 67657.11975, 'isotope': 'U235'},
{'samples_count_10m': 1.0, 'samples_count_15m': 4.0,
'sample_time': pd.Timestamp('2021-05-30 17:12:15.807000+0000', tz='UTC'), 'signal': 56173.06327, 'isotope': 'U235'},
{'samples_count_10m': 1.0, 'samples_count_15m': 1.0,
'sample_time': pd.Timestamp('2021-05-30 17:15:15.808000+0000', tz='UTC'), 'signal': 14249.67394, 'isotope': 'U238'},
{'samples_count_10m': 2.0, 'samples_count_15m': 2.0,
'sample_time': pd.Timestamp('2021-05-30 17:18:15.809000+0000', tz='UTC'), 'signal': 656.831, 'isotope': 'U238'},
{'samples_count_10m': 1.0, 'samples_count_15m': 1.0,
'sample_time': pd.Timestamp('2021-05-30 17:21:15.810000+0000', tz='UTC'), 'signal': 5768.4822, 'isotope': 'U235'},
{'samples_count_10m': 2.0, 'samples_count_15m': 2.0,
'sample_time': pd.Timestamp('2021-05-30 17:24:15.811000+0000', tz='UTC'), 'signal': 929.028, 'isotope': 'U235'},
{'samples_count_10m': 1.0, 'samples_count_15m': 3.0,
'sample_time': pd.Timestamp('2021-05-30 17:27:15.812000+0000', tz='UTC'), 'signal': 2585.9646, 'isotope': 'U238'},
{'samples_count_10m': 1.0, 'samples_count_15m': 1.0,
'sample_time': pd.Timestamp('2021-05-30 17:30:15.813000+0000', tz='UTC'), 'signal': 358.918, 'isotope': 'U238'}]
assert termination_result == expected, \
f'actual did not match expected. \n actual: {termination_result} \n expected: {expected}'
def test_sliding_window_aggregation_with_uncommon_windows_flow():
time_format = '%Y-%m-%d %H:%M:%S.%f'
columns = ['sample_time', 'signal', 'isotope']
data = [[datetime.strptime('2021-05-30 16:42:15.797000', time_format).replace(tzinfo=timezone.utc), 790.235, 'U235'],
[datetime.strptime('2021-05-30 16:45:15.798000', time_format).replace(tzinfo=timezone.utc), 498.491, 'U235'],
[datetime.strptime('2021-05-30 16:48:15.799000', time_format).replace(tzinfo=timezone.utc), 34650.00343, 'U235'],
[datetime.strptime('2021-05-30 16:51:15.800000', time_format).replace(tzinfo=timezone.utc), 189.823, 'U235'],
[datetime.strptime('2021-05-30 16:54:15.801000', time_format).replace(tzinfo=timezone.utc), 379.524, 'U235'],
[datetime.strptime('2021-05-30 16:57:15.802000', time_format).replace(tzinfo=timezone.utc), 2225.4952, 'U235'],
[datetime.strptime('2021-05-30 17:00:15.803000', time_format).replace(tzinfo=timezone.utc), 1049.0903, 'U235'],
[datetime.strptime('2021-05-30 17:03:15.804000', time_format).replace(tzinfo=timezone.utc), 41905.63447, 'U235'],
[datetime.strptime('2021-05-30 17:06:15.805000', time_format).replace(tzinfo=timezone.utc), 4987.6764, 'U235'],
[datetime.strptime('2021-05-30 17:09:15.806000', time_format).replace(tzinfo=timezone.utc), 67657.11975, 'U235'],
[datetime.strptime('2021-05-30 17:12:15.807000', time_format).replace(tzinfo=timezone.utc), 56173.06327, 'U235'],
[datetime.strptime('2021-05-30 17:15:15.808000', time_format).replace(tzinfo=timezone.utc), 14249.67394, 'U235'],
[datetime.strptime('2021-05-30 17:18:15.809000', time_format).replace(tzinfo=timezone.utc), 656.831, 'U235'],
[datetime.strptime('2021-05-30 17:21:15.810000', time_format).replace(tzinfo=timezone.utc), 5768.4822, 'U235'],
[datetime.strptime('2021-05-30 17:24:15.811000', time_format).replace(tzinfo=timezone.utc), 929.028, 'U235'],
[datetime.strptime('2021-05-30 17:27:15.812000', time_format).replace(tzinfo=timezone.utc), 2585.9646, 'U235'],
[datetime.strptime('2021-05-30 17:30:15.813000', time_format).replace(tzinfo=timezone.utc), 358.918, 'U235']]
df = pd.DataFrame(data, columns=columns)
controller = build_flow([
DataframeSource(df, time_field="sample_time", key_field="isotope"),
AggregateByKey([FieldAggregator("samples", "signal", ["count"],
SlidingWindows(['15m', '25m', '45m', '1h'], '5m'))], Table("U235_test", NoopDriver())),
Reduce([], lambda acc, x: append_return(acc, x)),
]).run()
termination_result = controller.await_termination()
expected = [{'samples_count_15m': 1.0, 'samples_count_25m': 1.0, 'samples_count_45m': 1.0, 'samples_count_1h': 1.0,
'sample_time': pd.Timestamp('2021-05-30 16:42:15.797000+0000', tz='UTC'), 'signal': 790.235,
'isotope': 'U235'},
{'samples_count_15m': 2.0, 'samples_count_25m': 2.0, 'samples_count_45m': 2.0, 'samples_count_1h': 2.0,
'sample_time': pd.Timestamp('2021-05-30 16:45:15.798000+0000', tz='UTC'), 'signal': 498.491,
'isotope': 'U235'},
{'samples_count_15m': 3.0, 'samples_count_25m': 3.0, 'samples_count_45m': 3.0, 'samples_count_1h': 3.0,
'sample_time':
|
pd.Timestamp('2021-05-30 16:48:15.799000+0000', tz='UTC')
|
pandas.Timestamp
|
import yaml
from pathlib import Path
import pandas as pd
from models.cleaners import clean_population, clean_country_codes, clean_life_expectancy, clean_mortality
from models.utils.paths import get_data_path, get_cleaned_data_path, get_prepared_data_path
DATA_DIR = get_data_path()
DATA_CLEANED_DIR = get_cleaned_data_path()
DATA_PREPARED_DIR = get_prepared_data_path()
NL_LIFE_EXP_FILE = 'netherlands_life_exp.xlsx'
JP_LIFE_EXP_FILE = 'japan_life_exp.xlsx'
CA_LIFE_EXP_FILE = 'canada_life_exp.xlsx'
COUNTRY_CODES_FILE = 'country_codes'
POPULATION_FILE = 'pop'
MORTALITY_FILE = 'Morticd10_part' # append 1 till 5 and concatenate the 5 files together
NL_LIFE_EXP_PATH = Path(DATA_DIR, NL_LIFE_EXP_FILE)
JP_LIFE_EXP_PATH = Path(DATA_DIR, JP_LIFE_EXP_FILE)
CA_LIFE_EXP_PATH = Path(DATA_DIR, CA_LIFE_EXP_FILE)
COUNTRY_CODES_PATH = Path(DATA_DIR, COUNTRY_CODES_FILE)
POPULATION_PATH = Path(DATA_DIR, POPULATION_FILE)
MORTALITY_PATH = Path(DATA_DIR, MORTALITY_FILE)
if __name__ == '__main__':
if not Path(Path(DATA_CLEANED_DIR)).exists():
Path.mkdir(Path(DATA_CLEANED_DIR))
if not Path(Path(DATA_PREPARED_DIR)).exists():
Path.mkdir(Path(DATA_PREPARED_DIR))
# Load datasets
mortality_datasets = [Path(DATA_DIR, f"{MORTALITY_FILE}{str(i + 1)}") for i in range(0, 5)]
mortality_datasets = [
|
pd.read_csv(data_path)
|
pandas.read_csv
|
# pylint: disable-msg=E1101,W0612
from datetime import datetime, timedelta
import os
import operator
import unittest
import cStringIO as StringIO
import nose
from numpy import nan
import numpy as np
import numpy.ma as ma
from pandas import Index, Series, TimeSeries, DataFrame, isnull, notnull
from pandas.core.index import MultiIndex
import pandas.core.datetools as datetools
from pandas.util import py3compat
from pandas.util.testing import assert_series_equal, assert_almost_equal
import pandas.util.testing as tm
#-------------------------------------------------------------------------------
# Series test cases
JOIN_TYPES = ['inner', 'outer', 'left', 'right']
class CheckNameIntegration(object):
def test_scalarop_preserve_name(self):
result = self.ts * 2
self.assertEquals(result.name, self.ts.name)
def test_copy_name(self):
result = self.ts.copy()
self.assertEquals(result.name, self.ts.name)
# def test_copy_index_name_checking(self):
# # don't want to be able to modify the index stored elsewhere after
# # making a copy
# self.ts.index.name = None
# cp = self.ts.copy()
# cp.index.name = 'foo'
# self.assert_(self.ts.index.name is None)
def test_append_preserve_name(self):
result = self.ts[:5].append(self.ts[5:])
self.assertEquals(result.name, self.ts.name)
def test_binop_maybe_preserve_name(self):
# names match, preserve
result = self.ts * self.ts
self.assertEquals(result.name, self.ts.name)
result = self.ts * self.ts[:-2]
self.assertEquals(result.name, self.ts.name)
# names don't match, don't preserve
cp = self.ts.copy()
cp.name = 'something else'
result = self.ts + cp
self.assert_(result.name is None)
def test_combine_first_name(self):
result = self.ts.combine_first(self.ts[:5])
self.assertEquals(result.name, self.ts.name)
def test_getitem_preserve_name(self):
result = self.ts[self.ts > 0]
self.assertEquals(result.name, self.ts.name)
result = self.ts[[0, 2, 4]]
self.assertEquals(result.name, self.ts.name)
result = self.ts[5:10]
self.assertEquals(result.name, self.ts.name)
def test_multilevel_name_print(self):
index = MultiIndex(levels=[['foo', 'bar', 'baz', 'qux'],
['one', 'two', 'three']],
labels=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3],
[0, 1, 2, 0, 1, 1, 2, 0, 1, 2]],
names=['first', 'second'])
s = Series(range(0,len(index)), index=index, name='sth')
expected = ["first second",
"foo one 0",
" two 1",
" three 2",
"bar one 3",
" two 4",
"baz two 5",
" three 6",
"qux one 7",
" two 8",
" three 9",
"Name: sth"]
expected = "\n".join(expected)
self.assertEquals(repr(s), expected)
def test_multilevel_preserve_name(self):
index = MultiIndex(levels=[['foo', 'bar', 'baz', 'qux'],
['one', 'two', 'three']],
labels=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3],
[0, 1, 2, 0, 1, 1, 2, 0, 1, 2]],
names=['first', 'second'])
s = Series(np.random.randn(len(index)), index=index, name='sth')
result = s['foo']
result2 = s.ix['foo']
self.assertEquals(result.name, s.name)
self.assertEquals(result2.name, s.name)
def test_name_printing(self):
# test small series
s = Series([0, 1, 2])
s.name = "test"
self.assert_("Name: test" in repr(s))
s.name = None
self.assert_(not "Name:" in repr(s))
# test big series (diff code path)
s = Series(range(0,1000))
s.name = "test"
self.assert_("Name: test" in repr(s))
s.name = None
self.assert_(not "Name:" in repr(s))
def test_pickle_preserve_name(self):
unpickled = self._pickle_roundtrip(self.ts)
self.assertEquals(unpickled.name, self.ts.name)
def _pickle_roundtrip(self, obj):
obj.save('__tmp__')
unpickled = Series.load('__tmp__')
os.remove('__tmp__')
return unpickled
def test_argsort_preserve_name(self):
result = self.ts.argsort()
self.assertEquals(result.name, self.ts.name)
def test_sort_index_name(self):
result = self.ts.sort_index(ascending=False)
self.assertEquals(result.name, self.ts.name)
def test_to_sparse_pass_name(self):
result = self.ts.to_sparse()
self.assertEquals(result.name, self.ts.name)
class SafeForSparse(object):
pass
class TestSeries(unittest.TestCase, CheckNameIntegration):
def setUp(self):
self.ts =
|
tm.makeTimeSeries()
|
pandas.util.testing.makeTimeSeries
|
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import power_transform
from sklearn.preprocessing import MinMaxScaler
import matplotlib.pyplot as plt
import os
import datetime
import numpy as np
import seaborn as sns
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import Imputer
#Garbage Collector
import gc
os.getcwd()
os.chdir('C:/Users/Mann-A2/Documents/Python Repository/IEEE Fraud Detection - Kaggle/ieee-fraud-detection')
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
train_identity = pd.read_csv('train_identity.csv')
train_transaction = pd.read_csv('train_transaction.csv')
test_identity = pd.read_csv('test_identity.csv')
test_transaction = pd.read_csv('test_transaction.csv')
# function to reduce size
def reduce_mem_usage(df):
""" iterate through all the columns of a dataframe and modify the data type
to reduce memory usage.
"""
start_mem = df.memory_usage().sum() / 1024**2
print('Memory usage of dataframe is {:.2f} MB'.format(start_mem))
for col in df.columns:
col_type = df[col].dtype
if col_type != object:
c_min = df[col].min()
c_max = df[col].max()
if str(col_type)[:3] == 'int':
if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:
df[col] = df[col].astype(np.int8)
elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:
df[col] = df[col].astype(np.int16)
elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:
df[col] = df[col].astype(np.int32)
elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:
df[col] = df[col].astype(np.int64)
else:
if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max:
df[col] = df[col].astype(np.float16)
elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:
df[col] = df[col].astype(np.float32)
else:
df[col] = df[col].astype(np.float64)
else:
df[col] = df[col].astype('category')
end_mem = df.memory_usage().sum() / 1024**2
print('Memory usage after optimization is: {:.2f} MB'.format(end_mem))
print('Decreased by {:.1f}%'.format(100 * (start_mem - end_mem) / start_mem))
return df
#split function
def id_split(dataframe):
dataframe['device_name'] = dataframe['DeviceInfo'].str.split('/', expand=True)[0]
dataframe['device_version'] = dataframe['DeviceInfo'].str.split('/', expand=True)[1]
dataframe['OS_id_30'] = dataframe['id_30'].str.split(' ', expand=True)[0]
dataframe['version_id_30'] = dataframe['id_30'].str.split(' ', expand=True)[1]
dataframe['browser_id_31'] = dataframe['id_31'].str.split(' ', expand=True)[0]
dataframe['version_id_31'] = dataframe['id_31'].str.split(' ', expand=True)[1]
dataframe['screen_width'] = dataframe['id_33'].str.split('x', expand=True)[0]
dataframe['screen_height'] = dataframe['id_33'].str.split('x', expand=True)[1]
dataframe['id_34'] = dataframe['id_34'].str.split(':', expand=True)[1]
dataframe['id_23'] = dataframe['id_23'].str.split(':', expand=True)[1]
dataframe.loc[dataframe['device_name'].str.contains('SM', na=False), 'device_name'] = 'Samsung'
dataframe.loc[dataframe['device_name'].str.contains('SAMSUNG', na=False), 'device_name'] = 'Samsung'
dataframe.loc[dataframe['device_name'].str.contains('GT-', na=False), 'device_name'] = 'Samsung'
dataframe.loc[dataframe['device_name'].str.contains('Moto G', na=False), 'device_name'] = 'Motorola'
dataframe.loc[dataframe['device_name'].str.contains('Moto', na=False), 'device_name'] = 'Motorola'
dataframe.loc[dataframe['device_name'].str.contains('moto', na=False), 'device_name'] = 'Motorola'
dataframe.loc[dataframe['device_name'].str.contains('LG-', na=False), 'device_name'] = 'LG'
dataframe.loc[dataframe['device_name'].str.contains('rv:', na=False), 'device_name'] = 'RV'
dataframe.loc[dataframe['device_name'].str.contains('HUAWEI', na=False), 'device_name'] = 'Huawei'
dataframe.loc[dataframe['device_name'].str.contains('ALE-', na=False), 'device_name'] = 'Huawei'
dataframe.loc[dataframe['device_name'].str.contains('-L', na=False), 'device_name'] = 'Huawei'
dataframe.loc[dataframe['device_name'].str.contains('Blade', na=False), 'device_name'] = 'ZTE'
dataframe.loc[dataframe['device_name'].str.contains('BLADE', na=False), 'device_name'] = 'ZTE'
dataframe.loc[dataframe['device_name'].str.contains('Linux', na=False), 'device_name'] = 'Linux'
dataframe.loc[dataframe['device_name'].str.contains('XT', na=False), 'device_name'] = 'Sony'
dataframe.loc[dataframe['device_name'].str.contains('HTC', na=False), 'device_name'] = 'HTC'
dataframe.loc[dataframe['device_name'].str.contains('ASUS', na=False), 'device_name'] = 'Asus'
dataframe.loc[dataframe.device_name.isin(dataframe.device_name.value_counts()[dataframe.device_name.value_counts() < 200].index), 'device_name'] = "Others"
dataframe['had_id'] = 1
gc.collect()
return dataframe
train_identity = id_split(train_identity)
test_identity = id_split(test_identity)
#Data joining
train = pd.merge(train_transaction, train_identity, on='TransactionID', how='left', left_index=True, right_index=True)
test = pd.merge(test_transaction, test_identity, on='TransactionID', how='left', left_index=True, right_index=True)
print('Data was successfully merged!\n')
del train_identity, train_transaction, test_identity, test_transaction
print(f'Train dataset has {train.shape[0]} rows and {train.shape[1]} columns.')
print(f'Test dataset has {test.shape[0]} rows and {test.shape[1]} columns.\n')
#============================================================================
useful_features = ['isFraud', 'TransactionDT', 'TransactionAmt', 'ProductCD', 'card1', 'card2', 'card3', 'card4', 'card5', 'card6', 'addr1', 'addr2', 'dist1',
'P_emaildomain', 'R_emaildomain', 'C1', 'C2', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9', 'C10', 'C11', 'C12', 'C13',
'C14', 'D1', 'D2', 'D3', 'D4', 'D5', 'D10', 'D11', 'D15', 'M2', 'M3', 'M4', 'M5', 'M6', 'M7', 'M8', 'M9',
'V3', 'V4', 'V5', 'V6', 'V7', 'V8', 'V9', 'V10', 'V11', 'V12', 'V13', 'V17',
'V19', 'V20', 'V29', 'V30', 'V33', 'V34', 'V35', 'V36', 'V37', 'V38', 'V40', 'V44', 'V45', 'V46', 'V47', 'V48',
'V49', 'V51', 'V52', 'V53', 'V54', 'V56', 'V58', 'V59', 'V60', 'V61', 'V62', 'V63', 'V64', 'V69', 'V70', 'V71',
'V72', 'V73', 'V74', 'V75', 'V76', 'V78', 'V80', 'V81', 'V82', 'V83', 'V84', 'V85', 'V87', 'V90', 'V91', 'V92',
'V93', 'V94', 'V95', 'V96', 'V97', 'V99', 'V100', 'V126', 'V127', 'V128', 'V130', 'V131', 'V138', 'V139', 'V140',
'V143', 'V145', 'V146', 'V147', 'V149', 'V150', 'V151', 'V152', 'V154', 'V156', 'V158', 'V159', 'V160', 'V161',
'V162', 'V163', 'V164', 'V165', 'V166', 'V167', 'V169', 'V170', 'V171', 'V172', 'V173', 'V175', 'V176', 'V177',
'V178', 'V180', 'V182', 'V184', 'V187', 'V188', 'V189', 'V195', 'V197', 'V200', 'V201', 'V202', 'V203', 'V204',
'V205', 'V206', 'V207', 'V208', 'V209', 'V210', 'V212', 'V213', 'V214', 'V215', 'V216', 'V217', 'V219', 'V220',
'V221', 'V222', 'V223', 'V224', 'V225', 'V226', 'V227', 'V228', 'V229', 'V231', 'V233', 'V234', 'V238', 'V239',
'V242', 'V243', 'V244', 'V245', 'V246', 'V247', 'V249', 'V251', 'V253', 'V256', 'V257', 'V258', 'V259', 'V261',
'V262', 'V263', 'V264', 'V265', 'V266', 'V267', 'V268', 'V270', 'V271', 'V272', 'V273', 'V274', 'V275', 'V276',
'V277', 'V278', 'V279', 'V280', 'V282', 'V283', 'V285', 'V287', 'V288', 'V289', 'V291', 'V292', 'V294', 'V303',
'V304', 'V306', 'V307', 'V308', 'V310', 'V312', 'V313', 'V314', 'V315', 'V317', 'V322', 'V323', 'V324', 'V326',
'V329', 'V331', 'V332', 'V333', 'V335', 'V336', 'V338', 'id_01', 'id_02', 'id_05', 'id_06',
'id_11', 'id_12', 'id_13', 'id_15', 'id_17', 'id_19', 'id_20', 'id_31', 'id_36', 'id_37', 'id_38', 'DeviceType',
'DeviceInfo', 'device_name', 'device_version', 'OS_id_30', 'version_id_30',
'browser_id_31', 'version_id_31', 'screen_width', 'screen_height', 'had_id']
cols_to_drop = [col for col in train.columns if col not in useful_features]
train = train.drop(cols_to_drop, axis=1)
test = test.drop(cols_to_drop, axis=1)
#Merging email columns
train.P_emaildomain.fillna(train.R_emaildomain, inplace=True)
del train['R_emaildomain']
test.P_emaildomain.fillna(test.R_emaildomain, inplace=True)
del test['R_emaildomain']
# New feature - log of transaction amount. ()
train['TransactionAmt_Log'] = np.log(train['TransactionAmt'])
test['TransactionAmt_Log'] = np.log(test['TransactionAmt'])
# New feature - decimal part of the transaction amount.
train['TransactionAmt_decimal'] = ((train['TransactionAmt'] - train['TransactionAmt'].astype(int)) * 1000).astype(int)
test['TransactionAmt_decimal'] = ((test['TransactionAmt'] - test['TransactionAmt'].astype(int)) * 1000).astype(int)
# New feature - day of week in which a transaction happened.
train['Transaction_day_of_week'] = np.floor((train['TransactionDT'] / (3600 * 24) - 1) % 7)
test['Transaction_day_of_week'] = np.floor((test['TransactionDT'] / (3600 * 24) - 1) % 7)
# New feature - hour of the day in which a transaction happened.
train['Transaction_hour'] = np.floor(train['TransactionDT'] / 3600) % 24
test['Transaction_hour'] = np.floor(test['TransactionDT'] / 3600) % 24
del train['TransactionAmt'], train['TransactionDT']
del test['TransactionAmt'], test['TransactionDT']
#handling missing values -- replacing with -999
train.replace(np.nan, -999, inplace=True)
test.replace(np.nan, -999, inplace=True)
train.isnull().sum()
test.isnull().sum()
#=====================
#You can use isnull with mean for treshold and then remove columns by boolean
# indexing with loc (because remove columns), also need invert condition -
# so <.8 means remove all columns >=0.8:
#
#df = df.loc[:, df.isnull().mean() < .8]
#Label Encoding
# Encoding - count encoding for both train and test
for feature in ['card1', 'card2', 'card3', 'card4', 'card5', 'card6', 'id_36']:
train[feature + '_count_full'] = train[feature].map(pd.concat([train[feature], test[feature]], ignore_index=True).value_counts(dropna=False))
test[feature + '_count_full'] = test[feature].map(
|
pd.concat([train[feature], test[feature]], ignore_index=True)
|
pandas.concat
|
import numpy as np
import pandas as pd
def haversine(lat1, lon1, lat2, lon2, to_radians=True, earth_radius=6371):
if to_radians:
lat1, lon1, lat2, lon2 = np.radians([lat1, lon1, lat2, lon2])
a = np.sin((lat2-lat1)/2.0)**2 + \
np.cos(lat1) * np.cos(lat2) * np.sin((lon2-lon1)/2.0)**2
return earth_radius * 2 * np.arcsin(np.sqrt(a)) * 1000
def extract_displacement_speed_acceleration(csv_filepath):
df =
|
pd.read_csv(csv_filepath)
|
pandas.read_csv
|
import pandas as pd
tools = pd.read_csv("clean_bitcoin_otc.csv")
tools = tools.values.tolist()
curr = set()
for t in tools:
curr = curr.union([t[0],t[1]])
curr = list(curr)
mapper= {c:ind for ind, c in enumerate(curr)}
tools = [[mapper[t[0]],mapper[t[1]],t[2]] for t in tools]
tools =
|
pd.DataFrame(tools, columns = ["id1","id2","sign"])
|
pandas.DataFrame
|
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/03_manage_data.ipynb (unless otherwise specified).
__all__ = ['NORMALIZE', 'HORIZONS', 'COLUMNS', 'savePredict', 'loadPredict', 'updatePredicts', 'doNewPredicts',
'infoDatesPredicts']
# Cell
from .load_model import getAllHorizonPrediction
import datetime
import numpy as np
from .resources import getInfo
import csv
import pandas as pd
import pickle
from fastcore.script import * # @Callparser
NORMALIZE=707.6
HORIZONS=[3,5,7,10,14,21,27]
COLUMNS=['Date','H3','H5','H7','H10','H14','H21','H27']
# Cell
def savePredict(datalist):
path=getInfo("csvdirectory")+"predictionData.csv"
try:
outfile = open(path, 'wb')
pickle.dump(datalist, outfile )
finally:
outfile.close()
# Cell
def loadPredict():
predict= pd.DataFrame(columns=COLUMNS)
path=getInfo("csvdirectory")+"predictionData.csv"
try:
with open(path,'rb') as infile:
predict = pickle.load(infile, encoding='bytes')
infile.close()
except IOError:
print("File not accessible")
return predict
# Cell
@call_parse
def updatePredicts():
path=getInfo("csvdirectory")+"predictionData.csv"
datapredict=loadPredict()
if(not datapredict.empty):
yesterday = datetime.datetime.today().date()-datetime.timedelta(1)
predictdate=pd.to_datetime(datapredict.loc[0,"Date"])+datetime.timedelta(1) #First date to predict
if(yesterday >= predictdate):
while(yesterday >= predictdate):# while yesterday is not in the past of data(predictdate)
#print(predictdate,yesterday)
print("Currently making ", predictdate.strftime("%Y-%m-%d") ," prediction")
currentpredict=getAllHorizonPrediction(predictdate)
datapredict=pd.concat([pd.DataFrame(currentpredict,columns=COLUMNS), datapredict], ignore_index=True)
predictdate=predictdate+datetime.timedelta(1)
print("Updated to ",yesterday)
savePredict(datapredict)
else:
print("It was already updated")
else:
print("The file does not exist, you should make predictions to update")
# Cell
def doNewPredicts(days):
datapredict=loadPredict()
if(not datapredict.empty):
datestart=pd.to_datetime(datapredict.iloc[-1].Date)-datetime.timedelta(1)
else:
datestart=datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)-datetime.timedelta(1)
for numdays in range(days):
print((datestart-datetime.timedelta(numdays)).strftime("%Y-%m-%d"))
currentpredict=getAllHorizonPrediction(datestart-datetime.timedelta(numdays))
datapredict=pd.concat([datapredict,
|
pd.DataFrame(currentpredict,columns=COLUMNS)
|
pandas.DataFrame
|
from __future__ import absolute_import, division, unicode_literals
import unittest
import jsonpickle
from helper import SkippableTest
try:
import pandas as pd
import numpy as np
from pandas.testing import assert_series_equal
from pandas.testing import assert_frame_equal
from pandas.testing import assert_index_equal
except ImportError:
np = None
class PandasTestCase(SkippableTest):
def setUp(self):
if np is None:
self.should_skip = True
return
self.should_skip = False
import jsonpickle.ext.pandas
jsonpickle.ext.pandas.register_handlers()
def tearDown(self):
if self.should_skip:
return
import jsonpickle.ext.pandas
jsonpickle.ext.pandas.unregister_handlers()
def roundtrip(self, obj):
return jsonpickle.decode(jsonpickle.encode(obj))
def test_series_roundtrip(self):
if self.should_skip:
return self.skip('pandas is not importable')
ser = pd.Series(
{
'an_int': np.int_(1),
'a_float': np.float_(2.5),
'a_nan': np.nan,
'a_minus_inf': -np.inf,
'an_inf': np.inf,
'a_str': np.str_('foo'),
'a_unicode': np.unicode_('bar'),
'date': np.datetime64('2014-01-01'),
'complex': np.complex_(1 - 2j),
# TODO: the following dtypes are not currently supported.
# 'object': np.object_({'a': 'b'}),
}
)
decoded_ser = self.roundtrip(ser)
assert_series_equal(decoded_ser, ser)
def test_dataframe_roundtrip(self):
if self.should_skip:
return self.skip('pandas is not importable')
df = pd.DataFrame(
{
'an_int': np.int_([1, 2, 3]),
'a_float': np.float_([2.5, 3.5, 4.5]),
'a_nan': np.array([np.nan] * 3),
'a_minus_inf': np.array([-np.inf] * 3),
'an_inf': np.array([np.inf] * 3),
'a_str': np.str_('foo'),
'a_unicode': np.unicode_('bar'),
'date': np.array([np.datetime64('2014-01-01')] * 3),
'complex': np.complex_([1 - 2j, 2 - 1.2j, 3 - 1.3j]),
# TODO: the following dtypes are not currently supported.
# 'object': np.object_([{'a': 'b'}]*3),
}
)
decoded_df = self.roundtrip(df)
assert_frame_equal(decoded_df, df)
def test_multindex_dataframe_roundtrip(self):
if self.should_skip:
return self.skip('pandas is not importable')
df = pd.DataFrame(
{
'idx_lvl0': ['a', 'b', 'c'],
'idx_lvl1': np.int_([1, 1, 2]),
'an_int': np.int_([1, 2, 3]),
'a_float': np.float_([2.5, 3.5, 4.5]),
'a_nan': np.array([np.nan] * 3),
'a_minus_inf': np.array([-np.inf] * 3),
'an_inf': np.array([np.inf] * 3),
'a_str': np.str_('foo'),
'a_unicode': np.unicode_('bar'),
}
)
df = df.set_index(['idx_lvl0', 'idx_lvl1'])
decoded_df = self.roundtrip(df)
assert_frame_equal(decoded_df, df)
def test_dataframe_with_interval_index_roundtrip(self):
if self.should_skip:
return self.skip('pandas is not importable')
df = pd.DataFrame(
{'a': [1, 2], 'b': [3, 4]}, index=pd.IntervalIndex.from_breaks([1, 2, 4])
)
decoded_df = self.roundtrip(df)
assert_frame_equal(decoded_df, df)
def test_index_roundtrip(self):
if self.should_skip:
return self.skip('pandas is not importable')
idx = pd.Index(range(5, 10))
decoded_idx = self.roundtrip(idx)
assert_index_equal(decoded_idx, idx)
def test_datetime_index_roundtrip(self):
if self.should_skip:
return self.skip('pandas is not importable')
idx = pd.date_range(start='2019-01-01', end='2019-02-01', freq='D')
decoded_idx = self.roundtrip(idx)
assert_index_equal(decoded_idx, idx)
def test_ragged_datetime_index_roundtrip(self):
if self.should_skip:
return self.skip('pandas is not importable')
idx =
|
pd.DatetimeIndex(['2019-01-01', '2019-01-02', '2019-01-05'])
|
pandas.DatetimeIndex
|
import collections
import numpy as np
import pytest
from pandas.core.dtypes.dtypes import CategoricalDtype
import pandas as pd
from pandas import (
Categorical,
DataFrame,
Index,
Series,
isna,
)
import pandas._testing as tm
class TestCategoricalMissing:
def test_isna(self):
exp = np.array([False, False, True])
cat = Categorical(["a", "b", np.nan])
res = cat.isna()
tm.assert_numpy_array_equal(res, exp)
def test_na_flags_int_categories(self):
# #1457
categories = list(range(10))
labels = np.random.randint(0, 10, 20)
labels[::5] = -1
cat = Categorical(labels, categories, fastpath=True)
repr(cat)
tm.assert_numpy_array_equal(isna(cat), labels == -1)
def test_nan_handling(self):
# Nans are represented as -1 in codes
c = Categorical(["a", "b", np.nan, "a"])
tm.assert_index_equal(c.categories, Index(["a", "b"]))
tm.assert_numpy_array_equal(c._codes, np.array([0, 1, -1, 0], dtype=np.int8))
c[1] = np.nan
tm.assert_index_equal(c.categories, Index(["a", "b"]))
tm.assert_numpy_array_equal(c._codes, np.array([0, -1, -1, 0], dtype=np.int8))
# Adding nan to categories should make assigned nan point to the
# category!
c = Categorical(["a", "b", np.nan, "a"])
tm.assert_index_equal(c.categories, Index(["a", "b"]))
tm.assert_numpy_array_equal(c._codes, np.array([0, 1, -1, 0], dtype=np.int8))
def test_set_dtype_nans(self):
c = Categorical(["a", "b", np.nan])
result = c._set_dtype(CategoricalDtype(["a", "c"]))
tm.assert_numpy_array_equal(result.codes, np.array([0, -1, -1], dtype="int8"))
def test_set_item_nan(self):
cat = Categorical([1, 2, 3])
cat[1] = np.nan
exp = Categorical([1, np.nan, 3], categories=[1, 2, 3])
tm.assert_categorical_equal(cat, exp)
@pytest.mark.parametrize(
"fillna_kwargs, msg",
[
(
{"value": 1, "method": "ffill"},
"Cannot specify both 'value' and 'method'.",
),
({}, "Must specify a fill 'value' or 'method'."),
({"method": "bad"}, "Invalid fill method. Expecting .* bad"),
(
{"value": Series([1, 2, 3, 4, "a"])},
"Cannot setitem on a Categorical with a new category",
),
],
)
def test_fillna_raises(self, fillna_kwargs, msg):
# https://github.com/pandas-dev/pandas/issues/19682
# https://github.com/pandas-dev/pandas/issues/13628
cat = Categorical([1, 2, 3, None, None])
with pytest.raises(ValueError, match=msg):
cat.fillna(**fillna_kwargs)
@pytest.mark.parametrize("named", [True, False])
def test_fillna_iterable_category(self, named):
# https://github.com/pandas-dev/pandas/issues/21097
if named:
Point = collections.namedtuple("Point", "x y")
else:
Point = lambda *args: args # tuple
cat = Categorical(np.array([Point(0, 0), Point(0, 1), None], dtype=object))
result = cat.fillna(Point(0, 0))
expected = Categorical([Point(0, 0), Point(0, 1), Point(0, 0)])
tm.assert_categorical_equal(result, expected)
def test_fillna_array(self):
# accept Categorical or ndarray value if it holds appropriate values
cat = Categorical(["A", "B", "C", None, None])
other = cat.fillna("C")
result = cat.fillna(other)
tm.assert_categorical_equal(result, other)
assert isna(cat[-1]) # didnt modify original inplace
other = np.array(["A", "B", "C", "B", "A"])
result = cat.fillna(other)
expected = Categorical(["A", "B", "C", "B", "A"], dtype=cat.dtype)
tm.assert_categorical_equal(result, expected)
assert isna(cat[-1]) # didnt modify original inplace
@pytest.mark.parametrize(
"values, expected",
[
([1, 2, 3], np.array([False, False, False])),
([1, 2, np.nan], np.array([False, False, True])),
([1, 2, np.inf], np.array([False, False, True])),
([1, 2, pd.NA], np.array([False, False, True])),
],
)
def test_use_inf_as_na(self, values, expected):
# https://github.com/pandas-dev/pandas/issues/33594
with pd.option_context("mode.use_inf_as_na", True):
cat = Categorical(values)
result = cat.isna()
|
tm.assert_numpy_array_equal(result, expected)
|
pandas._testing.assert_numpy_array_equal
|
import pandas as pd
import numpy as np
import glob as glob
import seaborn as sns
import matplotlib.pyplot as plt
def filter_TDP(data_frame, thresh = 0.3):
"""[optional function that removes molecules that do not transition below threshold at some point]
Args:
data_frame ([dataframe]): [dataframe that has been cleaned to remove outliers by 'remove_outliers' function]
thresh (float, optional): [FRET value to threshold - will filter molecules and keep those that go below the thresh]. Defaults to 0.3.
Returns:
[dataframe]: [contains only molecules of interest]
"""
filtered_mol = []
for treatment, df in data_frame.groupby("treatment_name"):
mol_list = df[(df["FRET_before"] <= thresh)|(df["FRET_after"] <= thresh)].Molecule.unique().tolist()
filtered = df[df["Molecule"].isin(mol_list)]
filtered_mol.append(filtered)
filtered_mol = pd.concat(filtered_mol)
return filtered_mol
def remove_outliers(compiled, plot_type, data_type = "raw"):
"""[removes outliers from dataframe]
Args:
compiled ([dataframe]): [raw dataframe containing outliers to be removed]
plot_type ([str]): [string can either be 'hist' for histogram data or 'TDP' for TDP data]
data_type (str, optional): [removes either raw FRET values or 'idealized' FRET values]. Defaults to "raw".
Returns:
[dataframe]: [returns cleaned data without outliers]
"""
if plot_type == 'hist':
if data_type == "raw":
rawFRET = compiled[(compiled[3] > -0.5) & (compiled[3] < 1.5)].copy()
return rawFRET
if data_type == "idealized":
idealizedFRET = compiled[(compiled[4] > -0.5) & (compiled[4] < 1.5)].copy()
return idealizedFRET
elif plot_type == 'TDP':
outliers = compiled[(compiled["FRET before transition"] < -0.5)|(compiled["FRET before transition"] > 1.5)|(compiled["FRET after transition"] < -0.5) | (compiled["FRET after transition"] > 1.5)].index
compiled.drop(outliers, inplace = True)
return compiled
else:
print('invalid plot type, please set plot_type as "hist" or "TDP" - you idiot')
def cleanup_dwell(data, fps, thresh, first_dwell = "delete"):
"""[Will convert the data frome frame number to unit of time (seconds) and then delete all dwell times
that are smaller than the set threshold (defined previously) in seconds. Will also delete the first dwell
state from each molecule]
Args:
data ([dataframe]): [raw data]
first_dwell (str, optional): [Set to 'keep' to keep the first dwell state from each molecule otherwise
Will delete the first dwell state from each molecule by default]. Defaults to "delete".
Returns:
[dataframe]: [Data is now cleaned and ready for subsequent processing]
"""
if first_dwell == "delete":
filtered = []
for molecule, df in data.groupby("Molecule"):
filtered.append(df.iloc[1:])
filtered = pd.concat(filtered) #####filtered = pd.concat([df.iloc[1:] for molecule, df in A.groupby("Molecule")]) ##code here is the same as the for loop but in a list comprehension format
filtered["Time (s)"] = filtered["Time"]/fps
filtered = filtered[filtered["Time (s)"] >= thresh]
return filtered
if first_dwell == "keep":
data["Time (s)"] = data["Time"]/fps
data = data[data["Time (s)"] >= thresh]
return data
def filter_dwell(df, FRET_thresh, headers):
"""[Will take the cleaned TDP data and will filter it using a threshold (defined by FRET_thresh)
into seperate types of transitions (e.g., < 0.5 to > 0.5 FRET if FRET_thresh is = 0.5 is one example
of a type of transition).
Args:
df ([dataframe]): [contains cleaned data that has been processed using the 'cleanup_dwell' function]
Returns:
[dataframe]: [contains dwell time that has been categorized into each transition class]
"""
filtered_lowtohigh = df[(df["FRET_before"] < FRET_thresh) & (df["FRET_after"] > FRET_thresh)].copy()
filtered_lowtolow = df[(df["FRET_before"] < FRET_thresh) & (df["FRET_after"] < FRET_thresh)].copy()
filtered_hightolow = df[(df["FRET_before"] > FRET_thresh) & (df["FRET_after"] < FRET_thresh)].copy()
filtered_hightohigh = df[(df["FRET_before"] > FRET_thresh) & (df["FRET_after"] > FRET_thresh)].copy()
dataf = [filtered_lowtolow["Time (s)"], filtered_lowtohigh["Time (s)"], filtered_hightohigh["Time (s)"], filtered_hightolow["Time (s)"]]
df_col = pd.concat(dataf, axis = 1, keys = headers)
df_col = df_col.apply(lambda x:pd.Series(x.dropna().values)) ## removes NaN values from each column in df_col
return df_col
def transition_frequency(filt):
"""calculates the transition frequency (i.e., the number of transitions per transition class divided
by the total number of transitions observed). For example if there are 40 transitions total, and a
< 0.5 to > 0.5 transition occurs 10 times, then the transition probability for that transition type is
0.25 or 25%.
Args:
filt (dataframe): contains the dataframe with filtered data (cleaned data has been filtered by
'filter_dwell' function)
Returns:
dataframe: returns a dataframe containing the percentage for each transition type
"""
count_df_col = pd.DataFrame(filt.count(axis = 0)).transpose()
count_df_col["sum"] = count_df_col.sum(axis = 1)
dwell_frequency = pd.DataFrame([(count_df_col[column]/count_df_col["sum"])*100 for column in count_df_col]).transpose()
print(dwell_frequency)
return dwell_frequency
def calculate_mean(filtered_data, treatment_name):
"""calculates the mean dwell time of each type of transition class
Args:
filtered_data (dataframe): dataframe generated after the 'cleanup_dwell' and 'filter_dwell' functions
have been run
treatment_name (str): not required, only present to receive input from for loop. set to treatment_name
Returns:
[dataframe]: returns dataframe containing the mean of each transition class
"""
mean_dwell = pd.DataFrame([filtered_data.iloc[0:].mean()])
mean_dwell["sample"] = treatment_name
return mean_dwell
def float_generator(data_frame, treatment, FRET_thresh):
"""Will generate the float values used to scale the size of the arrows when plotting the summary heatmap
Args:
data_frame (dataframe): Takes dataframe containing the transition frequencies generated using the
'transition_frequency' function
treatment (str): will take 'treatment' from for loop. Leave as treatment.
Returns:
[dataframe]: returns values used to scale arrow -
"""
transition_frequency_arrow = data_frame[data_frame["sample"]== treatment]
normalised_number_lowtohigh = float(np.array(transition_frequency_arrow[f"< {FRET_thresh} to > {FRET_thresh}"])/1000)
normalised_number_hightolow = float(np.array(transition_frequency_arrow[f"> {FRET_thresh} to < {FRET_thresh}"])/1000)
normalised_number_hightohigh = float(np.array(transition_frequency_arrow[f"> {FRET_thresh} to > {FRET_thresh}"])/1000)
normalised_number_lowtolow = float(np.array(transition_frequency_arrow[f"< {FRET_thresh} to < {FRET_thresh}"])/1000)
arrow_list = [normalised_number_lowtohigh,normalised_number_hightolow,normalised_number_hightohigh,normalised_number_lowtolow]
return arrow_list
def heatmap_prep(histogram_data, treatment, FRET_thresh):
"""Takes the data and calculates the number of data points total (total), how much data points are below
a threshold (time below) and above a threshold (time above) and will use these values to calculate what proportion
of time the FRET is below or above thresh. Will then feed into the heatmap when plotting
Args:
histogram_data (dataframe): data used to plot the histogram - will include all the cleaned FRET and
idealized FRET values (time not a factor here, just number of frames)
treatment (str): only used to be fed from for loop. do not change
Returns:
df: contains the data required to plot the heatmap. will be as a proportion of time spent below or above
threshold
"""
subset_data = histogram_data[histogram_data["treatment_name"]==treatment]
total = len(subset_data[(subset_data["FRET"] < FRET_thresh) | (subset_data["FRET"] > FRET_thresh)])
subset_data_largerthanthresh = len(subset_data[subset_data["FRET"] > FRET_thresh])
subset_data_lessthanthresh = len(subset_data[subset_data["FRET"] < FRET_thresh])
time_below = (subset_data_lessthanthresh/total)
time_above = (subset_data_largerthanthresh/total)
thresh_dicts = {f"< {FRET_thresh}":[time_below], f"> {FRET_thresh}":[time_above] }
thresh_dfs = pd.DataFrame(thresh_dicts)
#thresh_dfs["treatment"] = treatment
return thresh_dfs
def mean_dwell_prep(mean_dwell_data, treatment, FRET_thresh):
"""calculates the mean values for each transition class and converts to float values for plotting in
summary heatmap
Args:
mean_dwell_data (dataframe): dataframe containing mean values
treatment (str): used for a for loop. do not change.
Returns:
[list]: contains list of float values
"""
subset_mean_dwell = mean_dwell_data[mean_dwell_data["sample"]== treatment]
meandwell_lowtohigh = float(np.array(subset_mean_dwell[f"< {FRET_thresh} to > {FRET_thresh}"]))
meandwell_hightolow = float(np.array(subset_mean_dwell[f"> {FRET_thresh} to < {FRET_thresh}"]))
meandwell_hightohigh = float(np.array(subset_mean_dwell[f"> {FRET_thresh} to > {FRET_thresh}"]))
meandwell_lowtolow = float(np.array(subset_mean_dwell[f"< {FRET_thresh} to < {FRET_thresh}"]))
mean_list = [meandwell_lowtohigh,meandwell_hightolow,meandwell_hightohigh,meandwell_lowtolow]
return mean_list
def file_reader(input_folder, data_type, frame_rate = False, column_names = False):
"""will import data
Args:
input_folder (directory): where data is stored
data_type (str): what data will be used to plot, needs to be either 'hist', 'TDP', 'transition_frequency'
or 'other'.
Returns:
dataframe: dataframe with data to be used in subseqeunt codes
"""
if data_type == 'hist':
filenames = glob.glob(input_folder + "/*.dat")
dfs = []
for filename in filenames:
molecule_number = filename.split('\\')[1].split('_')[0]
hist_data = pd.read_table(filename, sep="\s+", header=None)
hist_data['molecule number'] = molecule_number
dfs.append(hist_data) ### will error if forward slash (e.g. "/s+")
test = pd.concat(dfs)
test_dfs = pd.DataFrame(test)
return test_dfs
elif data_type == 'TDP':
filename = input_folder
A = pd.read_table(filename, header = None, sep="\s+")
A.columns = ['Molecule', 'Idealized_FRET']
return A
elif data_type == 'transition_frequency':
if not column_names:
print('no column_names found, specify list to use')
return
filenames = glob.glob(input_folder + "/*.csv")
dfs = []
for filename in filenames:
dfs.append(
|
pd.read_csv(filename, header=None)
|
pandas.read_csv
|
from collections import (
abc,
deque,
)
from decimal import Decimal
from warnings import catch_warnings
import numpy as np
import pytest
import pandas as pd
from pandas import (
DataFrame,
Index,
MultiIndex,
PeriodIndex,
Series,
concat,
date_range,
)
import pandas._testing as tm
from pandas.core.arrays import SparseArray
from pandas.core.construction import create_series_with_explicit_dtype
from pandas.tests.extension.decimal import to_decimal
class TestConcatenate:
def test_append_concat(self):
# GH#1815
d1 = date_range("12/31/1990", "12/31/1999", freq="A-DEC")
d2 = date_range("12/31/2000", "12/31/2009", freq="A-DEC")
s1 = Series(np.random.randn(10), d1)
s2 = Series(np.random.randn(10), d2)
s1 = s1.to_period()
s2 = s2.to_period()
# drops index
result = concat([s1, s2])
assert isinstance(result.index, PeriodIndex)
assert result.index[0] == s1.index[0]
def test_concat_copy(self, using_array_manager):
df = DataFrame(np.random.randn(4, 3))
df2 = DataFrame(np.random.randint(0, 10, size=4).reshape(4, 1))
df3 = DataFrame({5: "foo"}, index=range(4))
# These are actual copies.
result = concat([df, df2, df3], axis=1, copy=True)
for arr in result._mgr.arrays:
assert arr.base is None
# These are the same.
result = concat([df, df2, df3], axis=1, copy=False)
for arr in result._mgr.arrays:
if arr.dtype.kind == "f":
assert arr.base is df._mgr.arrays[0].base
elif arr.dtype.kind in ["i", "u"]:
assert arr.base is df2._mgr.arrays[0].base
elif arr.dtype == object:
if using_array_manager:
# we get the same array object, which has no base
assert arr is df3._mgr.arrays[0]
else:
assert arr.base is not None
# Float block was consolidated.
df4 = DataFrame(np.random.randn(4, 1))
result = concat([df, df2, df3, df4], axis=1, copy=False)
for arr in result._mgr.arrays:
if arr.dtype.kind == "f":
if using_array_manager:
# this is a view on some array in either df or df4
assert any(
np.shares_memory(arr, other)
for other in df._mgr.arrays + df4._mgr.arrays
)
else:
# the block was consolidated, so we got a copy anyway
assert arr.base is None
elif arr.dtype.kind in ["i", "u"]:
assert arr.base is df2._mgr.arrays[0].base
elif arr.dtype == object:
# this is a view on df3
assert any(np.shares_memory(arr, other) for other in df3._mgr.arrays)
def test_concat_with_group_keys(self):
# axis=0
df = DataFrame(np.random.randn(3, 4))
df2 = DataFrame(np.random.randn(4, 4))
result = concat([df, df2], keys=[0, 1])
exp_index = MultiIndex.from_arrays(
[[0, 0, 0, 1, 1, 1, 1], [0, 1, 2, 0, 1, 2, 3]]
)
expected = DataFrame(np.r_[df.values, df2.values], index=exp_index)
tm.assert_frame_equal(result, expected)
result = concat([df, df], keys=[0, 1])
exp_index2 = MultiIndex.from_arrays([[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 1, 2]])
expected = DataFrame(np.r_[df.values, df.values], index=exp_index2)
tm.assert_frame_equal(result, expected)
# axis=1
df = DataFrame(np.random.randn(4, 3))
df2 = DataFrame(np.random.randn(4, 4))
result = concat([df, df2], keys=[0, 1], axis=1)
expected = DataFrame(np.c_[df.values, df2.values], columns=exp_index)
tm.assert_frame_equal(result, expected)
result = concat([df, df], keys=[0, 1], axis=1)
expected = DataFrame(np.c_[df.values, df.values], columns=exp_index2)
tm.assert_frame_equal(result, expected)
def test_concat_keys_specific_levels(self):
df = DataFrame(np.random.randn(10, 4))
pieces = [df.iloc[:, [0, 1]], df.iloc[:, [2]], df.iloc[:, [3]]]
level = ["three", "two", "one", "zero"]
result = concat(
pieces,
axis=1,
keys=["one", "two", "three"],
levels=[level],
names=["group_key"],
)
tm.assert_index_equal(result.columns.levels[0], Index(level, name="group_key"))
tm.assert_index_equal(result.columns.levels[1], Index([0, 1, 2, 3]))
assert result.columns.names == ["group_key", None]
@pytest.mark.parametrize("mapping", ["mapping", "dict"])
def test_concat_mapping(self, mapping, non_dict_mapping_subclass):
constructor = dict if mapping == "dict" else non_dict_mapping_subclass
frames = constructor(
{
"foo": DataFrame(np.random.randn(4, 3)),
"bar": DataFrame(np.random.randn(4, 3)),
"baz": DataFrame(np.random.randn(4, 3)),
"qux": DataFrame(np.random.randn(4, 3)),
}
)
sorted_keys = list(frames.keys())
result = concat(frames)
expected = concat([frames[k] for k in sorted_keys], keys=sorted_keys)
tm.assert_frame_equal(result, expected)
result = concat(frames, axis=1)
expected = concat([frames[k] for k in sorted_keys], keys=sorted_keys, axis=1)
tm.assert_frame_equal(result, expected)
keys = ["baz", "foo", "bar"]
result = concat(frames, keys=keys)
expected = concat([frames[k] for k in keys], keys=keys)
tm.assert_frame_equal(result, expected)
def test_concat_keys_and_levels(self):
df = DataFrame(np.random.randn(1, 3))
df2 = DataFrame(np.random.randn(1, 4))
levels = [["foo", "baz"], ["one", "two"]]
names = ["first", "second"]
result = concat(
[df, df2, df, df2],
keys=[("foo", "one"), ("foo", "two"), ("baz", "one"), ("baz", "two")],
levels=levels,
names=names,
)
expected = concat([df, df2, df, df2])
exp_index = MultiIndex(
levels=levels + [[0]],
codes=[[0, 0, 1, 1], [0, 1, 0, 1], [0, 0, 0, 0]],
names=names + [None],
)
expected.index = exp_index
tm.assert_frame_equal(result, expected)
# no names
result = concat(
[df, df2, df, df2],
keys=[("foo", "one"), ("foo", "two"), ("baz", "one"), ("baz", "two")],
levels=levels,
)
assert result.index.names == (None,) * 3
# no levels
result = concat(
[df, df2, df, df2],
keys=[("foo", "one"), ("foo", "two"), ("baz", "one"), ("baz", "two")],
names=["first", "second"],
)
assert result.index.names == ("first", "second", None)
tm.assert_index_equal(
result.index.levels[0], Index(["baz", "foo"], name="first")
)
def test_concat_keys_levels_no_overlap(self):
# GH #1406
df = DataFrame(np.random.randn(1, 3), index=["a"])
df2 = DataFrame(np.random.randn(1, 4), index=["b"])
msg = "Values not found in passed level"
with pytest.raises(ValueError, match=msg):
concat([df, df], keys=["one", "two"], levels=[["foo", "bar", "baz"]])
msg = "Key one not in level"
with pytest.raises(ValueError, match=msg):
concat([df, df2], keys=["one", "two"], levels=[["foo", "bar", "baz"]])
def test_crossed_dtypes_weird_corner(self):
columns = ["A", "B", "C", "D"]
df1 = DataFrame(
{
"A": np.array([1, 2, 3, 4], dtype="f8"),
"B": np.array([1, 2, 3, 4], dtype="i8"),
"C": np.array([1, 2, 3, 4], dtype="f8"),
"D": np.array([1, 2, 3, 4], dtype="i8"),
},
columns=columns,
)
df2 = DataFrame(
{
"A": np.array([1, 2, 3, 4], dtype="i8"),
"B": np.array([1, 2, 3, 4], dtype="f8"),
"C": np.array([1, 2, 3, 4], dtype="i8"),
"D": np.array([1, 2, 3, 4], dtype="f8"),
},
columns=columns,
)
appended = df1.append(df2, ignore_index=True)
expected = DataFrame(
np.concatenate([df1.values, df2.values], axis=0), columns=columns
)
tm.assert_frame_equal(appended, expected)
df = DataFrame(np.random.randn(1, 3), index=["a"])
df2 = DataFrame(np.random.randn(1, 4), index=["b"])
result = concat([df, df2], keys=["one", "two"], names=["first", "second"])
assert result.index.names == ("first", "second")
def test_with_mixed_tuples(self, sort):
# 10697
# columns have mixed tuples, so handle properly
df1 = DataFrame({"A": "foo", ("B", 1): "bar"}, index=range(2))
df2 = DataFrame({"B": "foo", ("B", 1): "bar"}, index=range(2))
# it works
concat([df1, df2], sort=sort)
def test_concat_mixed_objs(self):
# concat mixed series/frames
# G2385
# axis 1
index = date_range("01-Jan-2013", periods=10, freq="H")
arr = np.arange(10, dtype="int64")
s1 = Series(arr, index=index)
s2 = Series(arr, index=index)
df = DataFrame(arr.reshape(-1, 1), index=index)
expected = DataFrame(
np.repeat(arr, 2).reshape(-1, 2), index=index, columns=[0, 0]
)
result = concat([df, df], axis=1)
tm.assert_frame_equal(result, expected)
expected = DataFrame(
np.repeat(arr, 2).reshape(-1, 2), index=index, columns=[0, 1]
)
result = concat([s1, s2], axis=1)
tm.assert_frame_equal(result, expected)
expected = DataFrame(
np.repeat(arr, 3).reshape(-1, 3), index=index, columns=[0, 1, 2]
)
result = concat([s1, s2, s1], axis=1)
tm.assert_frame_equal(result, expected)
expected = DataFrame(
np.repeat(arr, 5).reshape(-1, 5), index=index, columns=[0, 0, 1, 2, 3]
)
result = concat([s1, df, s2, s2, s1], axis=1)
tm.assert_frame_equal(result, expected)
# with names
s1.name = "foo"
expected = DataFrame(
np.repeat(arr, 3).reshape(-1, 3), index=index, columns=["foo", 0, 0]
)
result = concat([s1, df, s2], axis=1)
tm.assert_frame_equal(result, expected)
s2.name = "bar"
expected = DataFrame(
np.repeat(arr, 3).reshape(-1, 3), index=index, columns=["foo", 0, "bar"]
)
result = concat([s1, df, s2], axis=1)
tm.assert_frame_equal(result, expected)
# ignore index
expected = DataFrame(
np.repeat(arr, 3).reshape(-1, 3), index=index, columns=[0, 1, 2]
)
result = concat([s1, df, s2], axis=1, ignore_index=True)
tm.assert_frame_equal(result, expected)
# axis 0
expected = DataFrame(
np.tile(arr, 3).reshape(-1, 1), index=index.tolist() * 3, columns=[0]
)
result = concat([s1, df, s2])
tm.assert_frame_equal(result, expected)
expected = DataFrame(np.tile(arr, 3).reshape(-1, 1), columns=[0])
result = concat([s1, df, s2], ignore_index=True)
tm.assert_frame_equal(result, expected)
def test_dtype_coerceion(self):
# 12411
df = DataFrame({"date": [pd.Timestamp("20130101").tz_localize("UTC"), pd.NaT]})
result = concat([df.iloc[[0]], df.iloc[[1]]])
tm.assert_series_equal(result.dtypes, df.dtypes)
# 12045
import datetime
df = DataFrame(
{"date": [datetime.datetime(2012, 1, 1), datetime.datetime(1012, 1, 2)]}
)
result = concat([df.iloc[[0]], df.iloc[[1]]])
tm.assert_series_equal(result.dtypes, df.dtypes)
# 11594
df = DataFrame({"text": ["some words"] + [None] * 9})
result = concat([df.iloc[[0]], df.iloc[[1]]])
tm.assert_series_equal(result.dtypes, df.dtypes)
def test_concat_single_with_key(self):
df = DataFrame(np.random.randn(10, 4))
result = concat([df], keys=["foo"])
expected = concat([df, df], keys=["foo", "bar"])
tm.assert_frame_equal(result, expected[:10])
def test_concat_no_items_raises(self):
with pytest.raises(ValueError, match="No objects to concatenate"):
concat([])
def test_concat_exclude_none(self):
df = DataFrame(np.random.randn(10, 4))
pieces = [df[:5], None, None, df[5:]]
result = concat(pieces)
tm.assert_frame_equal(result, df)
with pytest.raises(ValueError, match="All objects passed were None"):
concat([None, None])
def test_concat_keys_with_none(self):
# #1649
df0 = DataFrame([[10, 20, 30], [10, 20, 30], [10, 20, 30]])
result = concat({"a": None, "b": df0, "c": df0[:2], "d": df0[:1], "e": df0})
expected = concat({"b": df0, "c": df0[:2], "d": df0[:1], "e": df0})
tm.assert_frame_equal(result, expected)
result = concat(
[None, df0, df0[:2], df0[:1], df0], keys=["a", "b", "c", "d", "e"]
)
expected = concat([df0, df0[:2], df0[:1], df0], keys=["b", "c", "d", "e"])
tm.assert_frame_equal(result, expected)
def test_concat_bug_1719(self):
ts1 = tm.makeTimeSeries()
ts2 = tm.makeTimeSeries()[::2]
# to join with union
# these two are of different length!
left = concat([ts1, ts2], join="outer", axis=1)
right = concat([ts2, ts1], join="outer", axis=1)
assert len(left) == len(right)
def test_concat_bug_2972(self):
ts0 = Series(np.zeros(5))
ts1 = Series(np.ones(5))
ts0.name = ts1.name = "same name"
result = concat([ts0, ts1], axis=1)
expected = DataFrame({0: ts0, 1: ts1})
expected.columns = ["same name", "same name"]
tm.assert_frame_equal(result, expected)
def test_concat_bug_3602(self):
# GH 3602, duplicate columns
df1 = DataFrame(
{
"firmNo": [0, 0, 0, 0],
"prc": [6, 6, 6, 6],
"stringvar": ["rrr", "rrr", "rrr", "rrr"],
}
)
df2 = DataFrame(
{"C": [9, 10, 11, 12], "misc": [1, 2, 3, 4], "prc": [6, 6, 6, 6]}
)
expected = DataFrame(
[
[0, 6, "rrr", 9, 1, 6],
[0, 6, "rrr", 10, 2, 6],
[0, 6, "rrr", 11, 3, 6],
[0, 6, "rrr", 12, 4, 6],
]
)
expected.columns = ["firmNo", "prc", "stringvar", "C", "misc", "prc"]
result = concat([df1, df2], axis=1)
tm.assert_frame_equal(result, expected)
def test_concat_iterables(self):
# GH8645 check concat works with tuples, list, generators, and weird
# stuff like deque and custom iterables
df1 = DataFrame([1, 2, 3])
df2 = DataFrame([4, 5, 6])
expected = DataFrame([1, 2, 3, 4, 5, 6])
tm.assert_frame_equal(concat((df1, df2), ignore_index=True), expected)
tm.assert_frame_equal(concat([df1, df2], ignore_index=True), expected)
tm.assert_frame_equal(
concat((df for df in (df1, df2)), ignore_index=True), expected
)
tm.assert_frame_equal(concat(deque((df1, df2)), ignore_index=True), expected)
class CustomIterator1:
def __len__(self) -> int:
return 2
def __getitem__(self, index):
try:
return {0: df1, 1: df2}[index]
except KeyError as err:
raise IndexError from err
tm.assert_frame_equal(concat(CustomIterator1(), ignore_index=True), expected)
class CustomIterator2(abc.Iterable):
def __iter__(self):
yield df1
yield df2
tm.assert_frame_equal(concat(CustomIterator2(), ignore_index=True), expected)
def test_concat_order(self):
# GH 17344
dfs = [DataFrame(index=range(3), columns=["a", 1, None])]
dfs += [DataFrame(index=range(3), columns=[None, 1, "a"]) for i in range(100)]
result = concat(dfs, sort=True).columns
expected = dfs[0].columns
tm.assert_index_equal(result, expected)
def test_concat_different_extension_dtypes_upcasts(self):
a = Series(pd.array([1, 2], dtype="Int64"))
b = Series(to_decimal([1, 2]))
result = concat([a, b], ignore_index=True)
expected = Series([1, 2, Decimal(1), Decimal(2)], dtype=object)
tm.assert_series_equal(result, expected)
def test_concat_ordered_dict(self):
# GH 21510
expected = concat(
[Series(range(3)), Series(range(4))], keys=["First", "Another"]
)
result = concat({"First": Series(range(3)), "Another": Series(range(4))})
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("pdt", [Series, DataFrame])
@pytest.mark.parametrize("dt", np.sctypes["float"])
def test_concat_no_unnecessary_upcast(dt, pdt):
# GH 13247
dims = pdt(dtype=object).ndim
dfs = [
pdt(np.array([1], dtype=dt, ndmin=dims)),
pdt(np.array([np.nan], dtype=dt, ndmin=dims)),
pdt(np.array([5], dtype=dt, ndmin=dims)),
]
x = concat(dfs)
assert x.values.dtype == dt
@pytest.mark.parametrize("pdt", [create_series_with_explicit_dtype, DataFrame])
@pytest.mark.parametrize("dt", np.sctypes["int"])
def test_concat_will_upcast(dt, pdt):
with catch_warnings(record=True):
dims = pdt().ndim
dfs = [
pdt(np.array([1], dtype=dt, ndmin=dims)),
pdt(np.array([np.nan], ndmin=dims)),
pdt(np.array([5], dtype=dt, ndmin=dims)),
]
x = concat(dfs)
assert x.values.dtype == "float64"
def test_concat_empty_and_non_empty_frame_regression():
# GH 18178 regression test
df1 = DataFrame({"foo": [1]})
df2 = DataFrame({"foo": []})
expected = DataFrame({"foo": [1.0]})
result = concat([df1, df2])
tm.assert_frame_equal(result, expected)
def test_concat_sparse():
# GH 23557
a = Series(SparseArray([0, 1, 2]))
expected = DataFrame(data=[[0, 0], [1, 1], [2, 2]]).astype(
pd.SparseDtype(np.int64, 0)
)
result = concat([a, a], axis=1)
tm.assert_frame_equal(result, expected)
def test_concat_dense_sparse():
# GH 30668
a = Series(pd.arrays.SparseArray([1, None]), dtype=float)
b = Series([1], dtype=float)
expected = Series(data=[1, None, 1], index=[0, 1, 0]).astype(
pd.SparseDtype(np.float64, None)
)
result = concat([a, b], axis=0)
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("keys", [["e", "f", "f"], ["f", "e", "f"]])
def test_duplicate_keys(keys):
# GH 33654
df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
s1 = Series([7, 8, 9], name="c")
s2 = Series([10, 11, 12], name="d")
result = concat([df, s1, s2], axis=1, keys=keys)
expected_values = [[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]]
expected_columns = MultiIndex.from_tuples(
[(keys[0], "a"), (keys[0], "b"), (keys[1], "c"), (keys[2], "d")]
)
expected = DataFrame(expected_values, columns=expected_columns)
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize(
"obj",
[
tm.SubclassedDataFrame({"A": np.arange(0, 10)}),
tm.SubclassedSeries(np.arange(0, 10), name="A"),
],
)
def test_concat_preserves_subclass(obj):
# GH28330 -- preserve subclass
result = concat([obj, obj])
assert isinstance(result, type(obj))
def test_concat_frame_axis0_extension_dtypes():
# preserve extension dtype (through common_dtype mechanism)
df1 = DataFrame({"a": pd.array([1, 2, 3], dtype="Int64")})
df2 = DataFrame({"a": np.array([4, 5, 6])})
result = concat([df1, df2], ignore_index=True)
expected = DataFrame({"a": [1, 2, 3, 4, 5, 6]}, dtype="Int64")
tm.assert_frame_equal(result, expected)
result = concat([df2, df1], ignore_index=True)
expected = DataFrame({"a": [4, 5, 6, 1, 2, 3]}, dtype="Int64")
tm.assert_frame_equal(result, expected)
def test_concat_preserves_extension_int64_dtype():
# GH 24768
df_a = DataFrame({"a": [-1]}, dtype="Int64")
df_b = DataFrame({"b": [1]}, dtype="Int64")
result = concat([df_a, df_b], ignore_index=True)
expected = DataFrame({"a": [-1, None], "b": [None, 1]}, dtype="Int64")
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize(
"dtype1,dtype2,expected_dtype",
[
("bool", "bool", "bool"),
("boolean", "bool", "boolean"),
("bool", "boolean", "boolean"),
("boolean", "boolean", "boolean"),
],
)
def test_concat_bool_types(dtype1, dtype2, expected_dtype):
# GH 42800
ser1 = Series([True, False], dtype=dtype1)
ser2 = Series([False, True], dtype=dtype2)
result =
|
concat([ser1, ser2], ignore_index=True)
|
pandas.concat
|
'''
Module docstring
'''
import sys
import os
from importlib import reload
import tempfile
import string
import pyutilib
import contextlib
from collections import namedtuple
import numbers
import numpy as np
import pandas as pd
import pyomo.environ as po
from pyomo.core.base.objective import SimpleObjective
from pyomo.opt import SolverFactory
import grimsel.auxiliary.maps as maps
import grimsel.auxiliary.timemap as timemap
import grimsel.core.constraints as constraints
import grimsel.core.variables as variables
import grimsel.core.parameters as parameters
import grimsel.core.sets as sets
import grimsel.core.io as io # for class methods
from grimsel import _get_logger
logger = _get_logger(__name__)
def get_random_suffix():
return ''.join(np.random.choice(list(string.ascii_lowercase), 4))
#
#TEMP_DIR = 'grimsel_temp_' + get_random_suffix()
#def create_tempfile(self, suffix=None, prefix=None, text=False, dirc=None):
# """
# Return the absolute path of a temporary filename that is_init_pf_dicts
# guaranteed to be unique. This function generates the file and returns
# the filename.
# """
#
# logger.warn('!!!!!!!!tempfiles.TempfileManagerPlugin.create_tempfile '
# 'is monkey patched!!!!!!!!')
#
# if suffix is None:
# suffix = ''
# if prefix is None:
# prefix = 'tmp'
#
# ans = tempfile.mkstemp(suffix=suffix, prefix=prefix, text=text, dir=dirc)
# ans = list(ans)
# if not os.path.isabs(ans[1]): #pragma:nocover
# fname = os.path.join(dirc, ans[1])
# else:
# fname = ans[1]
# os.close(ans[0])
#
# dirc = TEMP_DIR
#
# if not os.path.isdir(dirc):
# os.mkdir(dirc)
#
# new_fname = os.path.join(dirc, 'grimsel_temp_' + get_random_suffix() + suffix)
# # Delete any file having the sequential name and then
# # rename
# if os.path.exists(new_fname):
# os.remove(new_fname)
# fname = new_fname
#
# self._tempfiles[-1].append(fname)
# return fname
#
#import pyutilib.component.config.tempfiles as tempfiles
#tempfiles.TempfileManagerPlugin.create_tempfile = create_tempfile
reload(constraints)
reload(variables)
reload(parameters)
reload(sets)
class ModelBase(po.ConcreteModel, constraints.Constraints,
parameters.Parameters, variables.Variables, sets.Sets):
# class attributes as defaults for presolve_fixed_capacities
list_vars = [('var_yr_cap_pwr_rem', 'cap_pwr_rem'),
('var_yr_cap_pwr_new', 'cap_pwr_new')]
list_constr_deact = ['set_win_sol']
# db = get_config('sql_connect')['db']
def __init__(self, **kwargs):
'''
Keyword arguments:
nhours -- time resolution of the model, used for profile scaling
sc_warmstart -- input database schema for presolving
slct_node -- limit node selection
slct_encar -- limit to energy carrier selection
skip_runs -- boolean; if True, solver calls are skipped, also
stops the IO instance from trying to write the model
variables.
'''
super(ModelBase, self).__init__() # init of po.ConcreteModel
defaults = {'slct_node': [],
'slct_pp_type': [],
'slct_node_connect': [],
'slct_encar': [],
'nhours': 1,
'unq_code': '',
'mps': None,
'tm_filt': False,
'verbose_solver': True,
'constraint_groups': None,
'symbolic_solver_labels': False,
'skip_runs': False,
'nthreads': False,
'keepfiles': True,
'tempdir': None}
for key, val in defaults.items():
setattr(self, key, val)
self.__dict__.update(kwargs)
self._check_contraint_groups()
logger.info('self.slct_encar=' + str(self.slct_encar))
logger.info('self.slct_pp_type=' + str(self.slct_pp_type))
logger.info('self.slct_node=' + str(self.slct_node))
logger.info('self.slct_node_connect=' + str(self.slct_node_connect))
logger.info('self.nhours=' + str(self.nhours))
logger.info('self.constraint_groups=' + str(self.constraint_groups))
self.warmstartfile = self.solutionfile = None
# attributes for presolve_fixed_capacities
self.list_vars = ModelBase.list_vars
self.list_constr_deact = ModelBase.list_constr_deact
# def _update_slct_lists(self):
# ''''''
# for attr, series in ((self.slct_encar, self.df_def_encar.ca),
# (self.slct_encar_id, self.df_def_encar.ca_id),
# (self.slct_pp_type_id, self.df_def_pp_type.pt),
# (self.slct_pp_type_id, self.df_def_pp_type.pt),
# (self.slct_node, self.df_def_node.nd)):
# if not attr:
# attr = series.tolist()
def build_model(self):
'''
Call the relevant model methods to get everything set up.
This consists in:
1. call self.get_setlst (in Sets mixin class) to initialize
the self.setlst dictionary
2. call self.define_sets (in Sets mixin class) to initialize
Pyomo set objects
3. call self.define_parameters (in Parameters mixin class)
4. call self.define_variables (in Variables mixin class)
5. call self.add_all_constraints
6. call self.init_solver
.. note::
io needs to have loaded all data, i.e. set the ModelBase
DataFrames.
'''
self.get_setlst()
self.define_sets()
self.define_parameters()
if not self.skip_runs:
self.define_variables()
self.add_all_constraints()
self.init_solver()
@classmethod
def get_constraint_groups(cls, excl=None):
'''
Returns list names of methods defining constraint groups.
This classmethod can also be used to define the constraint_groups
parameter to initialize the ModelBase object by selecting certain
groups to be excluded.
Parameters
----------
excl : list
exclude certain group names from the returned list
Returns
-------
list
Names of constraint groups. These correspond to the
methods in the :class:`Constraints` class without the prefix
`add_` and the suffix `_rules`
'''
cg_lst = [mth.replace('add_', '').replace('_rules', '')
for mth in dir(cls)
if mth.startswith('add_') and 'rule' in mth]
if excl:
cg_lst = [cg for cg in cg_lst if not cg in excl]
return cg_lst
def _check_contraint_groups(self):
'''
Verification and completion of the constraint group selection.
Verifies constraint groups if the ``constraint_groups`` argument
is not None. Otherwise it gathers all accordingly named
methods from the class attributes and populates the list thusly.
Raises
------
ValueError
If the :class:`ModelBase` instance attribute ``constraint_groups``
contains invalid entries.
'''
cg_options = self.get_constraint_groups()
if self.constraint_groups is None:
self.constraint_groups = cg_options
else:
# get invalid constraint groups in input
nv = [cg for cg in self.constraint_groups
if not cg in cg_options]
if nv:
estr = ('Invalid constraint group(s): {nv}.'
+ '\nPossible choices are:\n{cg}'
).format(nv=', '.join(nv), cg=',\n'.join(cg_options))
raise ValueError(estr)
def add_all_constraints(self):
'''
Call all selected methods from the constraint mixin class.
Loops through the `constraint_groups` list and calls the corresponding
methods in the :class:`.Constraints` mixing class.
'''
for cg in set(self.constraint_groups):
logger.info('##### Calling constraint group {}'.format(cg.upper()))
getattr(self, 'add_%s_rules'%cg)()
def _limit_prof_to_cap(self):
if len(self.chp) > 0:
self.limit_prof_to_cap()
def limit_prof_to_cap(self, param_mod='cap_pwr_leg'):
'''
Make sure CHP profiles don't ask for more power than feasible.
This operates on the parameters and is called before each model run.
'''
logger.info('Limiting chp profiles to cap_pwr_leg')
# get list of plants relevant for chp from corresponding set
pp_chp = self.setlst['chp']
df_chpprof = io.IO.param_to_df(self.chpprof, ('sy', 'nd_id', 'ca_id'))
df_erg_chp = io.IO.param_to_df(self.erg_chp, ('pp_id', 'ca_id'))
df_erg_chp = df_erg_chp.loc[df_erg_chp.pp_id.isin(pp_chp)]
df_erg_chp['nd_id'] = df_erg_chp.pp_id.replace(self.mps.dict_plant_2_node_id)
# outer join profiles and energy to get a profile for each fuel
df_chpprof_tot = pd.merge(df_erg_chp.rename(columns={'value': 'erg'}),
df_chpprof.rename(columns={'value': 'prof'}),
on=['nd_id', 'ca_id'])
# scale profiles
df_chpprof_tot['prof_sc'] = df_chpprof_tot['erg'] * df_chpprof_tot['prof']
# get capacities from parameter
df_cap_pwr_leg = io.IO.param_to_df(self.cap_pwr_leg, ('pp_id', 'ca_id'))
# keep only chp-related fuels
df_cap_pwr_leg = df_cap_pwr_leg.loc[df_cap_pwr_leg.pp_id.isin(self.chp)]
# pivot_by fl_id
df_cappv = df_cap_pwr_leg.pivot_table(values='value',
index=['ca_id', 'pp_id'],
aggfunc=np.sum)['value']
# rename
df_cappv = df_cappv.rename('cap').reset_index()
# add capacity to profiles
df_chpprof_tot = pd.merge(df_cappv, df_chpprof_tot, on=['ca_id', 'pp_id'])
# find occurrences of capacity zero and chp erg non-zero
df_slct = df_chpprof_tot[['pp_id', 'ca_id', 'cap', 'erg']].drop_duplicates().copy()
df_slct = df_slct.loc[df_slct.cap.isin([0])
& -df_slct.erg.isin([0])]
str_erg_cap = ''
if len(df_slct > 0):
for nrow, row in df_slct.iterrows():
str_erg_cap += 'pp_id=%d, ca_id=%d: cap_pwr_leg=%f, erg_chp=%f\n'%tuple(row.values)
raise ValueError ('limit_prof_to_cap: one or more cap_pwr_leg are zero '
'while erg_chp is greater 0: \n' + str_erg_cap)
# find occurrences of capacity violations
mask_viol = df_chpprof_tot.prof_sc > df_chpprof_tot.cap
if mask_viol.sum() == 0:
logger.info('ok, nothing changed.')
else:
# REPORTING
df_profviol = df_chpprof_tot.loc[mask_viol]
dict_viol = df_profviol.pivot_table(index=['pp_id', 'ca_id'],
values='sy', aggfunc=len)['sy'].to_dict()
for kk, vv in dict_viol.items():
logger.warning('limit_prof_to_cap: \n(pp, ca)='
'{}: {} violations'.format(kk, vv))
logger.warning('limit_prof_to_cap: Modifing model '
'parameter ' + param_mod)
if param_mod == 'chpprof':
df_profviol['prof'] *= 0.999 * df_chpprof_tot.cap / df_chpprof_tot.prof_sc
dict_chpprof = (df_profviol.pivot_table(index=['sy', 'nd_id', 'ca_id'],
values='prof', aggfunc=min)['prof']
.to_dict())
for kk, vv in dict_chpprof.items():
self.chpprof[kk] = vv
elif param_mod == 'cap_pwr_leg':
# calculate capacity scaling factor
df_capsc = df_profviol.pivot_table(index=['pp_id', 'ca_id'],
values=['cap', 'prof_sc'], aggfunc=np.max)
df_capsc['cap_sc'] = df_capsc.prof_sc / df_capsc.cap
# merge scaling factor with capacity table
df_cap_pwr_leg = df_cap_pwr_leg.join(df_capsc,
on=df_capsc.index.names)
df_cap_pwr_leg = df_cap_pwr_leg.loc[-df_cap_pwr_leg.cap_sc.isnull()]
# apply scaling factor to all capacity with the relevant fuel
df_cap_pwr_leg['cap'] *= df_cap_pwr_leg.cap_sc * 1.0001
# dictionary
dict_cap_pwr_leg = df_cap_pwr_leg.set_index(['pp_id', 'ca_id'])['cap']
dict_cap_pwr_leg = dict_cap_pwr_leg.to_dict()
for kk, vv in dict_cap_pwr_leg.items():
self.cap_pwr_leg[kk] = vv
def _init_pf_dicts(self):
'''
Initializes dicts mapping the profile ids to other model ids.
This results in dictionaries which are assigned as :class:`ModelBase`
instance attributes:
* ``dict_pricesll_pf``: (fl_id, nd_id, ca_id) |rarr| (pricesll_pf_id)
* ``dict_pricebuy_pf``: (fl_id, nd_id, ca_id) |rarr| (pricebuy_pf_id)
* ``dict_dmnd_pf``: (nd_id, ca_id) |rarr| (dmnd_pf_id)
* ``dict_supply_pf``: (pp_id, ca_id) |rarr| (supply_pf_id)
Purpose
---------
The resulting dictionaries are used for filtering the profile tables
in the :module:`io` module and to access the profile parameters
in the model :class:`Constraints`.
'''
list_pf = [(self.df_fuel_node_encar,
['fl_id', 'nd_id', 'ca_id'], 'pricebuy'),
(self.df_fuel_node_encar,
['fl_id', 'nd_id', 'ca_id'], 'pricesll'),
(self.df_node_encar,
['nd_id', 'ca_id'], 'dmnd'),
(self.df_plant_encar,
['pp_id', 'ca_id'], 'supply')]
df, ind, name = list_pf[-1]
for df, ind, name in list_pf:
col = '%s_pf_id'%name
if df is not None and col in df.columns:
ind_df = df.loc[~df[col].isna()].set_index(ind)[col]
dct = ind_df.to_dict()
else:
dct = {}
setattr(self, 'dict_%s_pf'%name, dct)
def translate_pf_id(self, df):
'''
Adds model id columns for the profile ids in the input DataFrame.
Searches vars(self) for the pf_dict corresponding to the pf_ids
in the input DataFrame. Then uses this dictionary to add additional
columns to the output table.
Parameters
----------
df (DataFrame): DataFrame with pf_id column.
Returns
-------
:obj:`pandas.DataFrame`
Input DataFrame with added model ids corresponding to the pf_id.
Raises
------
IndexError: If multiple pf dictionaries correspond to the pf_id
values in the input DataFrame.
IndexError: If no pf dictionary can be found for the pf_id values.
'''
# identify corresponding pf dict
list_pf_id = set(df.pf_id.unique().tolist())
pf_arrs = {name_dict:
list_pf_id
.issubset(set(getattr(self, name_dict).values()))
for name_dict in vars(self)
if name_dict.startswith('dict_')
and name_dict.endswith('_pf')}
if sum(pf_arrs.values()) > 1:
raise ValueError('Ambiguous pf array in translate_pf_id '
'or df empty.')
elif sum(pf_arrs.values()) == 0:
raise ValueError('No pf array found for table with columns '
'%s'%df.columns.tolist() + '. Maybe you are '
'trying to translate a table with pf_ids which '
'are not included in the original model.')
else:
pf_dict = {val: key for key, val in pf_arrs.items()}[True]
new_cols = {'dict_pricesll_pf': ['fl_id', 'nd_id', 'ca_id'],
'dict_pricebuy_pf': ['fl_id', 'nd_id', 'ca_id'],
'dict_price_pf': ['fl_id', 'nd_id', 'ca_id'],
'dict_dmnd_pf': ['nd_id', 'ca_id'],
'dict_supply_pf': ['pp_id', 'ca_id']}[pf_dict]
pf_dict = getattr(self, pf_dict)
df_new = pd.Series(pf_dict).reset_index()
df_new.columns = new_cols + ['pf_id']
df_new = pd.merge(df_new, df, on='pf_id')
return df_new
def _get_nhours_nodes(self, nhours):
'''
Generates the nhours dictionary ``nhours``.
Returns
-------
nhours_dict : dict
``{node_1: (original time res, target time res),
node_2: (original time res, target time res),
...}``
'''
logger.debug('Generating nhours dictionary for '
'nhours={} with type {}'.format(nhours, type(nhours)))
if isinstance(nhours, dict):
nhours_dict = {}
for nd_id in self.slct_node_id:
nd = self.mps.dict_nd[nd_id]
if nd in nhours:
if isinstance(nhours[nd], tuple):
# all there
nhours_dict[nd_id] = nhours[nd]
elif isinstance(nhours[nd], numbers.Number):
# assuming original time resolution 1 hour
nhours_dict[nd_id] = (1, nhours[nd])
else:
# assuming default
nhours_dict[nd_id] = (1, 1)
elif isinstance(nhours, numbers.Number):
nhours_dict = {nd: (1, nhours) for nd in self.slct_node_id}
elif isinstance(nhours, tuple):
nhours_dict = {nd: nhours for nd in self.slct_node_id}
else:
raise ValueError(f'Unknown structure of `nhours`: {nhours}.\n'
f'Must be one of\n'
f'* number: constant target time resolution,'
f' assuming 1 hour input data time resolution\n'
f'* tuple (input_t_res, target_t_res): applied'
f' to all nodes\n'
'* dict {nd: (input, target)}: explicit '
'specification')
return nhours_dict
def init_maps(self):
'''
Uses the input DataFrames to initialize a
:class:`grimsel.auxiliary.maps.Maps` instance.
'''
dct = {var.replace('df_def_', ''): getattr(self, var)
for var in vars(self) if 'df_def_' in var}
self.mps = maps.Maps.from_dicts(dct)
def _init_time_map_connect(self):
df_ndcnn = self.df_node_connect[['nd_id', 'nd_2_id', 'ca_id']].drop_duplicates()
df_ndcnn['freq'] = df_ndcnn.nd_id.apply(lambda x: {key: frnh[0] for key, frnh in self._dict_nd_tm.items()}[x])
df_ndcnn['nhours'] = df_ndcnn.nd_id.apply(lambda x: {key: frnh[1] for key, frnh in self._dict_nd_tm.items()}[x])
df_ndcnn['freq_2'] = df_ndcnn.nd_2_id.apply(lambda x: {key: frnh[0] for key, frnh in self._dict_nd_tm.items()}[x])
df_ndcnn['nhours_2'] = df_ndcnn.nd_2_id.apply(lambda x: {key: frnh[1] for key, frnh in self._dict_nd_tm.items()}[x])
df_ndcnn['tm_id'] = df_ndcnn.nd_id.replace(self.dict_nd_tm_id)
df_ndcnn['tm_2_id'] = df_ndcnn.nd_2_id.replace(self.dict_nd_tm_id)
# make dict_sy_ndnd_min
is_min_node = pd.concat([df_ndcnn,
df_ndcnn.assign(nd_id = df_ndcnn.nd_2_id,
nd_2_id = df_ndcnn.nd_id,
nhours = df_ndcnn.nhours_2,
nhours_2 = df_ndcnn.nhours)])
self.is_min_node = (
is_min_node.assign(is_min=is_min_node.nhours
<= is_min_node.nhours_2)
.set_index(['nd_id', 'nd_2_id'])
.is_min).to_dict()
def get_map_sy(x):
tm = timemap.TimeMap(tm_filt=self.tm_filt, minimum=True,
freq=x[['freq', 'freq_2']].min(axis=1).values[0],
nhours=x.nhours.iloc[0])
tm_2 = timemap.TimeMap(tm_filt=self.tm_filt, minimum=True,
freq=x[['freq', 'freq_2']].min(axis=1).values[0],
nhours=x.nhours_2.iloc[0])
return pd.merge(tm.df_hoy_soy,
tm_2.df_hoy_soy.rename(columns={'sy': 'sy2'}),
on='hy')[['sy', 'sy2']]
self.dict_ndnd_tm_id = df_ndcnn.set_index(['nd_id', 'nd_2_id']).copy()
self.dict_ndnd_tm_id['tm_min_id'] = self.dict_ndnd_tm_id.apply(lambda x: x.tm_id if x.nhours <= x.nhours_2 else x.tm_2_id, axis=1)
self.dict_ndnd_tm_id = self.dict_ndnd_tm_id.tm_min_id.to_dict()
self.dict_ndnd_tm_id = {**self.dict_ndnd_tm_id,
**{(key[1], key[0]): val
for key, val
in self.dict_ndnd_tm_id.items()}}
sysymap = df_ndcnn[[c for c in df_ndcnn.columns if not 'nd' in c]]
sysymap = df_ndcnn.drop_duplicates()
sysymap = df_ndcnn.groupby(['tm_id', 'tm_2_id']).apply(get_map_sy).reset_index()
sysymap = sysymap.drop('level_2', axis=1)
self.df_sysy_ndcnn = pd.merge(
df_ndcnn[['nd_id', 'nd_2_id', 'ca_id', 'tm_id', 'tm_2_id']],
sysymap, on=['tm_id', 'tm_2_id'], how='outer')
self.dict_sysy = {**self.df_sysy_ndcnn.groupby(['nd_id', 'nd_2_id', 'sy']).sy2.apply(lambda x: set((*x,))).to_dict(),
**self.df_sysy_ndcnn.groupby(['nd_2_id', 'nd_id', 'sy2']).sy.apply(lambda x: set((*x,))).to_dict()}
self.df_symin_ndcnn = self.df_sysy_ndcnn.join(df_ndcnn.set_index(['nd_id', 'nd_2_id'])[['nhours', 'nhours_2']], on=['nd_id', 'nd_2_id'])
idx = ['nd_id', 'nd_2_id']
cols = ['sy', 'sy2', 'tm_2_id', 'ca_id', 'tm_id', 'nhours', 'nhours_2']
list_df = []
for nd_id, nd_2_id in set(self.df_symin_ndcnn.set_index(idx).index.values):
df = self.df_symin_ndcnn.set_index(idx).loc[[(nd_id, nd_2_id)], cols]
nd_smaller = df.nhours.iloc[0] <= df.nhours_2.iloc[0]
list_df.append(df.assign(symin = df.sy if nd_smaller else df.sy2,
tm_min_id = df.tm_id if nd_smaller
else df.tm_2_id))
cols = ['tm_min_id', 'symin', 'nd_id', 'nd_2_id', 'ca_id']
self.df_symin_ndcnn = pd.concat(list_df).reset_index()[cols]
def _init_time_map_input(self):
'''
If a *tm_soy* table is provided in the input data, time slots
are assumed to be exogenously defined.
'''
# assert number of time slots in all profiles equals time slots in
# tm_soy input table
nsy = len(self.df_tm_soy.sy)
assert(len(self.df_profdmnd.hy.unique()) == nsy), \
'Inconsistent time slots tm_soy/profsupply'
if getattr(self, 'profsupply', None) is not None:
assert(len(self.df_profsupply.hy.unique()) == nsy), \
'Inconsistent time slots tm_soy/profsupply'
if getattr(self, 'profchp', None) is not None:
assert(len(self.df_profchp.hy.unique()) == nsy), \
'Inconsistent time slots tm_soy/profchp'
if getattr(self, 'profchp', None) is not None:
assert(len(self.df_profinflow.hy.unique()) == nsy), \
'Inconsistent time slots tm_soy/profinflow'
assert(len(self.df_tm_soy.weight.unique()) == 1), \
'Multiple weights in input df_tm_soy. Can\'t infer time resolution.'
# nhours follows from weight in df_tm_soy
self.nhours = self.df_tm_soy.weight.iloc[0]
self._dict_nd_tm = self._get_nhours_nodes(self.nhours)
# generate unique time map ids
dict_tm = {ntm: frnh for ntm, frnh
in enumerate(set(self._dict_nd_tm.values()))}
self.dict_nd_tm_id = {nd:
{val: key for key, val in dict_tm.items()}[tm]
for nd, tm in self._dict_nd_tm.items()}
self._tm_objs = {}
self.df_def_node['tm_id'] = (self.df_def_node.reset_index().nd_id
.replace(self.dict_nd_tm_id).values)
unique_tm_id = self.df_def_node['tm_id'].iloc[0]
self.df_hoy_soy = self.df_tm_soy[['sy']].assign(
hy=lambda x: x.sy, tm_id=unique_tm_id)
self.df_tm_soy = self.df_tm_soy.assign(tm_id=unique_tm_id,
mt_id=None)
self.df_tm_soy_full = None
self.dict_soy_week = None
self.dict_soy_month = None
self.dict_week_soy = None
self.dict_month_soy = None
self.df_sy_min_all = None
# dict pp_id -> tm
self.dict_pp_tm_id = (
self.df_def_plant.assign(tm_id=self.df_def_plant.nd_id
.replace(self.dict_nd_tm_id))
.set_index('pp_id').tm_id.to_dict())
# dict tm_id -> sy
unq_list = lambda x: list(set(x))
pv_kws = dict(index='tm_id', values='sy', aggfunc=unq_list)
self.dict_tm_sy = self.df_hoy_soy.pivot_table(**pv_kws).sy.to_dict()
def _init_time_map(self):
'''
Create a TimeMap instance and obtain derived attributes.
Generated attributes:
* ``tm`` (``TimeMap``): TimeMap object
* ``df_tm_soy`` (``DataFrame``): timemap table
* ``df_tm_soy_full`` (``DataFrame``): full timemap table
'''
self._dict_nd_tm = self._get_nhours_nodes(self.nhours)
# generate unique time map ids
dict_tm = {ntm: frnh for ntm, frnh
in enumerate(set(self._dict_nd_tm.values()))}
self.dict_nd_tm_id = {nd:
{val: key for key, val in dict_tm.items()}[tm]
for nd, tm in self._dict_nd_tm.items()}
self._tm_objs = {tm_id:
timemap.TimeMap(tm_filt=self.tm_filt,
nhours=frnh[1], freq=frnh[0])
for tm_id, frnh in dict_tm.items()}
self.df_def_node['tm_id'] = (self.df_def_node.reset_index().nd_id
.replace(self.dict_nd_tm_id).values)
cols_red = ['wk_id', 'mt_id', 'sy', 'weight', 'wk_weight']
list_tm_soy = [tm.df_time_red[cols_red].assign(tm_id=tm_id) for
tm_id, tm in self._tm_objs.items()]
self.df_tm_soy = pd.concat(list_tm_soy, axis=0)
list_tm_soy_full = [tm.df_time_red.assign(tm_id=tm_id)
for tm_id, tm in self._tm_objs.items()]
self.df_tm_soy_full = pd.concat(list_tm_soy_full, axis=0, sort=True)
list_hoy_soy = [tm.df_hoy_soy.assign(tm_id=tm_id)
for tm_id, tm in self._tm_objs.items()]
self.df_hoy_soy =
|
pd.concat(list_hoy_soy, axis=0)
|
pandas.concat
|
"""
Movie Recommendation Skill.
- movies like <movie-name>
"""
import numpy as np
import pandas as pd
from nltk import edit_distance
# Local Imports.
from backend.config import cosine_sim_scores_path, movie_data_path
def find_nearest_title(user_input_title):
"""
Checks for nearest movie title in dataset
Parameters
----------
user_input_title: str.
Returns
-------
nearest_title
"""
movies = pd.read_csv(movie_data_path)
movie_titles = movies["title"]
distances = {}
for titles in movie_titles:
distances[titles] = edit_distance(user_input_title, titles)
sorted_distances = sorted(distances.items(), key=lambda x: x[1], reverse=False)
nearest_title = sorted_distances[0][0]
return nearest_title
def get_movie_plot(user_input_tokens):
"""
Returns movie's summary.
Parameters
----------
user_input_tokens: list.
Returns
-------
summary.
"""
# Process movie title from user.
user_input_title = user_input_tokens[1:]
user_input_title = ' '.join(user_input_title)
# Find nearest title.
movie_title = find_nearest_title(user_input_title)
movie_data = pd.read_csv(movie_data_path)
# Find Plot.
plot = movie_data[movie_data["title"] == movie_title]["summary"].values[0]
year_of_release = movie_data[movie_data["title"] == movie_title]["year_of_release"].values[0]
genre = movie_data[movie_data["title"] == movie_title]["genres"].values[0]
# Format Response.
movie_plot = f"{movie_title.capitalize()} ({year_of_release}, {genre}): {plot}"
return movie_plot
def get_recommendations(user_input_tokens):
"""
Computes Top 5 movie recommendation.
Parameters
----------
user_input_tokens: tokenized input.
Returns
-------
5 similar movies.
"""
# Process movie title from user input.
user_input_title = user_input_tokens[2:]
user_input_title = ' '.join(user_input_title)
movie_title = find_nearest_title(user_input_title)
# Read files from db.
movie_data =
|
pd.read_csv(movie_data_path)
|
pandas.read_csv
|
import pandas as pd
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_auc_score
import joblib
import os
class Logistic_Regression():
df_bid_requests=pd.read_csv("D:/lecture sources/Win2021/information system/BCB_help/data/ipinyou/1458/dummified_train_test.txt", sep="\t")
df_bid_test=pd.read_csv("D:/lecture sources/Win2021/information system/BCB_help/data/ipinyou/1458/dummified_test_test.txt", sep="\t")
bf_help=pd.read_csv("D:/lecture sources/Win2021/information system/BCB_help/data/ipinyou/1458/train.log.txt", sep="\t")
# #print(df_bid_test)
#training
df_bid_requests['click']=bf_help['click']
df_bid_test=pd.DataFrame(df_bid_test.astype(np.uint8))
df_bid_requests=pd.DataFrame(df_bid_requests.astype(np.uint8))
X = df_bid_requests.drop(['click'], axis=1)
Y = df_bid_requests.click
#df_bid_test = df_bid_test[np.intersect1d(X.columns, df_bid_test.columns)]
X=X[np.intersect1d(X.columns, df_bid_test.columns)]
# ########### Train model with Logitstic Regression
# Logistic Regression: Model fitting
# print(X.dtypes)
# logreg = LogisticRegression(class_weight='balanced', max_iter=1000)
# logreg.fit(X, Y)
#save models
# joblib_filename = "logreg_1.sav"
# joblib.dump(logreg, joblib_filename)
#
# ## Check auccuracy score
# print(logreg.score(X,Y))
# prob = logreg.predict_proba(X)[:, 1]
# print(roc_auc_score(Y, prob))
logreg = joblib.load("logreg.sav")
#
# # ## Logistic Regression: Predict CTR
ctr_pre_train=logreg.predict(X)
ctr_pre_train_proba=logreg.predict_proba(X)
df_ctr_train = pd.DataFrame(ctr_pre_train_proba, columns=['ctr_prediction_pro','ctr_prediction'])
df_ctr_train['click'] =ctr_pre_train
df_ctr_train.to_csv('D:/lecture sources/Win2021/information system/BCB_help/data/ipinyou/1458/ctr_pred_train.txt', index=False, sep='\t', header=True)
ctr_pred = logreg.predict(df_bid_test[X.columns])
ctr_pre_proba = logreg.predict_proba(df_bid_test[X.columns])
df_ctr_test =
|
pd.DataFrame(ctr_pre_proba, columns=['ctr_prediction_pro_0', 'ctr_prediction_pro_1'])
|
pandas.DataFrame
|
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import os
import sys
import multiprocess as mp
import itertools
import pickle
import time
# import gpflow
# import tensorflow as tf
import GPy
# from IPython.display import display
from sklearn.model_selection import train_test_split
from sklearn.model_selection import KFold
from sklearn import preprocessing
from tqdm import tqdm
import perform_kernel_regression_fair_learing
from perform_kernel_regression_fair_learing import FairLearning
from perform_kernel_regression_fair_learing import fl_wrapper
from perform_kernel_regression_fair_learing import FairLearning_process
from perform_kernel_regression_fair_learing import centre_mat
from perform_kernel_regression_fair_learing import cross_v
from hyppo.independence import Hsic
# for median_heuristic
from numpy.random import permutation
from scipy.spatial.distance import squareform, pdist, cdist
import time
# %%
X = pd.read_csv('X.csv')
y = pd.read_csv('y.csv')
X = X.values.reshape(X.shape)[:, 1:]
y = y.values.reshape(y.shape)[:, 1:]
# %%
x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.3)
#%%
def save_csv(array_name, filename):
pd.DataFrame(array_name).to_csv(filename + '.csv')
save_csv(x_train, 'x_train')
save_csv(x_test, 'x_test')
save_csv(y_train, 'y_train')
save_csv(y_test, 'y_test')
#%%
x_train = pd.read_csv('x_train.csv').values[:, 1:]
x_test =
|
pd.read_csv('x_test.csv')
|
pandas.read_csv
|
"""
A warehouse for constant values required to initilize the PUDL Database.
This constants module stores and organizes a bunch of constant values which are
used throughout PUDL to populate static lists within the data packages or for
data cleaning purposes.
"""
import pandas as pd
import sqlalchemy as sa
######################################################################
# Constants used within the init.py module.
######################################################################
prime_movers = [
'steam_turbine',
'gas_turbine',
'hydro',
'internal_combustion',
'solar_pv',
'wind_turbine'
]
"""list: A list of the types of prime movers"""
rto_iso = {
'CAISO': 'California ISO',
'ERCOT': 'Electric Reliability Council of Texas',
'MISO': 'Midcontinent ISO',
'ISO-NE': 'ISO New England',
'NYISO': 'New York ISO',
'PJM': 'PJM Interconnection',
'SPP': 'Southwest Power Pool'
}
"""dict: A dictionary containing ISO/RTO abbreviations (keys) and names (values)
"""
us_states = {
'AK': 'Alaska',
'AL': 'Alabama',
'AR': 'Arkansas',
'AS': 'American Samoa',
'AZ': 'Arizona',
'CA': 'California',
'CO': 'Colorado',
'CT': 'Connecticut',
'DC': 'District of Columbia',
'DE': 'Delaware',
'FL': 'Florida',
'GA': 'Georgia',
'GU': 'Guam',
'HI': 'Hawaii',
'IA': 'Iowa',
'ID': 'Idaho',
'IL': 'Illinois',
'IN': 'Indiana',
'KS': 'Kansas',
'KY': 'Kentucky',
'LA': 'Louisiana',
'MA': 'Massachusetts',
'MD': 'Maryland',
'ME': 'Maine',
'MI': 'Michigan',
'MN': 'Minnesota',
'MO': 'Missouri',
'MP': 'Northern Mariana Islands',
'MS': 'Mississippi',
'MT': 'Montana',
'NA': 'National',
'NC': 'North Carolina',
'ND': 'North Dakota',
'NE': 'Nebraska',
'NH': 'New Hampshire',
'NJ': 'New Jersey',
'NM': 'New Mexico',
'NV': 'Nevada',
'NY': 'New York',
'OH': 'Ohio',
'OK': 'Oklahoma',
'OR': 'Oregon',
'PA': 'Pennsylvania',
'PR': 'Puerto Rico',
'RI': 'Rhode Island',
'SC': 'South Carolina',
'SD': 'South Dakota',
'TN': 'Tennessee',
'TX': 'Texas',
'UT': 'Utah',
'VA': 'Virginia',
'VI': 'Virgin Islands',
'VT': 'Vermont',
'WA': 'Washington',
'WI': 'Wisconsin',
'WV': 'West Virginia',
'WY': 'Wyoming'
}
"""dict: A dictionary containing US state abbreviations (keys) and names
(values)
"""
canada_prov_terr = {
'AB': 'Alberta',
'BC': 'British Columbia',
'CN': 'Canada',
'MB': 'Manitoba',
'NB': 'New Brunswick',
'NS': 'Nova Scotia',
'NL': 'Newfoundland and Labrador',
'NT': 'Northwest Territories',
'NU': 'Nunavut',
'ON': 'Ontario',
'PE': 'Prince Edwards Island',
'QC': 'Quebec',
'SK': 'Saskatchewan',
'YT': 'Yukon Territory',
}
"""dict: A dictionary containing Canadian provinces' and territories'
abbreviations (keys) and names (values)
"""
cems_states = {k: v for k, v in us_states.items() if v not in
{'Alaska',
'American Samoa',
'Guam',
'Hawaii',
'Northern Mariana Islands',
'National',
'Puerto Rico',
'Virgin Islands'}
}
"""dict: A dictionary containing US state abbreviations (keys) and names
(values) that are present in the CEMS dataset
"""
# This is imperfect for states that have split timezones. See:
# https://en.wikipedia.org/wiki/List_of_time_offsets_by_U.S._state_and_territory
# For states that are split, I went with where there seem to be more people
# List of timezones in pytz.common_timezones
# Canada: https://en.wikipedia.org/wiki/Time_in_Canada#IANA_time_zone_database
state_tz_approx = {
"AK": "US/Alaska", # Alaska; Not in CEMS
"AL": "US/Central", # Alabama
"AR": "US/Central", # Arkansas
"AS": "Pacific/Pago_Pago", # American Samoa; Not in CEMS
"AZ": "US/Arizona", # Arizona
"CA": "US/Pacific", # California
"CO": "US/Mountain", # Colorado
"CT": "US/Eastern", # Connecticut
"DC": "US/Eastern", # District of Columbia
"DE": "US/Eastern", # Delaware
"FL": "US/Eastern", # Florida (split state)
"GA": "US/Eastern", # Georgia
"GU": "Pacific/Guam", # Guam; Not in CEMS
"HI": "US/Hawaii", # Hawaii; Not in CEMS
"IA": "US/Central", # Iowa
"ID": "US/Mountain", # Idaho (split state)
"IL": "US/Central", # Illinois
"IN": "US/Eastern", # Indiana (split state)
"KS": "US/Central", # Kansas (split state)
"KY": "US/Eastern", # Kentucky (split state)
"LA": "US/Central", # Louisiana
"MA": "US/Eastern", # Massachusetts
"MD": "US/Eastern", # Maryland
"ME": "US/Eastern", # Maine
"MI": "America/Detroit", # Michigan (split state)
"MN": "US/Central", # Minnesota
"MO": "US/Central", # Missouri
"MP": "Pacific/Saipan", # Northern Mariana Islands; Not in CEMS
"MS": "US/Central", # Mississippi
"MT": "US/Mountain", # Montana
"NC": "US/Eastern", # North Carolina
"ND": "US/Central", # North Dakota (split state)
"NE": "US/Central", # Nebraska (split state)
"NH": "US/Eastern", # New Hampshire
"NJ": "US/Eastern", # New Jersey
"NM": "US/Mountain", # New Mexico
"NV": "US/Pacific", # Nevada
"NY": "US/Eastern", # New York
"OH": "US/Eastern", # Ohio
"OK": "US/Central", # Oklahoma
"OR": "US/Pacific", # Oregon (split state)
"PA": "US/Eastern", # Pennsylvania
"PR": "America/Puerto_Rico", # Puerto Rico; Not in CEMS
"RI": "US/Eastern", # Rhode Island
"SC": "US/Eastern", # South Carolina
"SD": "US/Central", # South Dakota (split state)
"TN": "US/Central", # Tennessee
"TX": "US/Central", # Texas
"UT": "US/Mountain", # Utah
"VA": "US/Eastern", # Virginia
"VI": "America/Puerto_Rico", # Virgin Islands; Not in CEMS
"VT": "US/Eastern", # Vermont
"WA": "US/Pacific", # Washington
"WI": "US/Central", # Wisconsin
"WV": "US/Eastern", # West Virginia
"WY": "US/Mountain", # Wyoming
# Canada (none of these are in CEMS)
"AB": "America/Edmonton", # Alberta
"BC": "America/Vancouver", # British Columbia (split province)
"MB": "America/Winnipeg", # Manitoba
"NB": "America/Moncton", # New Brunswick
"NS": "America/Halifax", # Nova Scotia
"NL": "America/St_Johns", # Newfoundland and Labrador (split province)
"NT": "America/Yellowknife", # Northwest Territories (split province)
"NU": "America/Iqaluit", # Nunavut (split province)
"ON": "America/Toronto", # Ontario (split province)
"PE": "America/Halifax", # Prince Edwards Island
"QC": "America/Montreal", # Quebec (split province)
"SK": "America/Regina", # Saskatchewan (split province)
"YT": "America/Whitehorse", # Yukon Territory
}
"""dict: A dictionary containing US and Canadian state/territory abbreviations
(keys) and timezones (values)
"""
ferc1_power_purchase_type = {
'RQ': 'requirement',
'LF': 'long_firm',
'IF': 'intermediate_firm',
'SF': 'short_firm',
'LU': 'long_unit',
'IU': 'intermediate_unit',
'EX': 'electricity_exchange',
'OS': 'other_service',
'AD': 'adjustment'
}
"""dict: A dictionary of abbreviations (keys) and types (values) for power
purchase agreements from FERC Form 1.
"""
# Dictionary mapping DBF files (w/o .DBF file extension) to DB table names
ferc1_dbf2tbl = {
'F1_1': 'f1_respondent_id',
'F1_2': 'f1_acb_epda',
'F1_3': 'f1_accumdepr_prvsn',
'F1_4': 'f1_accumdfrrdtaxcr',
'F1_5': 'f1_adit_190_detail',
'F1_6': 'f1_adit_190_notes',
'F1_7': 'f1_adit_amrt_prop',
'F1_8': 'f1_adit_other',
'F1_9': 'f1_adit_other_prop',
'F1_10': 'f1_allowances',
'F1_11': 'f1_bal_sheet_cr',
'F1_12': 'f1_capital_stock',
'F1_13': 'f1_cash_flow',
'F1_14': 'f1_cmmn_utlty_p_e',
'F1_15': 'f1_comp_balance_db',
'F1_16': 'f1_construction',
'F1_17': 'f1_control_respdnt',
'F1_18': 'f1_co_directors',
'F1_19': 'f1_cptl_stk_expns',
'F1_20': 'f1_csscslc_pcsircs',
'F1_21': 'f1_dacs_epda',
'F1_22': 'f1_dscnt_cptl_stk',
'F1_23': 'f1_edcfu_epda',
'F1_24': 'f1_elctrc_erg_acct',
'F1_25': 'f1_elctrc_oper_rev',
'F1_26': 'f1_elc_oper_rev_nb',
'F1_27': 'f1_elc_op_mnt_expn',
'F1_28': 'f1_electric',
'F1_29': 'f1_envrnmntl_expns',
'F1_30': 'f1_envrnmntl_fclty',
'F1_31': 'f1_fuel',
'F1_32': 'f1_general_info',
'F1_33': 'f1_gnrt_plant',
'F1_34': 'f1_important_chg',
'F1_35': 'f1_incm_stmnt_2',
'F1_36': 'f1_income_stmnt',
'F1_37': 'f1_miscgen_expnelc',
'F1_38': 'f1_misc_dfrrd_dr',
'F1_39': 'f1_mthly_peak_otpt',
'F1_40': 'f1_mtrl_spply',
'F1_41': 'f1_nbr_elc_deptemp',
'F1_42': 'f1_nonutility_prop',
'F1_43': 'f1_note_fin_stmnt', # 37% of DB
'F1_44': 'f1_nuclear_fuel',
'F1_45': 'f1_officers_co',
'F1_46': 'f1_othr_dfrrd_cr',
'F1_47': 'f1_othr_pd_in_cptl',
'F1_48': 'f1_othr_reg_assets',
'F1_49': 'f1_othr_reg_liab',
'F1_50': 'f1_overhead',
'F1_51': 'f1_pccidica',
'F1_52': 'f1_plant_in_srvce',
'F1_53': 'f1_pumped_storage',
'F1_54': 'f1_purchased_pwr',
'F1_55': 'f1_reconrpt_netinc',
'F1_56': 'f1_reg_comm_expn',
'F1_57': 'f1_respdnt_control',
'F1_58': 'f1_retained_erng',
'F1_59': 'f1_r_d_demo_actvty',
'F1_60': 'f1_sales_by_sched',
'F1_61': 'f1_sale_for_resale',
'F1_62': 'f1_sbsdry_totals',
'F1_63': 'f1_schedules_list',
'F1_64': 'f1_security_holder',
'F1_65': 'f1_slry_wg_dstrbtn',
'F1_66': 'f1_substations',
'F1_67': 'f1_taxacc_ppchrgyr',
'F1_68': 'f1_unrcvrd_cost',
'F1_69': 'f1_utltyplnt_smmry',
'F1_70': 'f1_work',
'F1_71': 'f1_xmssn_adds',
'F1_72': 'f1_xmssn_elc_bothr',
'F1_73': 'f1_xmssn_elc_fothr',
'F1_74': 'f1_xmssn_line',
'F1_75': 'f1_xtraordnry_loss',
'F1_76': 'f1_codes_val',
'F1_77': 'f1_sched_lit_tbl',
'F1_78': 'f1_audit_log',
'F1_79': 'f1_col_lit_tbl',
'F1_80': 'f1_load_file_names',
'F1_81': 'f1_privilege',
'F1_82': 'f1_sys_error_log',
'F1_83': 'f1_unique_num_val',
'F1_84': 'f1_row_lit_tbl',
'F1_85': 'f1_footnote_data',
'F1_86': 'f1_hydro',
'F1_87': 'f1_footnote_tbl', # 52% of DB
'F1_88': 'f1_ident_attsttn',
'F1_89': 'f1_steam',
'F1_90': 'f1_leased',
'F1_91': 'f1_sbsdry_detail',
'F1_92': 'f1_plant',
'F1_93': 'f1_long_term_debt',
'F1_106_2009': 'f1_106_2009',
'F1_106A_2009': 'f1_106a_2009',
'F1_106B_2009': 'f1_106b_2009',
'F1_208_ELC_DEP': 'f1_208_elc_dep',
'F1_231_TRN_STDYCST': 'f1_231_trn_stdycst',
'F1_324_ELC_EXPNS': 'f1_324_elc_expns',
'F1_325_ELC_CUST': 'f1_325_elc_cust',
'F1_331_TRANSISO': 'f1_331_transiso',
'F1_338_DEP_DEPL': 'f1_338_dep_depl',
'F1_397_ISORTO_STL': 'f1_397_isorto_stl',
'F1_398_ANCL_PS': 'f1_398_ancl_ps',
'F1_399_MTH_PEAK': 'f1_399_mth_peak',
'F1_400_SYS_PEAK': 'f1_400_sys_peak',
'F1_400A_ISO_PEAK': 'f1_400a_iso_peak',
'F1_429_TRANS_AFF': 'f1_429_trans_aff',
'F1_ALLOWANCES_NOX': 'f1_allowances_nox',
'F1_CMPINC_HEDGE_A': 'f1_cmpinc_hedge_a',
'F1_CMPINC_HEDGE': 'f1_cmpinc_hedge',
'F1_EMAIL': 'f1_email',
'F1_RG_TRN_SRV_REV': 'f1_rg_trn_srv_rev',
'F1_S0_CHECKS': 'f1_s0_checks',
'F1_S0_FILING_LOG': 'f1_s0_filing_log',
'F1_SECURITY': 'f1_security'
# 'F1_PINS': 'f1_pins', # private data, not publicized.
# 'F1_FREEZE': 'f1_freeze', # private data, not publicized
}
"""dict: A dictionary mapping FERC Form 1 DBF files(w / o .DBF file extension)
(keys) to database table names (values).
"""
ferc1_huge_tables = {
'f1_footnote_tbl',
'f1_footnote_data',
'f1_note_fin_stmnt',
}
"""set: A set containing large FERC Form 1 tables.
"""
# Invert the map above so we can go either way as needed
ferc1_tbl2dbf = {v: k for k, v in ferc1_dbf2tbl.items()}
"""dict: A dictionary mapping database table names (keys) to FERC Form 1 DBF
files(w / o .DBF file extension) (values).
"""
# This dictionary maps the strings which are used to denote field types in the
# DBF objects to the corresponding generic SQLAlchemy Column types:
# These definitions come from a combination of the dbfread example program
# dbf2sqlite and this DBF file format documentation page:
# http://www.dbase.com/KnowledgeBase/int/db7_file_fmt.htm
# Un-mapped types left as 'XXX' which should obviously make an error...
dbf_typemap = {
'C': sa.String,
'D': sa.Date,
'F': sa.Float,
'I': sa.Integer,
'L': sa.Boolean,
'M': sa.Text, # 10 digit .DBT block number, stored as a string...
'N': sa.Float,
'T': sa.DateTime,
'0': sa.Integer, # based on dbf2sqlite mapping
'B': 'XXX', # .DBT block number, binary string
'@': 'XXX', # Timestamp... Date = Julian Day, Time is in milliseconds?
'+': 'XXX', # Autoincrement (e.g. for IDs)
'O': 'XXX', # Double, 8 bytes
'G': 'XXX', # OLE 10 digit/byte number of a .DBT block, stored as string
}
"""dict: A dictionary mapping field types in the DBF objects (keys) to the
corresponding generic SQLAlchemy Column types.
"""
# This is the set of tables which have been successfully integrated into PUDL:
ferc1_pudl_tables = (
'fuel_ferc1', # Plant-level data, linked to plants_steam_ferc1
'plants_steam_ferc1', # Plant-level data
'plants_small_ferc1', # Plant-level data
'plants_hydro_ferc1', # Plant-level data
'plants_pumped_storage_ferc1', # Plant-level data
'purchased_power_ferc1', # Inter-utility electricity transactions
'plant_in_service_ferc1', # Row-mapped plant accounting data.
# 'accumulated_depreciation_ferc1' # Requires row-mapping to be useful.
)
"""tuple: A tuple containing the FERC Form 1 tables that can be successfully
integrated into PUDL.
"""
table_map_ferc1_pudl = {
'fuel_ferc1': 'f1_fuel',
'plants_steam_ferc1': 'f1_steam',
'plants_small_ferc1': 'f1_gnrt_plant',
'plants_hydro_ferc1': 'f1_hydro',
'plants_pumped_storage_ferc1': 'f1_pumped_storage',
'plant_in_service_ferc1': 'f1_plant_in_srvce',
'purchased_power_ferc1': 'f1_purchased_pwr',
# 'accumulated_depreciation_ferc1': 'f1_accumdepr_prvsn'
}
"""dict: A dictionary mapping PUDL table names (keys) to the corresponding FERC
Form 1 DBF table names.
"""
# This is the list of EIA923 tables that can be successfully pulled into PUDL
eia923_pudl_tables = ('generation_fuel_eia923',
'boiler_fuel_eia923',
'generation_eia923',
'coalmine_eia923',
'fuel_receipts_costs_eia923')
"""tuple: A tuple containing the EIA923 tables that can be successfully
integrated into PUDL.
"""
epaipm_pudl_tables = (
'transmission_single_epaipm',
'transmission_joint_epaipm',
'load_curves_epaipm',
'plant_region_map_epaipm',
)
"""tuple: A tuple containing the EPA IPM tables that can be successfully
integrated into PUDL.
"""
# List of entity tables
entity_tables = ['utilities_entity_eia',
'plants_entity_eia',
'generators_entity_eia',
'boilers_entity_eia',
'regions_entity_epaipm', ]
"""list: A list of PUDL entity tables.
"""
xlsx_maps_pkg = 'pudl.package_data.meta.xlsx_maps'
"""string: The location of the xlsx maps within the PUDL package data."""
##############################################################################
# EIA 923 Spreadsheet Metadata
##############################################################################
##############################################################################
# EIA 860 Spreadsheet Metadata
##############################################################################
# This is the list of EIA860 tables that can be successfully pulled into PUDL
eia860_pudl_tables = (
'boiler_generator_assn_eia860',
'utilities_eia860',
'plants_eia860',
'generators_eia860',
'ownership_eia860'
)
"""tuple: A tuple enumerating EIA 860 tables for which PUDL's ETL works."""
# The set of FERC Form 1 tables that have the same composite primary keys: [
# respondent_id, report_year, report_prd, row_number, spplmnt_num ].
# TODO: THIS ONLY PERTAINS TO 2015 AND MAY NEED TO BE ADJUSTED BY YEAR...
ferc1_data_tables = (
'f1_acb_epda', 'f1_accumdepr_prvsn', 'f1_accumdfrrdtaxcr',
'f1_adit_190_detail', 'f1_adit_190_notes', 'f1_adit_amrt_prop',
'f1_adit_other', 'f1_adit_other_prop', 'f1_allowances', 'f1_bal_sheet_cr',
'f1_capital_stock', 'f1_cash_flow', 'f1_cmmn_utlty_p_e',
'f1_comp_balance_db', 'f1_construction', 'f1_control_respdnt',
'f1_co_directors', 'f1_cptl_stk_expns', 'f1_csscslc_pcsircs',
'f1_dacs_epda', 'f1_dscnt_cptl_stk', 'f1_edcfu_epda', 'f1_elctrc_erg_acct',
'f1_elctrc_oper_rev', 'f1_elc_oper_rev_nb', 'f1_elc_op_mnt_expn',
'f1_electric', 'f1_envrnmntl_expns', 'f1_envrnmntl_fclty', 'f1_fuel',
'f1_general_info', 'f1_gnrt_plant', 'f1_important_chg', 'f1_incm_stmnt_2',
'f1_income_stmnt', 'f1_miscgen_expnelc', 'f1_misc_dfrrd_dr',
'f1_mthly_peak_otpt', 'f1_mtrl_spply', 'f1_nbr_elc_deptemp',
'f1_nonutility_prop', 'f1_note_fin_stmnt', 'f1_nuclear_fuel',
'f1_officers_co', 'f1_othr_dfrrd_cr', 'f1_othr_pd_in_cptl',
'f1_othr_reg_assets', 'f1_othr_reg_liab', 'f1_overhead', 'f1_pccidica',
'f1_plant_in_srvce', 'f1_pumped_storage', 'f1_purchased_pwr',
'f1_reconrpt_netinc', 'f1_reg_comm_expn', 'f1_respdnt_control',
'f1_retained_erng', 'f1_r_d_demo_actvty', 'f1_sales_by_sched',
'f1_sale_for_resale', 'f1_sbsdry_totals', 'f1_schedules_list',
'f1_security_holder', 'f1_slry_wg_dstrbtn', 'f1_substations',
'f1_taxacc_ppchrgyr', 'f1_unrcvrd_cost', 'f1_utltyplnt_smmry', 'f1_work',
'f1_xmssn_adds', 'f1_xmssn_elc_bothr', 'f1_xmssn_elc_fothr',
'f1_xmssn_line', 'f1_xtraordnry_loss',
'f1_hydro', 'f1_steam', 'f1_leased', 'f1_sbsdry_detail',
'f1_plant', 'f1_long_term_debt', 'f1_106_2009', 'f1_106a_2009',
'f1_106b_2009', 'f1_208_elc_dep', 'f1_231_trn_stdycst', 'f1_324_elc_expns',
'f1_325_elc_cust', 'f1_331_transiso', 'f1_338_dep_depl',
'f1_397_isorto_stl', 'f1_398_ancl_ps', 'f1_399_mth_peak',
'f1_400_sys_peak', 'f1_400a_iso_peak', 'f1_429_trans_aff',
'f1_allowances_nox', 'f1_cmpinc_hedge_a', 'f1_cmpinc_hedge',
'f1_rg_trn_srv_rev')
"""tuple: A tuple containing the FERC Form 1 tables that have the same composite
primary keys: [respondent_id, report_year, report_prd, row_number,
spplmnt_num].
"""
# Line numbers, and corresponding FERC account number
# from FERC Form 1 pages 204-207, Electric Plant in Service.
# Descriptions from: https://www.law.cornell.edu/cfr/text/18/part-101
ferc_electric_plant_accounts = pd.DataFrame.from_records([
# 1. Intangible Plant
(2, '301', 'Intangible: Organization'),
(3, '302', 'Intangible: Franchises and consents'),
(4, '303', 'Intangible: Miscellaneous intangible plant'),
(5, 'subtotal_intangible', 'Subtotal: Intangible Plant'),
# 2. Production Plant
# A. steam production
(8, '310', 'Steam production: Land and land rights'),
(9, '311', 'Steam production: Structures and improvements'),
(10, '312', 'Steam production: Boiler plant equipment'),
(11, '313', 'Steam production: Engines and engine-driven generators'),
(12, '314', 'Steam production: Turbogenerator units'),
(13, '315', 'Steam production: Accessory electric equipment'),
(14, '316', 'Steam production: Miscellaneous power plant equipment'),
(15, '317', 'Steam production: Asset retirement costs for steam production\
plant'),
(16, 'subtotal_steam_production', 'Subtotal: Steam Production Plant'),
# B. nuclear production
(18, '320', 'Nuclear production: Land and land rights (Major only)'),
(19, '321', 'Nuclear production: Structures and improvements (Major\
only)'),
(20, '322', 'Nuclear production: Reactor plant equipment (Major only)'),
(21, '323', 'Nuclear production: Turbogenerator units (Major only)'),
(22, '324', 'Nuclear production: Accessory electric equipment (Major\
only)'),
(23, '325', 'Nuclear production: Miscellaneous power plant equipment\
(Major only)'),
(24, '326', 'Nuclear production: Asset retirement costs for nuclear\
production plant (Major only)'),
(25, 'subtotal_nuclear_produciton', 'Subtotal: Nuclear Production Plant'),
# C. hydraulic production
(27, '330', 'Hydraulic production: Land and land rights'),
(28, '331', 'Hydraulic production: Structures and improvements'),
(29, '332', 'Hydraulic production: Reservoirs, dams, and waterways'),
(30, '333', 'Hydraulic production: Water wheels, turbines and generators'),
(31, '334', 'Hydraulic production: Accessory electric equipment'),
(32, '335', 'Hydraulic production: Miscellaneous power plant equipment'),
(33, '336', 'Hydraulic production: Roads, railroads and bridges'),
(34, '337', 'Hydraulic production: Asset retirement costs for hydraulic\
production plant'),
(35, 'subtotal_hydraulic_production', 'Subtotal: Hydraulic Production\
Plant'),
# D. other production
(37, '340', 'Other production: Land and land rights'),
(38, '341', 'Other production: Structures and improvements'),
(39, '342', 'Other production: Fuel holders, producers, and accessories'),
(40, '343', 'Other production: Prime movers'),
(41, '344', 'Other production: Generators'),
(42, '345', 'Other production: Accessory electric equipment'),
(43, '346', 'Other production: Miscellaneous power plant equipment'),
(44, '347', 'Other production: Asset retirement costs for other production\
plant'),
(None, '348', 'Other production: Energy Storage Equipment'),
(45, 'subtotal_other_production', 'Subtotal: Other Production Plant'),
(46, 'subtotal_production', 'Subtotal: Production Plant'),
# 3. Transmission Plant,
(48, '350', 'Transmission: Land and land rights'),
(None, '351', 'Transmission: Energy Storage Equipment'),
(49, '352', 'Transmission: Structures and improvements'),
(50, '353', 'Transmission: Station equipment'),
(51, '354', 'Transmission: Towers and fixtures'),
(52, '355', 'Transmission: Poles and fixtures'),
(53, '356', 'Transmission: Overhead conductors and devices'),
(54, '357', 'Transmission: Underground conduit'),
(55, '358', 'Transmission: Underground conductors and devices'),
(56, '359', 'Transmission: Roads and trails'),
(57, '359.1', 'Transmission: Asset retirement costs for transmission\
plant'),
(58, 'subtotal_transmission', 'Subtotal: Transmission Plant'),
# 4. Distribution Plant
(60, '360', 'Distribution: Land and land rights'),
(61, '361', 'Distribution: Structures and improvements'),
(62, '362', 'Distribution: Station equipment'),
(63, '363', 'Distribution: Storage battery equipment'),
(64, '364', 'Distribution: Poles, towers and fixtures'),
(65, '365', 'Distribution: Overhead conductors and devices'),
(66, '366', 'Distribution: Underground conduit'),
(67, '367', 'Distribution: Underground conductors and devices'),
(68, '368', 'Distribution: Line transformers'),
(69, '369', 'Distribution: Services'),
(70, '370', 'Distribution: Meters'),
(71, '371', 'Distribution: Installations on customers\' premises'),
(72, '372', 'Distribution: Leased property on customers\' premises'),
(73, '373', 'Distribution: Street lighting and signal systems'),
(74, '374', 'Distribution: Asset retirement costs for distribution plant'),
(75, 'subtotal_distribution', 'Subtotal: Distribution Plant'),
# 5. Regional Transmission and Market Operation Plant
(77, '380', 'Regional transmission: Land and land rights'),
(78, '381', 'Regional transmission: Structures and improvements'),
(79, '382', 'Regional transmission: Computer hardware'),
(80, '383', 'Regional transmission: Computer software'),
(81, '384', 'Regional transmission: Communication Equipment'),
(82, '385', 'Regional transmission: Miscellaneous Regional Transmission\
and Market Operation Plant'),
(83, '386', 'Regional transmission: Asset Retirement Costs for Regional\
Transmission and Market Operation\
Plant'),
(84, 'subtotal_regional_transmission', 'Subtotal: Transmission and Market\
Operation Plant'),
(None, '387', 'Regional transmission: [Reserved]'),
# 6. General Plant
(86, '389', 'General: Land and land rights'),
(87, '390', 'General: Structures and improvements'),
(88, '391', 'General: Office furniture and equipment'),
(89, '392', 'General: Transportation equipment'),
(90, '393', 'General: Stores equipment'),
(91, '394', 'General: Tools, shop and garage equipment'),
(92, '395', 'General: Laboratory equipment'),
(93, '396', 'General: Power operated equipment'),
(94, '397', 'General: Communication equipment'),
(95, '398', 'General: Miscellaneous equipment'),
(96, 'subtotal_general', 'Subtotal: General Plant'),
(97, '399', 'General: Other tangible property'),
(98, '399.1', 'General: Asset retirement costs for general plant'),
(99, 'total_general', 'TOTAL General Plant'),
(100, '101_and_106', 'Electric plant in service (Major only)'),
(101, '102_purchased', 'Electric plant purchased'),
(102, '102_sold', 'Electric plant sold'),
(103, '103', 'Experimental plant unclassified'),
(104, 'total_electric_plant', 'TOTAL Electric Plant in Service')],
columns=['row_number', 'ferc_account_id', 'ferc_account_description'])
"""list: A list of tuples containing row numbers, FERC account IDs, and FERC
account descriptions from FERC Form 1 pages 204 - 207, Electric Plant in
Service.
"""
# Line numbers, and corresponding FERC account number
# from FERC Form 1 page 219, ACCUMULATED PROVISION FOR DEPRECIATION
# OF ELECTRIC UTILITY PLANT (Account 108).
ferc_accumulated_depreciation = pd.DataFrame.from_records([
# Section A. Balances and Changes During Year
(1, 'balance_beginning_of_year', 'Balance Beginning of Year'),
(3, 'depreciation_expense', '(403) Depreciation Expense'),
(4, 'depreciation_expense_asset_retirement', \
'(403.1) Depreciation Expense for Asset Retirement Costs'),
(5, 'expense_electric_plant_leased_to_others', \
'(413) Exp. of Elec. Plt. Leas. to Others'),
(6, 'transportation_expenses_clearing',\
'Transportation Expenses-Clearing'),
(7, 'other_clearing_accounts', 'Other Clearing Accounts'),
(8, 'other_accounts_specified',\
'Other Accounts (Specify, details in footnote):'),
# blank: might also be other charges like line 17.
(9, 'other_charges', 'Other Charges:'),
(10, 'total_depreciation_provision_for_year',\
'TOTAL Deprec. Prov for Year (Enter Total of lines 3 thru 9)'),
(11, 'net_charges_for_plant_retired', 'Net Charges for Plant Retired:'),
(12, 'book_cost_of_plant_retired', 'Book Cost of Plant Retired'),
(13, 'cost_of_removal', 'Cost of Removal'),
(14, 'salvage_credit', 'Salvage (Credit)'),
(15, 'total_net_charges_for_plant_retired',\
'TOTAL Net Chrgs. for Plant Ret. (Enter Total of lines 12 thru 14)'),
(16, 'other_debit_or_credit_items',\
'Other Debit or Cr. Items (Describe, details in footnote):'),
# blank: can be "Other Charges", e.g. in 2012 for PSCo.
(17, 'other_charges_2', 'Other Charges 2'),
(18, 'book_cost_or_asset_retirement_costs_retired',\
'Book Cost or Asset Retirement Costs Retired'),
(19, 'balance_end_of_year', \
'Balance End of Year (Enter Totals of lines 1, 10, 15, 16, and 18)'),
# Section B. Balances at End of Year According to Functional Classification
(20, 'steam_production_end_of_year', 'Steam Production'),
(21, 'nuclear_production_end_of_year', 'Nuclear Production'),
(22, 'hydraulic_production_end_of_year',\
'Hydraulic Production-Conventional'),
(23, 'pumped_storage_end_of_year', 'Hydraulic Production-Pumped Storage'),
(24, 'other_production', 'Other Production'),
(25, 'transmission', 'Transmission'),
(26, 'distribution', 'Distribution'),
(27, 'regional_transmission_and_market_operation',
'Regional Transmission and Market Operation'),
(28, 'general', 'General'),
(29, 'total', 'TOTAL (Enter Total of lines 20 thru 28)')],
columns=['row_number', 'line_id', 'ferc_account_description'])
"""list: A list of tuples containing row numbers, FERC account IDs, and FERC
account descriptions from FERC Form 1 page 219, Accumulated Provision for
Depreciation of electric utility plant(Account 108).
"""
######################################################################
# Constants from EIA From 923 used within init.py module
######################################################################
# From Page 7 of EIA Form 923, Census Region a US state is located in
census_region = {
'NEW': 'New England',
'MAT': 'Middle Atlantic',
'SAT': 'South Atlantic',
'ESC': 'East South Central',
'WSC': 'West South Central',
'ENC': 'East North Central',
'WNC': 'West North Central',
'MTN': 'Mountain',
'PACC': 'Pacific Contiguous (OR, WA, CA)',
'PACN': 'Pacific Non-Contiguous (AK, HI)',
}
"""dict: A dictionary mapping Census Region abbreviations (keys) to Census
Region names (values).
"""
# From Page 7 of EIA Form923
# Static list of NERC (North American Electric Reliability Corporation)
# regions, used for where plant is located
nerc_region = {
'NPCC': 'Northeast Power Coordinating Council',
'ASCC': 'Alaska Systems Coordinating Council',
'HICC': 'Hawaiian Islands Coordinating Council',
'MRO': 'Midwest Reliability Organization',
'SERC': 'SERC Reliability Corporation',
'RFC': 'Reliability First Corporation',
'SPP': 'Southwest Power Pool',
'TRE': 'Texas Regional Entity',
'FRCC': 'Florida Reliability Coordinating Council',
'WECC': 'Western Electricity Coordinating Council'
}
"""dict: A dictionary mapping NERC Region abbreviations (keys) to NERC
Region names (values).
"""
# From Page 7 of EIA Form 923 EIA’s internal consolidated NAICS sectors.
# For internal purposes, EIA consolidates NAICS categories into seven groups.
sector_eia = {
# traditional regulated electric utilities
'1': 'Electric Utility',
# Independent power producers which are not cogenerators
'2': 'NAICS-22 Non-Cogen',
# Independent power producers which are cogenerators, but whose
# primary business purpose is the sale of electricity to the public
'3': 'NAICS-22 Cogen',
# Commercial non-cogeneration facilities that produce electric power,
# are connected to the gird, and can sell power to the public
'4': 'Commercial NAICS Non-Cogen',
# Commercial cogeneration facilities that produce electric power, are
# connected to the grid, and can sell power to the public
'5': 'Commercial NAICS Cogen',
# Industrial non-cogeneration facilities that produce electric power, are
# connected to the gird, and can sell power to the public
'6': 'Industrial NAICS Non-Cogen',
# Industrial cogeneration facilities that produce electric power, are
# connected to the gird, and can sell power to the public
'7': 'Industrial NAICS Cogen'
}
"""dict: A dictionary mapping EIA numeric codes (keys) to EIA’s internal
consolidated NAICS sectors (values).
"""
# EIA 923: EIA Type of prime mover:
prime_movers_eia923 = {
'BA': 'Energy Storage, Battery',
'BT': 'Turbines Used in a Binary Cycle. Including those used for geothermal applications',
'CA': 'Combined-Cycle -- Steam Part',
'CC': 'Combined-Cycle, Total Unit',
'CE': 'Energy Storage, Compressed Air',
'CP': 'Energy Storage, Concentrated Solar Power',
'CS': 'Combined-Cycle Single-Shaft Combustion Turbine and Steam Turbine share of single',
'CT': 'Combined-Cycle Combustion Turbine Part',
'ES': 'Energy Storage, Other (Specify on Schedule 9, Comments)',
'FC': 'Fuel Cell',
'FW': 'Energy Storage, Flywheel',
'GT': 'Combustion (Gas) Turbine. Including Jet Engine design',
'HA': 'Hydrokinetic, Axial Flow Turbine',
'HB': 'Hydrokinetic, Wave Buoy',
'HK': 'Hydrokinetic, Other',
'HY': 'Hydraulic Turbine. Including turbines associated with delivery of water by pipeline.',
'IC': 'Internal Combustion (diesel, piston, reciprocating) Engine',
'PS': 'Energy Storage, Reversible Hydraulic Turbine (Pumped Storage)',
'OT': 'Other',
'ST': 'Steam Turbine. Including Nuclear, Geothermal, and Solar Steam (does not include Combined Cycle).',
'PV': 'Photovoltaic',
'WT': 'Wind Turbine, Onshore',
'WS': 'Wind Turbine, Offshore'
}
"""dict: A dictionary mapping EIA 923 prime mover codes (keys) and prime mover
names / descriptions (values).
"""
# EIA 923: The fuel code reported to EIA.Two or three letter alphanumeric:
fuel_type_eia923 = {
'AB': 'Agricultural By-Products',
'ANT': 'Anthracite Coal',
'BFG': 'Blast Furnace Gas',
'BIT': 'Bituminous Coal',
'BLQ': 'Black Liquor',
'CBL': 'Coal, Blended',
'DFO': 'Distillate Fuel Oil. Including diesel, No. 1, No. 2, and No. 4 fuel oils.',
'GEO': 'Geothermal',
'JF': 'Jet Fuel',
'KER': 'Kerosene',
'LFG': 'Landfill Gas',
'LIG': 'Lignite Coal',
'MSB': 'Biogenic Municipal Solid Waste',
'MSN': 'Non-biogenic Municipal Solid Waste',
'MSW': 'Municipal Solid Waste',
'MWH': 'Electricity used for energy storage',
'NG': 'Natural Gas',
'NUC': 'Nuclear. Including Uranium, Plutonium, and Thorium.',
'OBG': 'Other Biomass Gas. Including digester gas, methane, and other biomass gases.',
'OBL': 'Other Biomass Liquids',
'OBS': 'Other Biomass Solids',
'OG': 'Other Gas',
'OTH': 'Other Fuel',
'PC': 'Petroleum Coke',
'PG': 'Gaseous Propane',
'PUR': 'Purchased Steam',
'RC': 'Refined Coal',
'RFO': 'Residual Fuel Oil. Including No. 5 & 6 fuel oils and bunker C fuel oil.',
'SC': 'Coal-based Synfuel. Including briquettes, pellets, or extrusions, which are formed by binding materials or processes that recycle materials.',
'SGC': 'Coal-Derived Synthesis Gas',
'SGP': 'Synthesis Gas from Petroleum Coke',
'SLW': 'Sludge Waste',
'SUB': 'Subbituminous Coal',
'SUN': 'Solar',
'TDF': 'Tire-derived Fuels',
'WAT': 'Water at a Conventional Hydroelectric Turbine and water used in Wave Buoy Hydrokinetic Technology, current Hydrokinetic Technology, Tidal Hydrokinetic Technology, and Pumping Energy for Reversible (Pumped Storage) Hydroelectric Turbines.',
'WC': 'Waste/Other Coal. Including anthracite culm, bituminous gob, fine coal, lignite waste, waste coal.',
'WDL': 'Wood Waste Liquids, excluding Black Liquor. Including red liquor, sludge wood, spent sulfite liquor, and other wood-based liquids.',
'WDS': 'Wood/Wood Waste Solids. Including paper pellets, railroad ties, utility polies, wood chips, bark, and other wood waste solids.',
'WH': 'Waste Heat not directly attributed to a fuel source',
'WND': 'Wind',
'WO': 'Waste/Other Oil. Including crude oil, liquid butane, liquid propane, naphtha, oil waste, re-refined moto oil, sludge oil, tar oil, or other petroleum-based liquid wastes.'
}
"""dict: A dictionary mapping EIA 923 fuel type codes (keys) and fuel type
names / descriptions (values).
"""
# Fuel type strings for EIA 923 generator fuel table
fuel_type_eia923_gen_fuel_coal_strings = [
'ant', 'bit', 'cbl', 'lig', 'pc', 'rc', 'sc', 'sub', 'wc', ]
"""list: The list of EIA 923 Generation Fuel strings associated with coal fuel.
"""
fuel_type_eia923_gen_fuel_oil_strings = [
'dfo', 'rfo', 'wo', 'jf', 'ker', ]
"""list: The list of EIA 923 Generation Fuel strings associated with oil fuel.
"""
fuel_type_eia923_gen_fuel_gas_strings = [
'bfg', 'lfg', 'ng', 'og', 'obg', 'pg', 'sgc', 'sgp', ]
"""list: The list of EIA 923 Generation Fuel strings associated with gas fuel.
"""
fuel_type_eia923_gen_fuel_solar_strings = ['sun', ]
"""list: The list of EIA 923 Generation Fuel strings associated with solar
power.
"""
fuel_type_eia923_gen_fuel_wind_strings = ['wnd', ]
"""list: The list of EIA 923 Generation Fuel strings associated with wind
power.
"""
fuel_type_eia923_gen_fuel_hydro_strings = ['wat', ]
"""list: The list of EIA 923 Generation Fuel strings associated with hydro
power.
"""
fuel_type_eia923_gen_fuel_nuclear_strings = ['nuc', ]
"""list: The list of EIA 923 Generation Fuel strings associated with nuclear
power.
"""
fuel_type_eia923_gen_fuel_waste_strings = [
'ab', 'blq', 'msb', 'msn', 'msw', 'obl', 'obs', 'slw', 'tdf', 'wdl', 'wds']
"""list: The list of EIA 923 Generation Fuel strings associated with solid waste
fuel.
"""
fuel_type_eia923_gen_fuel_other_strings = ['geo', 'mwh', 'oth', 'pur', 'wh', ]
"""list: The list of EIA 923 Generation Fuel strings associated with geothermal
power.
"""
fuel_type_eia923_gen_fuel_simple_map = {
'coal': fuel_type_eia923_gen_fuel_coal_strings,
'oil': fuel_type_eia923_gen_fuel_oil_strings,
'gas': fuel_type_eia923_gen_fuel_gas_strings,
'solar': fuel_type_eia923_gen_fuel_solar_strings,
'wind': fuel_type_eia923_gen_fuel_wind_strings,
'hydro': fuel_type_eia923_gen_fuel_hydro_strings,
'nuclear': fuel_type_eia923_gen_fuel_nuclear_strings,
'waste': fuel_type_eia923_gen_fuel_waste_strings,
'other': fuel_type_eia923_gen_fuel_other_strings,
}
"""dict: A dictionary mapping EIA 923 Generation Fuel fuel types (keys) to lists
of strings associated with that fuel type (values).
"""
# Fuel type strings for EIA 923 boiler fuel table
fuel_type_eia923_boiler_fuel_coal_strings = [
'ant', 'bit', 'lig', 'pc', 'rc', 'sc', 'sub', 'wc', ]
"""list: A list of strings from EIA 923 Boiler Fuel associated with fuel type
coal.
"""
fuel_type_eia923_boiler_fuel_oil_strings = ['dfo', 'rfo', 'wo', 'jf', 'ker', ]
"""list: A list of strings from EIA 923 Boiler Fuel associated with fuel type
oil.
"""
fuel_type_eia923_boiler_fuel_gas_strings = [
'bfg', 'lfg', 'ng', 'og', 'obg', 'pg', 'sgc', 'sgp', ]
"""list: A list of strings from EIA 923 Boiler Fuel associated with fuel type
gas.
"""
fuel_type_eia923_boiler_fuel_waste_strings = [
'ab', 'blq', 'msb', 'msn', 'obl', 'obs', 'slw', 'tdf', 'wdl', 'wds', ]
"""list: A list of strings from EIA 923 Boiler Fuel associated with fuel type
waste.
"""
fuel_type_eia923_boiler_fuel_other_strings = ['oth', 'pur', 'wh', ]
"""list: A list of strings from EIA 923 Boiler Fuel associated with fuel type
other.
"""
fuel_type_eia923_boiler_fuel_simple_map = {
'coal': fuel_type_eia923_boiler_fuel_coal_strings,
'oil': fuel_type_eia923_boiler_fuel_oil_strings,
'gas': fuel_type_eia923_boiler_fuel_gas_strings,
'waste': fuel_type_eia923_boiler_fuel_waste_strings,
'other': fuel_type_eia923_boiler_fuel_other_strings,
}
"""dict: A dictionary mapping EIA 923 Boiler Fuel fuel types (keys) to lists
of strings associated with that fuel type (values).
"""
# PUDL consolidation of EIA923 AER fuel type strings into same categories as
# 'energy_source_eia923' plus additional renewable and nuclear categories.
# These classifications are not currently used, as the EIA fuel type and energy
# source designations provide more detailed information.
aer_coal_strings = ['col', 'woc', 'pc']
"""list: A list of EIA 923 AER fuel type strings associated with coal.
"""
aer_gas_strings = ['mlg', 'ng', 'oog']
"""list: A list of EIA 923 AER fuel type strings associated with gas.
"""
aer_oil_strings = ['dfo', 'rfo', 'woo']
"""list: A list of EIA 923 AER fuel type strings associated with oil.
"""
aer_solar_strings = ['sun']
"""list: A list of EIA 923 AER fuel type strings associated with solar power.
"""
aer_wind_strings = ['wnd']
"""list: A list of EIA 923 AER fuel type strings associated with wind power.
"""
aer_hydro_strings = ['hps', 'hyc']
"""list: A list of EIA 923 AER fuel type strings associated with hydro power.
"""
aer_nuclear_strings = ['nuc']
"""list: A list of EIA 923 AER fuel type strings associated with nuclear power.
"""
aer_waste_strings = ['www']
"""list: A list of EIA 923 AER fuel type strings associated with waste.
"""
aer_other_strings = ['geo', 'orw', 'oth']
"""list: A list of EIA 923 AER fuel type strings associated with other fuel.
"""
aer_fuel_type_strings = {
'coal': aer_coal_strings,
'gas': aer_gas_strings,
'oil': aer_oil_strings,
'solar': aer_solar_strings,
'wind': aer_wind_strings,
'hydro': aer_hydro_strings,
'nuclear': aer_nuclear_strings,
'waste': aer_waste_strings,
'other': aer_other_strings
}
"""dict: A dictionary mapping EIA 923 AER fuel types (keys) to lists
of strings associated with that fuel type (values).
"""
# EIA 923: A partial aggregation of the reported fuel type codes into
# larger categories used by EIA in, for example,
# the Annual Energy Review (AER).Two or three letter alphanumeric.
# See the Fuel Code table (Table 5), below:
fuel_type_aer_eia923 = {
'SUN': 'Solar PV and thermal',
'COL': 'Coal',
'DFO': 'Distillate Petroleum',
'GEO': 'Geothermal',
'HPS': 'Hydroelectric Pumped Storage',
'HYC': 'Hydroelectric Conventional',
'MLG': 'Biogenic Municipal Solid Waste and Landfill Gas',
'NG': 'Natural Gas',
'NUC': 'Nuclear',
'OOG': 'Other Gases',
'ORW': 'Other Renewables',
'OTH': 'Other (including nonbiogenic MSW)',
'PC': 'Petroleum Coke',
'RFO': 'Residual Petroleum',
'WND': 'Wind',
'WOC': 'Waste Coal',
'WOO': 'Waste Oil',
'WWW': 'Wood and Wood Waste'
}
"""dict: A dictionary mapping EIA 923 AER fuel types (keys) to lists
of strings associated with that fuel type (values).
"""
fuel_type_eia860_coal_strings = ['ant', 'bit', 'cbl', 'lig', 'pc', 'rc', 'sc',
'sub', 'wc', 'coal', 'petroleum coke', 'col',
'woc']
"""list: A list of strings from EIA 860 associated with fuel type coal.
"""
fuel_type_eia860_oil_strings = ['dfo', 'jf', 'ker', 'rfo', 'wo', 'woo',
'petroleum']
"""list: A list of strings from EIA 860 associated with fuel type oil.
"""
fuel_type_eia860_gas_strings = ['bfg', 'lfg', 'mlg', 'ng', 'obg', 'og', 'pg',
'sgc', 'sgp', 'natural gas', 'other gas',
'oog', 'sg']
"""list: A list of strings from EIA 860 associated with fuel type gas.
"""
fuel_type_eia860_solar_strings = ['sun', 'solar']
"""list: A list of strings from EIA 860 associated with solar power.
"""
fuel_type_eia860_wind_strings = ['wnd', 'wind', 'wt']
"""list: A list of strings from EIA 860 associated with wind power.
"""
fuel_type_eia860_hydro_strings = ['wat', 'hyc', 'hps', 'hydro']
"""list: A list of strings from EIA 860 associated with hydro power.
"""
fuel_type_eia860_nuclear_strings = ['nuc', 'nuclear']
"""list: A list of strings from EIA 860 associated with nuclear power.
"""
fuel_type_eia860_waste_strings = ['ab', 'blq', 'bm', 'msb', 'msn', 'obl',
'obs', 'slw', 'tdf', 'wdl', 'wds', 'biomass',
'msw', 'www']
"""list: A list of strings from EIA 860 associated with fuel type waste.
"""
fuel_type_eia860_other_strings = ['mwh', 'oth', 'pur', 'wh', 'geo', 'none',
'orw', 'other']
"""list: A list of strings from EIA 860 associated with fuel type other.
"""
fuel_type_eia860_simple_map = {
'coal': fuel_type_eia860_coal_strings,
'oil': fuel_type_eia860_oil_strings,
'gas': fuel_type_eia860_gas_strings,
'solar': fuel_type_eia860_solar_strings,
'wind': fuel_type_eia860_wind_strings,
'hydro': fuel_type_eia860_hydro_strings,
'nuclear': fuel_type_eia860_nuclear_strings,
'waste': fuel_type_eia860_waste_strings,
'other': fuel_type_eia860_other_strings,
}
"""dict: A dictionary mapping EIA 860 fuel types (keys) to lists
of strings associated with that fuel type (values).
"""
# EIA 923/860: Lumping of energy source categories.
energy_source_eia_simple_map = {
'coal': ['ANT', 'BIT', 'LIG', 'PC', 'SUB', 'WC', 'RC'],
'oil': ['DFO', 'JF', 'KER', 'RFO', 'WO'],
'gas': ['BFG', 'LFG', 'NG', 'OBG', 'OG', 'PG', 'SG', 'SGC', 'SGP'],
'solar': ['SUN'],
'wind': ['WND'],
'hydro': ['WAT'],
'nuclear': ['NUC'],
'waste': ['AB', 'BLQ', 'MSW', 'OBL', 'OBS', 'SLW', 'TDF', 'WDL', 'WDS'],
'other': ['GEO', 'MWH', 'OTH', 'PUR', 'WH']
}
"""dict: A dictionary mapping EIA fuel types (keys) to fuel codes (values).
"""
fuel_group_eia923_simple_map = {
'coal': ['coal', 'petroleum coke'],
'oil': ['petroleum'],
'gas': ['natural gas', 'other gas']
}
"""dict: A dictionary mapping EIA 923 simple fuel types("oil", "coal", "gas")
(keys) to fuel types (values).
"""
# EIA 923: The type of physical units fuel consumption is reported in.
# All consumption is reported in either short tons for solids,
# thousands of cubic feet for gases, and barrels for liquids.
fuel_units_eia923 = {
'mcf': 'Thousands of cubic feet (for gases)',
'short_tons': 'Short tons (for solids)',
'barrels': 'Barrels (for liquids)'
}
"""dict: A dictionary mapping EIA 923 fuel units (keys) to fuel unit
descriptions (values).
"""
# EIA 923: Designates the purchase type under which receipts occurred
# in the reporting month. One or two character alphanumeric:
contract_type_eia923 = {
'C': 'Contract - Fuel received under a purchase order or contract with a term of one year or longer. Contracts with a shorter term are considered spot purchases ',
'NC': 'New Contract - Fuel received under a purchase order or contract with duration of one year or longer, under which deliveries were first made during the reporting month',
'N': 'New Contract - see NC code. This abbreviation existed only in 2008 before being replaced by NC.',
'S': 'Spot Purchase',
'T': 'Tolling Agreement – Fuel received under a tolling agreement (bartering arrangement of fuel for generation)'
}
"""dict: A dictionary mapping EIA 923 contract codes (keys) to contract
descriptions (values) for each month in the Fuel Receipts and Costs table.
"""
# EIA 923: The fuel code associated with the fuel receipt.
# Defined on Page 7 of EIA Form 923
# Two or three character alphanumeric:
energy_source_eia923 = {
'ANT': 'Anthracite Coal',
'BFG': 'Blast Furnace Gas',
'BM': 'Biomass',
'BIT': 'Bituminous Coal',
'DFO': 'Distillate Fuel Oil. Including diesel, No. 1, No. 2, and No. 4 fuel oils.',
'JF': 'Jet Fuel',
'KER': 'Kerosene',
'LIG': 'Lignite Coal',
'NG': 'Natural Gas',
'PC': 'Petroleum Coke',
'PG': 'Gaseous Propone',
'OG': 'Other Gas',
'RC': 'Refined Coal',
'RFO': 'Residual Fuel Oil. Including No. 5 & 6 fuel oils and bunker C fuel oil.',
'SG': 'Synthesis Gas from Petroleum Coke',
'SGP': 'Petroleum Coke Derived Synthesis Gas',
'SC': 'Coal-based Synfuel. Including briquettes, pellets, or extrusions, which are formed by binding materials or processes that recycle materials.',
'SUB': 'Subbituminous Coal',
'WC': 'Waste/Other Coal. Including anthracite culm, bituminous gob, fine coal, lignite waste, waste coal.',
'WO': 'Waste/Other Oil. Including crude oil, liquid butane, liquid propane, naphtha, oil waste, re-refined moto oil, sludge oil, tar oil, or other petroleum-based liquid wastes.',
}
"""dict: A dictionary mapping fuel codes (keys) to fuel descriptions (values)
for each fuel receipt from the EIA 923 Fuel Receipts and Costs table.
"""
# EIA 923 Fuel Group, from Page 7 EIA Form 923
# Groups fossil fuel energy sources into fuel groups that are located in the
# Electric Power Monthly: Coal, Natural Gas, Petroleum, Petroleum Coke.
fuel_group_eia923 = (
'coal',
'natural_gas',
'petroleum',
'petroleum_coke',
'other_gas'
)
"""tuple: A tuple containing EIA 923 fuel groups.
"""
# EIA 923: Type of Coal Mine as defined on Page 7 of EIA Form 923
coalmine_type_eia923 = {
'P': 'Preparation Plant',
'S': 'Surface',
'U': 'Underground',
'US': 'Both an underground and surface mine with most coal extracted from underground',
'SU': 'Both an underground and surface mine with most coal extracted from surface',
}
"""dict: A dictionary mapping EIA 923 coal mine type codes (keys) to
descriptions (values).
"""
# EIA 923: State abbreviation related to coal mine location.
# Country abbreviations are also used in this category, but they are
# non-standard because of collisions with US state names. Instead of using
# the provided non-standard names, we convert to ISO-3166-1 three letter
# country codes https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3
coalmine_country_eia923 = {
'AU': 'AUS', # Australia
'CL': 'COL', # Colombia
'CN': 'CAN', # Canada
'IS': 'IDN', # Indonesia
'PL': 'POL', # Poland
'RS': 'RUS', # Russia
'UK': 'GBR', # United Kingdom of Great Britain
'VZ': 'VEN', # Venezuela
'OT': 'other_country',
'IM': 'unknown'
}
"""dict: A dictionary mapping coal mine country codes (keys) to ISO-3166-1 three
letter country codes (values).
"""
# EIA 923: Mode for the longest / second longest distance.
transport_modes_eia923 = {
'RR': 'Rail: Shipments of fuel moved to consumers by rail \
(private or public/commercial). Included is coal hauled to or \
away from a railroad siding by truck if the truck did not use public\
roads.',
'RV': 'River: Shipments of fuel moved to consumers via river by barge. \
Not included are shipments to Great Lakes coal loading docks, \
tidewater piers, or coastal ports.',
'GL': 'Great Lakes: Shipments of coal moved to consumers via \
the Great Lakes. These shipments are moved via the Great Lakes \
coal loading docks, which are identified by name and location as \
follows: Conneaut Coal Storage & Transfer, Conneaut, Ohio; \
NS Coal Dock (Ashtabula Coal Dock), Ashtabula, Ohio; \
Sandusky Coal Pier, Sandusky, Ohio; Toledo Docks, Toledo, Ohio; \
KCBX Terminals Inc., Chicago, Illinois; \
Superior Midwest Energy Terminal, Superior, Wisconsin',
'TP': 'Tidewater Piers and Coastal Ports: Shipments of coal moved to \
Tidewater Piers and Coastal Ports for further shipments to consumers \
via coastal water or ocean. The Tidewater Piers and Coastal Ports \
are identified by name and location as follows: Dominion Terminal \
Associates, Newport News, Virginia; McDuffie Coal Terminal, Mobile, \
Alabama; IC Railmarine Terminal, Convent, Louisiana; \
International Marine Terminals, Myrtle Grove, Louisiana; \
Cooper/T. Smith Stevedoring Co. Inc., Darrow, Louisiana; \
Seward Terminal Inc., Seward, Alaska; Los Angeles Export Terminal, \
Inc., Los Angeles, California; Levin-Richmond Terminal Corp., \
Richmond, California; Baltimore Terminal, Baltimore, Maryland; \
Norfolk Southern Lamberts Point P-6, Norfolk, Virginia; \
Chesapeake Bay Piers, Baltimore, Maryland; Pier IX Terminal Company, \
Newport News, Virginia; Electro-Coal Transport Corp., Davant, \
Louisiana',
'WT': 'Water: Shipments of fuel moved to consumers by other waterways.',
'TR': 'Truck: Shipments of fuel moved to consumers by truck. \
Not included is fuel hauled to or away from a railroad siding by \
truck on non-public roads.',
'tr': 'Truck: Shipments of fuel moved to consumers by truck. \
Not included is fuel hauled to or away from a railroad siding by \
truck on non-public roads.',
'TC': 'Tramway/Conveyor: Shipments of fuel moved to consumers \
by tramway or conveyor.',
'SP': 'Slurry Pipeline: Shipments of coal moved to consumers \
by slurry pipeline.',
'PL': 'Pipeline: Shipments of fuel moved to consumers by pipeline'
}
"""dict: A dictionary mapping primary and secondary transportation mode codes
(keys) to descriptions (values).
"""
# we need to include all of the columns which we want to keep for either the
# entity or annual tables. The order here matters. We need to harvest the plant
# location before harvesting the location of the utilites for example.
entities = {
'plants': [
# base cols
['plant_id_eia'],
# static cols
['balancing_authority_code_eia', 'balancing_authority_name_eia',
'city', 'county', 'ferc_cogen_status',
'ferc_exempt_wholesale_generator', 'ferc_small_power_producer',
'grid_voltage_2_kv', 'grid_voltage_3_kv', 'grid_voltage_kv',
'iso_rto_code', 'latitude', 'longitude', 'service_area',
'plant_name_eia', 'primary_purpose_naics_id',
'sector_id', 'sector_name', 'state', 'street_address', 'zip_code'],
# annual cols
['ash_impoundment', 'ash_impoundment_lined', 'ash_impoundment_status',
'datum', 'energy_storage', 'ferc_cogen_docket_no', 'water_source',
'ferc_exempt_wholesale_generator_docket_no',
'ferc_small_power_producer_docket_no',
'liquefied_natural_gas_storage',
'natural_gas_local_distribution_company', 'natural_gas_storage',
'natural_gas_pipeline_name_1', 'natural_gas_pipeline_name_2',
'natural_gas_pipeline_name_3', 'nerc_region', 'net_metering',
'pipeline_notes', 'regulatory_status_code',
'transmission_distribution_owner_id',
'transmission_distribution_owner_name',
'transmission_distribution_owner_state', 'utility_id_eia'],
# need type fixing
{},
],
'generators': [
# base cols
['plant_id_eia', 'generator_id'],
# static cols
['prime_mover_code', 'duct_burners', 'operating_date',
'topping_bottoming_code', 'solid_fuel_gasification',
'pulverized_coal_tech', 'fluidized_bed_tech', 'subcritical_tech',
'supercritical_tech', 'ultrasupercritical_tech', 'stoker_tech',
'other_combustion_tech', 'bypass_heat_recovery',
'rto_iso_lmp_node_id', 'rto_iso_location_wholesale_reporting_id',
'associated_combined_heat_power', 'original_planned_operating_date',
'operating_switch', 'previously_canceled'],
# annual cols
['capacity_mw', 'fuel_type_code_pudl', 'multiple_fuels',
'ownership_code', 'owned_by_non_utility', 'deliver_power_transgrid',
'summer_capacity_mw', 'winter_capacity_mw', 'summer_capacity_estimate',
'winter_capacity_estimate', 'minimum_load_mw', 'distributed_generation',
'technology_description', 'reactive_power_output_mvar',
'energy_source_code_1', 'energy_source_code_2',
'energy_source_code_3', 'energy_source_code_4',
'energy_source_code_5', 'energy_source_code_6',
'energy_source_1_transport_1', 'energy_source_1_transport_2',
'energy_source_1_transport_3', 'energy_source_2_transport_1',
'energy_source_2_transport_2', 'energy_source_2_transport_3',
'startup_source_code_1', 'startup_source_code_2',
'startup_source_code_3', 'startup_source_code_4',
'time_cold_shutdown_full_load_code', 'syncronized_transmission_grid',
'turbines_num', 'operational_status_code', 'operational_status',
'planned_modifications', 'planned_net_summer_capacity_uprate_mw',
'planned_net_winter_capacity_uprate_mw', 'planned_new_capacity_mw',
'planned_uprate_date', 'planned_net_summer_capacity_derate_mw',
'planned_net_winter_capacity_derate_mw', 'planned_derate_date',
'planned_new_prime_mover_code', 'planned_energy_source_code_1',
'planned_repower_date', 'other_planned_modifications',
'other_modifications_date', 'planned_retirement_date',
'carbon_capture', 'cofire_fuels', 'switch_oil_gas',
'turbines_inverters_hydrokinetics', 'nameplate_power_factor',
'uprate_derate_during_year', 'uprate_derate_completed_date',
'current_planned_operating_date', 'summer_estimated_capability_mw',
'winter_estimated_capability_mw', 'retirement_date',
'utility_id_eia', 'data_source'],
# need type fixing
{}
],
# utilities must come after plants. plant location needs to be
# removed before the utility locations are compiled
'utilities': [
# base cols
['utility_id_eia'],
# static cols
['utility_name_eia'],
# annual cols
['street_address', 'city', 'state', 'zip_code', 'entity_type',
'plants_reported_owner', 'plants_reported_operator',
'plants_reported_asset_manager', 'plants_reported_other_relationship',
'attention_line', 'address_2', 'zip_code_4',
'contact_firstname', 'contact_lastname', 'contact_title',
'contact_firstname_2', 'contact_lastname_2', 'contact_title_2',
'phone_extension_1', 'phone_extension_2', 'phone_number_1',
'phone_number_2'],
# need type fixing
{'utility_id_eia': 'int64', }, ],
'boilers': [
# base cols
['plant_id_eia', 'boiler_id'],
# static cols
['prime_mover_code'],
# annual cols
[],
# need type fixing
{},
]
}
"""dict: A dictionary containing table name strings (keys) and lists of columns
to keep for those tables (values).
"""
epacems_tables = ("hourly_emissions_epacems")
"""tuple: A tuple containing tables of EPA CEMS data to pull into PUDL.
"""
files_dict_epaipm = {
'transmission_single_epaipm': '*table_3-21*',
'transmission_joint_epaipm': '*transmission_joint_ipm*',
'load_curves_epaipm': '*table_2-2_*',
'plant_region_map_epaipm': '*needs_v6*',
}
"""dict: A dictionary of EPA IPM tables and strings that files of those tables
contain.
"""
epaipm_url_ext = {
'transmission_single_epaipm': 'table_3-21_annual_transmission_capabilities_of_u.s._model_regions_in_epa_platform_v6_-_2021.xlsx',
'load_curves_epaipm': 'table_2-2_load_duration_curves_used_in_epa_platform_v6.xlsx',
'plant_region_map_epaipm': 'needs_v6_november_2018_reference_case_0.xlsx',
}
"""dict: A dictionary of EPA IPM tables and associated URLs extensions for
downloading that table's data.
"""
epaipm_region_names = [
'ERC_PHDL', 'ERC_REST', 'ERC_FRNT', 'ERC_GWAY', 'ERC_WEST',
'FRCC', 'NENG_CT', 'NENGREST', 'NENG_ME', 'MIS_AR', 'MIS_IL',
'MIS_INKY', 'MIS_IA', 'MIS_MIDA', 'MIS_LA', 'MIS_LMI', 'MIS_MNWI',
'MIS_D_MS', 'MIS_MO', 'MIS_MAPP', 'MIS_AMSO', 'MIS_WOTA',
'MIS_WUMS', 'NY_Z_A', 'NY_Z_B', 'NY_Z_C&E', 'NY_Z_D', 'NY_Z_F',
'NY_Z_G-I', 'NY_Z_J', 'NY_Z_K', 'PJM_West', 'PJM_AP', 'PJM_ATSI',
'PJM_COMD', 'PJM_Dom', 'PJM_EMAC', 'PJM_PENE', 'PJM_SMAC',
'PJM_WMAC', 'S_C_KY', 'S_C_TVA', 'S_D_AECI', 'S_SOU', 'S_VACA',
'SPP_NEBR', 'SPP_N', 'SPP_SPS', 'SPP_WEST', 'SPP_KIAM', 'SPP_WAUE',
'WECC_AZ', 'WEC_BANC', 'WECC_CO', 'WECC_ID', 'WECC_IID',
'WEC_LADW', 'WECC_MT', 'WECC_NM', 'WEC_CALN', 'WECC_NNV',
'WECC_PNW', 'WEC_SDGE', 'WECC_SCE', 'WECC_SNV', 'WECC_UT',
'WECC_WY', 'CN_AB', 'CN_BC', 'CN_NL', 'CN_MB', 'CN_NB', 'CN_NF',
'CN_NS', 'CN_ON', 'CN_PE', 'CN_PQ', 'CN_SK',
]
"""list: A list of EPA IPM region names."""
epaipm_region_aggregations = {
'PJM': [
'PJM_AP', 'PJM_ATSI', 'PJM_COMD', 'PJM_Dom',
'PJM_EMAC', 'PJM_PENE', 'PJM_SMAC', 'PJM_WMAC'
],
'NYISO': [
'NY_Z_A', 'NY_Z_B', 'NY_Z_C&E', 'NY_Z_D',
'NY_Z_F', 'NY_Z_G-I', 'NY_Z_J', 'NY_Z_K'
],
'ISONE': ['NENG_CT', 'NENGREST', 'NENG_ME'],
'MISO': [
'MIS_AR', 'MIS_IL', 'MIS_INKY', 'MIS_IA',
'MIS_MIDA', 'MIS_LA', 'MIS_LMI', 'MIS_MNWI', 'MIS_D_MS',
'MIS_MO', 'MIS_MAPP', 'MIS_AMSO', 'MIS_WOTA', 'MIS_WUMS'
],
'SPP': [
'SPP_NEBR', 'SPP_N', 'SPP_SPS', 'SPP_WEST', 'SPP_KIAM', 'SPP_WAUE'
],
'WECC_NW': [
'WECC_CO', 'WECC_ID', 'WECC_MT', 'WECC_NNV',
'WECC_PNW', 'WECC_UT', 'WECC_WY'
]
}
"""
dict: A dictionary containing EPA IPM regions (keys) and lists of their
associated abbreviations (values).
"""
epaipm_rename_dict = {
'transmission_single_epaipm': {
'From': 'region_from',
'To': 'region_to',
'Capacity TTC (MW)': 'firm_ttc_mw',
'Energy TTC (MW)': 'nonfirm_ttc_mw',
'Transmission Tariff (2016 mills/kWh)': 'tariff_mills_kwh',
},
'load_curves_epaipm': {
'day': 'day_of_year',
'region': 'region_id_epaipm',
},
'plant_region_map_epaipm': {
'ORIS Plant Code': 'plant_id_eia',
'Region Name': 'region',
},
}
glue_pudl_tables = ('plants_eia', 'plants_ferc', 'plants', 'utilities_eia',
'utilities_ferc', 'utilities', 'utility_plant_assn')
"""
dict: A dictionary of dictionaries containing EPA IPM tables (keys) and items
for each table to be renamed along with the replacement name (values).
"""
data_sources = (
'eia860',
'eia861',
'eia923',
'epacems',
'epaipm',
'ferc1',
'ferc714',
# 'pudl'
)
"""tuple: A tuple containing the data sources we are able to pull into PUDL."""
# All the years for which we ought to be able to download these data sources
data_years = {
'eia860': tuple(range(2001, 2020)),
'eia861': tuple(range(1990, 2020)),
'eia923': tuple(range(2001, 2020)),
'epacems': tuple(range(1995, 2021)),
'epaipm': (None, ),
'ferc1': tuple(range(1994, 2020)),
'ferc714': (None, ),
}
"""
dict: A dictionary of data sources (keys) and tuples containing the years
that we expect to be able to download for each data source (values).
"""
# The full set of years we currently expect to be able to ingest, per source:
working_partitions = {
'eia860': {
'years': tuple(range(2004, 2020))
},
'eia860m': {
'year_month': '2020-11'
},
'eia861': {
'years': tuple(range(2001, 2020))
},
'eia923': {
'years': tuple(range(2001, 2020))
},
'epacems': {
'years': tuple(range(1995, 2021)),
'states': tuple(cems_states.keys())},
'ferc1': {
'years': tuple(range(1994, 2020))
},
'ferc714': {},
}
"""
dict: A dictionary of data sources (keys) and dictionaries (values) of names of
partition type (sub-key) and paritions (sub-value) containing the paritions
such as tuples of years for each data source that are able to be ingested
into PUDL.
"""
pudl_tables = {
'eia860': eia860_pudl_tables,
'eia861': (
"service_territory_eia861",
"balancing_authority_eia861",
"sales_eia861",
"advanced_metering_infrastructure_eia861",
"demand_response_eia861",
"demand_side_management_eia861",
"distributed_generation_eia861",
"distribution_systems_eia861",
"dynamic_pricing_eia861",
"energy_efficiency_eia861",
"green_pricing_eia861",
"mergers_eia861",
"net_metering_eia861",
"non_net_metering_eia861",
"operational_data_eia861",
"reliability_eia861",
"utility_data_eia861",
),
'eia923': eia923_pudl_tables,
'epacems': epacems_tables,
'epaipm': epaipm_pudl_tables,
'ferc1': ferc1_pudl_tables,
'ferc714': (
"respondent_id_ferc714",
"id_certification_ferc714",
"gen_plants_ba_ferc714",
"demand_monthly_ba_ferc714",
"net_energy_load_ba_ferc714",
"adjacency_ba_ferc714",
"interchange_ba_ferc714",
"lambda_hourly_ba_ferc714",
"lambda_description_ferc714",
"description_pa_ferc714",
"demand_forecast_pa_ferc714",
"demand_hourly_pa_ferc714",
),
'glue': glue_pudl_tables,
}
"""
dict: A dictionary containing data sources (keys) and the list of associated
tables from that datasource that can be pulled into PUDL (values).
"""
base_data_urls = {
'eia860': 'https://www.eia.gov/electricity/data/eia860',
'eia861': 'https://www.eia.gov/electricity/data/eia861/zip',
'eia923': 'https://www.eia.gov/electricity/data/eia923',
'epacems': 'ftp://newftp.epa.gov/dmdnload/emissions/hourly/monthly',
'ferc1': 'ftp://eforms1.ferc.gov/f1allyears',
'ferc714': 'https://www.ferc.gov/docs-filing/forms/form-714/data',
'ferceqr': 'ftp://eqrdownload.ferc.gov/DownloadRepositoryProd/BulkNew/CSV',
'msha': 'https://arlweb.msha.gov/OpenGovernmentData/DataSets',
'epaipm': 'https://www.epa.gov/sites/production/files/2019-03',
'pudl': 'https://catalyst.coop/pudl/'
}
"""
dict: A dictionary containing data sources (keys) and their base data URLs
(values).
"""
need_fix_inting = {
'plants_steam_ferc1': ('construction_year', 'installation_year'),
'plants_small_ferc1': ('construction_year', 'ferc_license_id'),
'plants_hydro_ferc1': ('construction_year', 'installation_year',),
'plants_pumped_storage_ferc1': ('construction_year', 'installation_year',),
'hourly_emissions_epacems': ('facility_id', 'unit_id_epa',),
}
"""
dict: A dictionary containing tables (keys) and column names (values)
containing integer - type columns whose null values need fixing.
"""
contributors = {
"catalyst-cooperative": {
"title": "Catalyst Cooperative",
"path": "https://catalyst.coop/",
"role": "publisher",
"email": "<EMAIL>",
"organization": "Catalyst Cooperative",
},
"zane-selvans": {
"title": "<NAME>",
"email": "<EMAIL>",
"path": "https://amateurearthling.org/",
"role": "wrangler",
"organization": "Catalyst Cooperative"
},
"christina-gosnell": {
"title": "<NAME>",
"email": "<EMAIL>",
"role": "contributor",
"organization": "Catalyst Cooperative",
},
"steven-winter": {
"title": "<NAME>",
"email": "<EMAIL>",
"role": "contributor",
"organization": "Catalyst Cooperative",
},
"alana-wilson": {
"title": "<NAME>",
"email": "<EMAIL>",
"role": "contributor",
"organization": "Catalyst Cooperative",
},
"karl-dunkle-werner": {
"title": "<NAME>",
"email": "<EMAIL>",
"path": "https://karldw.org/",
"role": "contributor",
"organization": "UC Berkeley",
},
'greg-schivley': {
"title": "<NAME>",
"role": "contributor",
},
}
"""
dict: A dictionary of dictionaries containing organization names (keys) and
their attributes (values).
"""
data_source_info = {
"eia860": {
"title": "EIA Form 860",
"path": "https://www.eia.gov/electricity/data/eia860/",
},
"eia861": {
"title": "EIA Form 861",
"path": "https://www.eia.gov/electricity/data/eia861/",
},
"eia923": {
"title": "EIA Form 923",
"path": "https://www.eia.gov/electricity/data/eia923/",
},
"eiawater": {
"title": "EIA Water Use for Power",
"path": "https://www.eia.gov/electricity/data/water/",
},
"epacems": {
"title": "EPA Air Markets Program Data",
"path": "https://ampd.epa.gov/ampd/",
},
"epaipm": {
"title": "EPA Integrated Planning Model",
"path": "https://www.epa.gov/airmarkets/national-electric-energy-data-system-needs-v6",
},
"ferc1": {
"title": "FERC Form 1",
"path": "https://www.ferc.gov/docs-filing/forms/form-1/data.asp",
},
"ferc714": {
"title": "FERC Form 714",
"path": "https://www.ferc.gov/docs-filing/forms/form-714/data.asp",
},
"ferceqr": {
"title": "FERC Electric Quarterly Report",
"path": "https://www.ferc.gov/docs-filing/eqr.asp",
},
"msha": {
"title": "Mining Safety and Health Administration",
"path": "https://www.msha.gov/mine-data-retrieval-system",
},
"phmsa": {
"title": "Pipelines and Hazardous Materials Safety Administration",
"path": "https://www.phmsa.dot.gov/data-and-statistics/pipeline/data-and-statistics-overview",
},
"pudl": {
"title": "The Public Utility Data Liberation Project (PUDL)",
"path": "https://catalyst.coop/pudl/",
"email": "<EMAIL>",
},
}
"""
dict: A dictionary of dictionaries containing datasources (keys) and
associated attributes (values)
"""
contributors_by_source = {
"pudl": [
"catalyst-cooperative",
"zane-selvans",
"christina-gosnell",
"steven-winter",
"alana-wilson",
"karl-dunkle-werner",
],
"eia923": [
"catalyst-cooperative",
"zane-selvans",
"christina-gosnell",
"steven-winter",
],
"eia860": [
"catalyst-cooperative",
"zane-selvans",
"christina-gosnell",
"steven-winter",
"alana-wilson",
],
"ferc1": [
"catalyst-cooperative",
"zane-selvans",
"christina-gosnell",
"steven-winter",
"alana-wilson",
],
"epacems": [
"catalyst-cooperative",
"karl-dunkle-werner",
"zane-selvans",
],
"epaipm": [
"greg-schivley",
],
}
"""
dict: A dictionary of data sources (keys) and lists of contributors (values).
"""
licenses = {
"cc-by-4.0": {
"name": "CC-BY-4.0",
"title": "Creative Commons Attribution 4.0",
"path": "https://creativecommons.org/licenses/by/4.0/"
},
"us-govt": {
"name": "other-pd",
"title": "U.S. Government Work",
"path": "http://www.usa.gov/publicdomain/label/1.0/",
}
}
"""
dict: A dictionary of dictionaries containing license types and their
attributes.
"""
output_formats = [
'sqlite',
'parquet',
'datapkg',
]
"""list: A list of types of PUDL output formats."""
keywords_by_data_source = {
'pudl': [
'us', 'electricity',
],
'eia860': [
'electricity', 'electric', 'boiler', 'generator', 'plant', 'utility',
'fuel', 'coal', 'natural gas', 'prime mover', 'eia860', 'retirement',
'capacity', 'planned', 'proposed', 'energy', 'hydro', 'solar', 'wind',
'nuclear', 'form 860', 'eia', 'annual', 'gas', 'ownership', 'steam',
'turbine', 'combustion', 'combined cycle', 'eia',
'energy information administration'
],
'eia923': [
'fuel', 'boiler', 'generator', 'plant', 'utility', 'cost', 'price',
'natural gas', 'coal', 'eia923', 'energy', 'electricity', 'form 923',
'receipts', 'generation', 'net generation', 'monthly', 'annual', 'gas',
'fuel consumption', 'MWh', 'energy information administration', 'eia',
'mercury', 'sulfur', 'ash', 'lignite', 'bituminous', 'subbituminous',
'heat content'
],
'epacems': [
'epa', 'us', 'emissions', 'pollution', 'ghg', 'so2', 'co2', 'sox',
'nox', 'load', 'utility', 'electricity', 'plant', 'generator', 'unit',
'generation', 'capacity', 'output', 'power', 'heat content', 'mmbtu',
'steam', 'cems', 'continuous emissions monitoring system', 'hourly'
'environmental protection agency', 'ampd', 'air markets program data',
],
'ferc1': [
'electricity', 'electric', 'utility', 'plant', 'steam', 'generation',
'cost', 'expense', 'price', 'heat content', 'ferc', 'form 1',
'federal energy regulatory commission', 'capital', 'accounting',
'depreciation', 'finance', 'plant in service', 'hydro', 'coal',
'natural gas', 'gas', 'opex', 'capex', 'accounts', 'investment',
'capacity'
],
'ferc714': [
'electricity', 'electric', 'utility', 'planning area', 'form 714',
'balancing authority', 'demand', 'system lambda', 'ferc',
'federal energy regulatory commission', "hourly", "generation",
"interchange", "forecast", "load", "adjacency", "plants",
],
'epaipm': [
'epaipm', 'integrated planning',
]
}
"""dict: A dictionary of datasets (keys) and keywords (values). """
ENTITY_TYPE_DICT = {
'M': 'Municipal',
'C': 'Cooperative',
'R': 'Retail Power Marketer',
'I': 'Investor Owned',
'P': 'Political Subdivision',
'T': 'Transmission',
'S': 'State',
'W': 'Wholesale Power Marketer',
'F': 'Federal',
'A': 'Municipal Mktg Authority',
'G': 'Community Choice Aggregator',
'D': 'Nonutility DSM Administrator',
'B': 'Behind the Meter',
'Q': 'Independent Power Producer',
'IND': 'Industrial',
'COM': 'Commercial',
'PR': 'Private', # Added by AES for OD table (Arbitrary moniker)
'PO': 'Power Marketer', # Added by AES for OD table
'U': 'Unknown', # Added by AES for OD table
'O': 'Other' # Added by AES for OD table
}
# Confirm these designations -- educated guess based on the form instructions
MOMENTARY_INTERRUPTION_DEF = { # Added by AES for R table
'L': 'Less than 1 minute',
'F': 'Less than or equal to 5 minutes',
'O': 'Other',
}
# https://www.eia.gov/electricity/data/eia411/#tabs_NERC-3
RECOGNIZED_NERC_REGIONS = [
'BASN', # ASSESSMENT AREA Basin (WECC)
'CALN', # ASSESSMENT AREA California (WECC)
'CALS', # ASSESSMENT AREA California (WECC)
'DSW', # ASSESSMENT AREA Desert Southwest (WECC)
'ASCC', # Alaska
'ISONE', # ISO New England (NPCC)
'ERCOT', # lumped under TRE in 2017 Form instructions
'NORW', # ASSESSMENT AREA Northwest (WECC)
'NYISO', # ISO (NPCC)
'PJM', # RTO
'ROCK', # ASSESSMENT AREA Rockies (WECC)
'ECAR', # OLD RE Now part of RFC and SERC
'FRCC', # included in 2017 Form instructions, recently joined with SERC
'HICC', # Hawaii
'MAAC', # OLD RE Now part of RFC
'MAIN', # OLD RE Now part of SERC, RFC, MRO
'MAPP', # OLD/NEW RE Became part of MRO, resurfaced in 2010
'MRO', # RE included in 2017 Form instructions
'NPCC', # RE included in 2017 Form instructions
'RFC', # RE included in 2017 Form instructions
'SERC', # RE included in 2017 Form instructions
'SPP', # RE included in 2017 Form instructions
'TRE', # RE included in 2017 Form instructions (included ERCOT)
'WECC', # RE included in 2017 Form instructions
'WSCC', # OLD RE pre-2002 version of WECC
'MISO', # ISO unclear whether technically a regional entity, but lots of entries
'ECAR_MAAC',
'MAPP_WECC',
'RFC_SERC',
'SPP_WECC',
'MRO_WECC',
'ERCOT_SPP',
'SPP_TRE',
'ERCOT_TRE',
'MISO_TRE',
'VI', # Virgin Islands
'GU', # Guam
'PR', # Puerto Rico
'AS', # American Samoa
'UNK',
]
CUSTOMER_CLASSES = [
"commercial",
"industrial",
"direct_connection",
"other",
"residential",
"total",
"transportation"
]
TECH_CLASSES = [
'backup', # WHERE Is this used? because removed from DG table b/c not a real component
'chp_cogen',
'combustion_turbine',
'fuel_cell',
'hydro',
'internal_combustion',
'other',
'pv',
'steam',
'storage_pv',
'all_storage', # need 'all' as prefix so as not to confuse with other storage category
'total',
'virtual_pv',
'wind',
]
REVENUE_CLASSES = [
'retail_sales',
'unbundled',
'delivery_customers',
'sales_for_resale',
'credits_or_adjustments',
'other',
'transmission',
'total',
]
RELIABILITY_STANDARDS = [
'ieee_standard',
'other_standard'
]
FUEL_CLASSES = [
'gas',
'oil',
'other',
'renewable',
'water',
'wind',
'wood',
]
RTO_CLASSES = [
'caiso',
'ercot',
'pjm',
'nyiso',
'spp',
'miso',
'isone',
'other'
]
ESTIMATED_OR_ACTUAL = {'E': 'estimated', 'A': 'actual'}
TRANSIT_TYPE_DICT = {
'CV': 'conveyer',
'PL': 'pipeline',
'RR': 'railroad',
'TK': 'truck',
'WA': 'water',
'UN': 'unknown',
}
"""dict: A dictionary of datasets (keys) and keywords (values). """
column_dtypes = {
"ferc1": { # Obviously this is not yet a complete list...
"construction_year": pd.Int64Dtype(),
"installation_year": pd.Int64Dtype(),
"plant_id_ferc1": pd.Int64Dtype(),
"plant_id_pudl": pd.Int64Dtype(),
"report_date": "datetime64[ns]",
"report_year": pd.Int64Dtype(),
"utility_id_ferc1": pd.Int64Dtype(),
"utility_id_pudl": pd.Int64Dtype(),
},
"ferc714": { # INCOMPLETE
"demand_mwh": float,
"demand_annual_mwh": float,
"eia_code": pd.Int64Dtype(),
"peak_demand_summer_mw": float,
"peak_demand_winter_mw": float,
"report_date": "datetime64[ns]",
"respondent_id_ferc714": pd.Int64Dtype(),
"respondent_name_ferc714": pd.StringDtype(),
"respondent_type": pd.CategoricalDtype(categories=[
"utility", "balancing_authority",
]),
"timezone": pd.CategoricalDtype(categories=[
"America/New_York", "America/Chicago", "America/Denver",
"America/Los_Angeles", "America/Anchorage", "Pacific/Honolulu"]),
"utc_datetime": "datetime64[ns]",
},
"epacems": {
'state': pd.StringDtype(),
'plant_id_eia': pd.Int64Dtype(), # Nullable Integer
'unitid': pd.StringDtype(),
'operating_datetime_utc': "datetime64[ns]",
'operating_time_hours': float,
'gross_load_mw': float,
'steam_load_1000_lbs': float,
'so2_mass_lbs': float,
'so2_mass_measurement_code': pd.StringDtype(),
'nox_rate_lbs_mmbtu': float,
'nox_rate_measurement_code': pd.StringDtype(),
'nox_mass_lbs': float,
'nox_mass_measurement_code': pd.StringDtype(),
'co2_mass_tons': float,
'co2_mass_measurement_code': pd.StringDtype(),
'heat_content_mmbtu': float,
'facility_id': pd.Int64Dtype(), # Nullable Integer
'unit_id_epa': pd.Int64Dtype(), # Nullable Integer
},
"eia": {
'actual_peak_demand_savings_mw': float, # Added by AES for DR table
'address_2': pd.StringDtype(), # Added by AES for 860 utilities table
'advanced_metering_infrastructure': pd.Int64Dtype(), # Added by AES for AMI table
# Added by AES for UD misc table
'alternative_fuel_vehicle_2_activity': pd.BooleanDtype(),
'alternative_fuel_vehicle_activity': pd.BooleanDtype(),
'annual_indirect_program_cost': float,
'annual_total_cost': float,
'ash_content_pct': float,
'ash_impoundment': pd.BooleanDtype(),
'ash_impoundment_lined': pd.BooleanDtype(),
# TODO: convert this field to more descriptive words
'ash_impoundment_status': pd.StringDtype(),
'associated_combined_heat_power': pd.BooleanDtype(),
'attention_line': pd.StringDtype(),
'automated_meter_reading': pd.Int64Dtype(), # Added by AES for AMI table
'backup_capacity_mw': float, # Added by AES for NNM & DG misc table
'balancing_authority_code_eia': pd.CategoricalDtype(),
'balancing_authority_id_eia': pd.Int64Dtype(),
'balancing_authority_name_eia': pd.StringDtype(),
'bga_source': pd.StringDtype(),
'boiler_id': pd.StringDtype(),
'bunded_activity': pd.BooleanDtype(),
'business_model': pd.CategoricalDtype(categories=[
"retail", "energy_services"]),
'buy_distribution_activity': pd.BooleanDtype(),
'buying_transmission_activity': pd.BooleanDtype(),
'bypass_heat_recovery': pd.BooleanDtype(),
'caidi_w_major_event_days_minus_loss_of_service_minutes': float,
'caidi_w_major_event_dats_minutes': float,
'caidi_wo_major_event_days_minutes': float,
'capacity_mw': float,
'carbon_capture': pd.BooleanDtype(),
'chlorine_content_ppm': float,
'circuits_with_voltage_optimization': pd.Int64Dtype(),
'city': pd.StringDtype(),
'cofire_fuels': pd.BooleanDtype(),
'consumed_by_facility_mwh': float,
'consumed_by_respondent_without_charge_mwh': float,
'contact_firstname': pd.StringDtype(),
'contact_firstname_2': pd.StringDtype(),
'contact_lastname': pd.StringDtype(),
'contact_lastname_2': pd.StringDtype(),
'contact_title': pd.StringDtype(),
'contact_title_2': pd.StringDtype(),
'contract_expiration_date': 'datetime64[ns]',
'contract_type_code': pd.StringDtype(),
'county': pd.StringDtype(),
'county_id_fips': pd.StringDtype(), # Must preserve leading zeroes
'credits_or_adjustments': float,
'critical_peak_pricing': pd.BooleanDtype(),
'critical_peak_rebate': pd.BooleanDtype(),
'current_planned_operating_date': 'datetime64[ns]',
'customers': float,
'customer_class': pd.CategoricalDtype(categories=CUSTOMER_CLASSES),
'customer_incentives_cost': float,
'customer_incentives_incremental_cost': float,
'customer_incentives_incremental_life_cycle_cost': float,
'customer_other_costs_incremental_life_cycle_cost': float,
'daily_digital_access_customers': pd.Int64Dtype(),
'data_observed': pd.BooleanDtype(),
'datum': pd.StringDtype(),
'deliver_power_transgrid': pd.BooleanDtype(),
'delivery_customers': float,
'direct_load_control_customers': pd.Int64Dtype(),
'distributed_generation': pd.BooleanDtype(),
'distributed_generation_owned_capacity_mw': float,
'distribution_activity': pd.BooleanDtype(),
'distribution_circuits': pd.Int64Dtype(),
'duct_burners': pd.BooleanDtype(),
'energy_displaced_mwh': float,
'energy_efficiency_annual_cost': float,
'energy_efficiency_annual_actual_peak_reduction_mw': float,
'energy_efficiency_annual_effects_mwh': float,
'energy_efficiency_annual_incentive_payment': float,
'energy_efficiency_incremental_actual_peak_reduction_mw': float,
'energy_efficiency_incremental_effects_mwh': float,
'energy_savings_estimates_independently_verified': pd.BooleanDtype(),
'energy_savings_independently_verified': pd.BooleanDtype(),
'energy_savings_mwh': float,
'energy_served_ami_mwh': float,
'energy_source_1_transport_1': pd.CategoricalDtype(categories=TRANSIT_TYPE_DICT.values()),
'energy_source_1_transport_2': pd.CategoricalDtype(categories=TRANSIT_TYPE_DICT.values()),
'energy_source_1_transport_3': pd.CategoricalDtype(categories=TRANSIT_TYPE_DICT.values()),
'energy_source_2_transport_1': pd.CategoricalDtype(categories=TRANSIT_TYPE_DICT.values()),
'energy_source_2_transport_2': pd.CategoricalDtype(categories=TRANSIT_TYPE_DICT.values()),
'energy_source_2_transport_3': pd.CategoricalDtype(categories=TRANSIT_TYPE_DICT.values()),
'energy_source_code': pd.StringDtype(),
'energy_source_code_1': pd.StringDtype(),
'energy_source_code_2': pd.StringDtype(),
'energy_source_code_3': pd.StringDtype(),
'energy_source_code_4': pd.StringDtype(),
'energy_source_code_5': pd.StringDtype(),
'energy_source_code_6': pd.StringDtype(),
'energy_storage': pd.BooleanDtype(),
'entity_type': pd.CategoricalDtype(categories=ENTITY_TYPE_DICT.values()),
'estimated_or_actual_capacity_data': pd.CategoricalDtype(categories=ESTIMATED_OR_ACTUAL.values()),
'estimated_or_actual_fuel_data': pd.CategoricalDtype(categories=ESTIMATED_OR_ACTUAL.values()),
'estimated_or_actual_tech_data': pd.CategoricalDtype(categories=ESTIMATED_OR_ACTUAL.values()),
'exchange_energy_delivered_mwh': float,
'exchange_energy_recieved_mwh': float,
'ferc_cogen_docket_no': pd.StringDtype(),
'ferc_cogen_status': pd.BooleanDtype(),
'ferc_exempt_wholesale_generator': pd.BooleanDtype(),
'ferc_exempt_wholesale_generator_docket_no': pd.StringDtype(),
'ferc_small_power_producer': pd.BooleanDtype(),
'ferc_small_power_producer_docket_no': pd.StringDtype(),
'fluidized_bed_tech': pd.BooleanDtype(),
'fraction_owned': float,
'fuel_class': pd.StringDtype(),
'fuel_consumed_for_electricity_mmbtu': float,
'fuel_consumed_for_electricity_units': float,
'fuel_consumed_mmbtu': float,
'fuel_consumed_units': float,
'fuel_cost_per_mmbtu': float,
'fuel_group_code': pd.StringDtype(),
'fuel_group_code_simple': pd.StringDtype(),
'fuel_mmbtu_per_unit': float,
'fuel_pct': float,
'fuel_qty_units': float,
# are fuel_type and fuel_type_code the same??
# fuel_type includes 40 code-like things.. WAT, SUN, NUC, etc.
'fuel_type': pd.StringDtype(),
# from the boiler_fuel_eia923 table, there are 30 code-like things, like NG, BIT, LIG
'fuel_type_code': pd.StringDtype(),
'fuel_type_code_aer': pd.StringDtype(),
'fuel_type_code_pudl': pd.StringDtype(),
'furnished_without_charge_mwh': float,
'generation_activity': pd.BooleanDtype(),
# this is a mix of integer-like values (2 or 5) and strings like AUGSF
'generator_id': pd.StringDtype(),
'generators_number': float,
'generators_num_less_1_mw': float,
'green_pricing_revenue': float,
'grid_voltage_2_kv': float,
'grid_voltage_3_kv': float,
'grid_voltage_kv': float,
'heat_content_mmbtu_per_unit': float,
'highest_distribution_voltage_kv': float,
'home_area_network': pd.Int64Dtype(),
'inactive_accounts_included': pd.BooleanDtype(),
'incremental_energy_savings_mwh': float,
'incremental_life_cycle_energy_savings_mwh': float,
'incremental_life_cycle_peak_reduction_mwh': float,
'incremental_peak_reduction_mw': float,
'iso_rto_code': pd.StringDtype(),
'latitude': float,
'liquefied_natural_gas_storage': pd.BooleanDtype(),
'load_management_annual_cost': float,
'load_management_annual_actual_peak_reduction_mw': float,
'load_management_annual_effects_mwh': float,
'load_management_annual_incentive_payment': float,
'load_management_annual_potential_peak_reduction_mw': float,
'load_management_incremental_actual_peak_reduction_mw': float,
'load_management_incremental_effects_mwh': float,
'load_management_incremental_potential_peak_reduction_mw': float,
'longitude': float,
'major_program_changes': pd.BooleanDtype(),
'mercury_content_ppm': float,
'merge_address': pd.StringDtype(),
'merge_city': pd.StringDtype(),
'merge_company': pd.StringDtype(),
'merge_date': 'datetime64[ns]',
'merge_state': pd.StringDtype(),
'mine_id_msha': pd.Int64Dtype(),
'mine_id_pudl': pd.Int64Dtype(),
'mine_name': pd.StringDtype(),
'mine_type_code': pd.StringDtype(),
'minimum_load_mw': float,
'moisture_content_pct': float,
'momentary_interruption_definition': pd.CategoricalDtype(categories=MOMENTARY_INTERRUPTION_DEF.values()),
'multiple_fuels': pd.BooleanDtype(),
'nameplate_power_factor': float,
'natural_gas_delivery_contract_type_code': pd.StringDtype(),
'natural_gas_local_distribution_company': pd.StringDtype(),
'natural_gas_pipeline_name_1': pd.StringDtype(),
'natural_gas_pipeline_name_2': pd.StringDtype(),
'natural_gas_pipeline_name_3': pd.StringDtype(),
'natural_gas_storage': pd.BooleanDtype(),
'natural_gas_transport_code': pd.StringDtype(),
'nerc_region': pd.CategoricalDtype(categories=RECOGNIZED_NERC_REGIONS),
'nerc_regions_of_operation': pd.CategoricalDtype(categories=RECOGNIZED_NERC_REGIONS),
'net_generation_mwh': float,
'net_metering': pd.BooleanDtype(),
'net_power_exchanged_mwh': float,
'net_wheeled_power_mwh': float,
'new_parent': pd.StringDtype(),
'non_amr_ami': pd.Int64Dtype(),
'nuclear_unit_id': pd.Int64Dtype(),
'operates_generating_plant': pd.BooleanDtype(),
'operating_date': 'datetime64[ns]',
'operating_switch': pd.StringDtype(),
# TODO: double check this for early 860 years
'operational_status': pd.StringDtype(),
'operational_status_code': pd.StringDtype(),
'original_planned_operating_date': 'datetime64[ns]',
'other': float,
'other_combustion_tech': pd.BooleanDtype(),
'other_costs': float,
'other_costs_incremental_cost': float,
'other_modifications_date': 'datetime64[ns]',
'other_planned_modifications': pd.BooleanDtype(),
'outages_recorded_automatically': pd.BooleanDtype(),
'owned_by_non_utility': pd.BooleanDtype(),
'owner_city': pd.StringDtype(),
'owner_name': pd.StringDtype(),
'owner_state': pd.StringDtype(),
'owner_street_address': pd.StringDtype(),
'owner_utility_id_eia': pd.Int64Dtype(),
'owner_zip_code': pd.StringDtype(),
# we should transition these into readable codes, not a one letter thing
'ownership_code': pd.StringDtype(),
'phone_extension_1': pd.StringDtype(),
'phone_extension_2': pd.StringDtype(),
'phone_number_1': pd.StringDtype(),
'phone_number_2': pd.StringDtype(),
'pipeline_notes': pd.StringDtype(),
'planned_derate_date': 'datetime64[ns]',
'planned_energy_source_code_1': pd.StringDtype(),
'planned_modifications': pd.BooleanDtype(),
'planned_net_summer_capacity_derate_mw': float,
'planned_net_summer_capacity_uprate_mw': float,
'planned_net_winter_capacity_derate_mw': float,
'planned_net_winter_capacity_uprate_mw': float,
'planned_new_capacity_mw': float,
'planned_new_prime_mover_code': pd.StringDtype(),
'planned_repower_date': 'datetime64[ns]',
'planned_retirement_date': 'datetime64[ns]',
'planned_uprate_date': 'datetime64[ns]',
'plant_id_eia': pd.Int64Dtype(),
'plant_id_epa': pd.Int64Dtype(),
'plant_id_pudl': pd.Int64Dtype(),
'plant_name_eia': pd.StringDtype(),
'plants_reported_asset_manager': pd.BooleanDtype(),
'plants_reported_operator': pd.BooleanDtype(),
'plants_reported_other_relationship': pd.BooleanDtype(),
'plants_reported_owner': pd.BooleanDtype(),
'point_source_unit_id_epa': pd.StringDtype(),
'potential_peak_demand_savings_mw': float,
'pulverized_coal_tech': pd.BooleanDtype(),
'previously_canceled': pd.BooleanDtype(),
'price_responsive_programes': pd.BooleanDtype(),
'price_responsiveness_customers': pd.Int64Dtype(),
'primary_transportation_mode_code': pd.StringDtype(),
'primary_purpose_naics_id': pd.Int64Dtype(),
'prime_mover_code': pd.StringDtype(),
'pv_current_flow_type': pd.CategoricalDtype(categories=['AC', 'DC']),
'reactive_power_output_mvar': float,
'real_time_pricing_program': pd.BooleanDtype(),
'rec_revenue': float,
'rec_sales_mwh': float,
'regulatory_status_code': pd.StringDtype(),
'report_date': 'datetime64[ns]',
'reported_as_another_company': pd.StringDtype(),
'retail_marketing_activity': pd.BooleanDtype(),
'retail_sales': float,
'retail_sales_mwh': float,
'retirement_date': 'datetime64[ns]',
'revenue_class': pd.CategoricalDtype(categories=REVENUE_CLASSES),
'rto_iso_lmp_node_id': pd.StringDtype(),
'rto_iso_location_wholesale_reporting_id': pd.StringDtype(),
'rtos_of_operation': pd.StringDtype(),
'saidi_w_major_event_dats_minus_loss_of_service_minutes': float,
'saidi_w_major_event_days_minutes': float,
'saidi_wo_major_event_days_minutes': float,
'saifi_w_major_event_days_customers': float,
'saifi_w_major_event_days_minus_loss_of_service_customers': float,
'saifi_wo_major_event_days_customers': float,
'sales_for_resale': float,
'sales_for_resale_mwh': float,
'sales_mwh': float,
'sales_revenue': float,
'sales_to_ultimate_consumers_mwh': float,
'secondary_transportation_mode_code': pd.StringDtype(),
'sector_id': pd.Int64Dtype(),
'sector_name': pd.StringDtype(),
'service_area':
|
pd.StringDtype()
|
pandas.StringDtype
|
#!/usr/bin/env python
# coding: utf-8
# # CE-40717: Machine Learning
# ## HW8-Clustering & Reinforcement Learning
#
# <NAME> - 99210259
# ### Kmeans & GMM:
#
# At this question, we tend to implement Kmeans & GMM algorithms. For this purpose, `DO NOT EMPLOY` ready-for-use python libraries. Use this implementation for solving the following questions. Kmeans should continue till centeroids won't change. Furthermore, GMM also should continue till the difference of two consecutive likelihood logarithm would be less than 0.1. Notice that after executing the Kmeans part, the primitive centroids of GMM should be identical with ultimate Kmeans centroids.
# In[8]:
from sklearn.datasets.samples_generator import make_classification, make_moons, make_circles
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# #### Part 1:
#
# Utilize the subsequent cell in order to create the Dataset. Afterwards, try to execute the algorithm with k=2 centroids. At Kmeans, it is recommended to execute the algorithm with several various starting states in order to eventually choose the best respective result.
# In[9]:
X,Y = make_classification(n_samples=700, n_features=10, n_informative=5,
n_redundant=0, n_clusters_per_class=2, n_classes=3)
# ## KMeans Implementation
# In[10]:
class KMeans:
def __init__(self, n_clusters = 3, tolerance = 0.01, max_iter = 100, runs = 1):
self.n_clusters = n_clusters
self.tolerance = tolerance
self.cluster_means = np.zeros(n_clusters)
self.max_iter = max_iter
self.runs = runs
def fit(self, X,Y):
row_count, col_count = X.shape
X_values = self.__get_values(X)
X_labels = np.zeros(row_count)
costs = np.zeros(self.runs)
all_clusterings = []
for i in range(self.runs):
cluster_means = self.__initialize_means(X_values, row_count)
for _ in range(self.max_iter):
previous_means = np.copy(cluster_means)
distances = self.__compute_distances(X_values, cluster_means, row_count)
X_labels = self.__label_examples(distances)
cluster_means = self.__compute_means(X_values, X_labels, col_count)
clusters_not_changed = np.abs(cluster_means - previous_means) < self.tolerance
if np.all(clusters_not_changed) != False:
break
X_values_with_labels = np.append(X_values, X_labels[:, np.newaxis], axis = 1)
all_clusterings.append( (cluster_means, X_values_with_labels) )
costs[i] = self.__compute_cost(X_values, X_labels, cluster_means)
best_clustering_index = costs.argmin()
self.costs = costs
self.cost_ = costs[best_clustering_index]
self.centroid,self.items = all_clusterings[best_clustering_index]
self.y = Y
return all_clusterings[best_clustering_index]
def __initialize_means(self, X, row_count):
return X [ np.random.choice(row_count, size=self.n_clusters, replace=False) ]
def __compute_distances(self, X, cluster_means, row_count):
distances = np.zeros((row_count, self.n_clusters))
for cluster_mean_index, cluster_mean in enumerate(cluster_means):
distances[:, cluster_mean_index] = np.linalg.norm(X - cluster_mean, axis = 1)
return distances
def __label_examples(self, distances):
return distances.argmin(axis = 1)
def __compute_means(self, X, labels, col_count):
cluster_means = np.zeros((self.n_clusters, col_count))
for cluster_mean_index, _ in enumerate(cluster_means):
cluster_elements = X [ labels == cluster_mean_index ]
if len(cluster_elements):
cluster_means[cluster_mean_index, :] = cluster_elements.mean(axis = 0)
return cluster_means
def __compute_cost(self, X, labels, cluster_means):
cost = 0
for cluster_mean_index, cluster_mean in enumerate(cluster_means):
cluster_elements = X [ labels == cluster_mean_index ]
cost += np.linalg.norm(cluster_elements - cluster_mean, axis = 1).sum()
return cost
def __get_values(self, X):
if isinstance(X, np.ndarray):
return X
return np.array(X)
def predict(self):
data=pd.DataFrame(self.items)
added_column=list(data.columns)[-1]
data['Label'] = self.y
resultOfClustering=data.groupby([added_column])['Label'].agg(lambda x: x.value_counts().index[0])
mapping = dict()
for label in range(self.n_clusters):
label_predicted = resultOfClustering[label]
mapping[label] = label_predicted
data['PredictedLabels']=data[added_column].map(mapping)
return np.array(data['PredictedLabels'])
# In[11]:
kmeans=KMeans(2,max_iter=10000,runs=20)
centroids,kmeans_items=kmeans.fit(X,Y)
plt.plot(np.arange(len(kmeans.costs)),kmeans.costs)
plt.title('error of different runs')
plt.xticks(np.arange(len(kmeans.costs)))
plt.show();
# In[ ]:
# ## Gaussian Mixture Model Implementation
# In[12]:
import numpy as np
import scipy.stats as sp
class GaussianMixModel():
def __init__(self, X, k=2):
X = np.asarray(X)
self.m, self.n = X.shape
self.data = X.copy()
self.k = k
self.sigma_arr = np.array([np.asmatrix(np.identity(self.n)) for i in range(self.k)])
self.phi = np.ones(self.k)/self.k
self.Z = np.asmatrix(np.empty((self.m, self.k), dtype=float))
def initialize_means(self,means):
self.mean_arr = means
def fit(self, tol=0.1):
num_iters = 0
logl = 1
previous_logl = 0
while(logl-previous_logl > tol):
previous_logl = self.loglikelihood()
self.e_step()
self.m_step()
num_iters += 1
logl = self.loglikelihood()
print('Iteration %d: log-likelihood is %.6f'%(num_iters, logl))
print('Terminate at %d-th iteration:log-likelihood is %.6f'%(num_iters, logl))
def loglikelihood(self):
logl = 0
for i in range(self.m):
tmp = 0
for j in range(self.k):
tmp += sp.multivariate_normal.pdf(self.data[i, :],self.mean_arr[j, :].A1,self.sigma_arr[j, :]) * self.phi[j]
logl += np.log(tmp)
return logl
def e_step(self):
for i in range(self.m):
den = 0
for j in range(self.k):
num = sp.multivariate_normal.pdf(self.data[i, :],
self.mean_arr[j].A1,
self.sigma_arr[j]) *\
self.phi[j]
den += num
self.Z[i, j] = num
self.Z[i, :] /= den
assert self.Z[i, :].sum() - 1 < 1e-4 # Program stop if this condition is false
def m_step(self):
for j in range(self.k):
const = self.Z[:, j].sum()
self.phi[j] = 1/self.m * const
_mu_j = np.zeros(self.n)
_sigma_j = np.zeros((self.n, self.n))
for i in range(self.m):
_mu_j += (self.data[i, :] * self.Z[i, j])
_sigma_j += self.Z[i, j] * ((self.data[i, :] - self.mean_arr[j, :]).T * (self.data[i, :] - self.mean_arr[j, :]))
self.mean_arr[j] = _mu_j / const
self.sigma_arr[j] = _sigma_j / const
def predict(self):
return np.array(np.argmax(gmm.Z,axis=1)).flatten()
# In[13]:
gmm=GaussianMixModel(X,k=2)
gmm.initialize_means(np.asmatrix(centroids))
gmm.fit()
# #### Part 2:
#
# In a separated cell, implement `Purity` and `Rand-Index` criteria in order to compare the performance of mentioned algorithms.
# ## KMeans
# In[ ]:
print('Purity Of kmeans: ',np.sum(kmeans.predict()==Y)/len(Y))
# In[447]:
from scipy.special import comb
def rand_index_score(clusters, classes):
A = np.c_[(clusters, classes)]
tp = sum(comb(np.bincount(A[A[:, 0] == i, 1]), 2).sum()
for i in set(clusters))
fp = comb(np.bincount(clusters), 2).sum() - tp
fn = comb(np.bincount(classes), 2).sum() - tp
tn = comb(len(A), 2) - tp - fp - fn
return (tp + tn) / (tp + fp + fn + tn)
# In[448]:
print('rand index of kmeans', rand_index_score(kmeans.predict(),Y))
# ## Gaussian Mixture Model
# In[449]:
print('purity index: ', np.sum(gmm.predict() == Y)/len(Y))
# In[450]:
print('rand index', rand_index_score(gmm.predict(),Y))
# #### Part 3:
#
# Use the following cell in order to create new Datasets. Afterwards, try to execute mentioned algorithms on new Dataset and eventually compare the recent results with the help of visualization(there is no problem for using relevant python libraries like `matplotlib`). Consider two clusters for this part.
# In[496]:
X, Y = make_classification(n_samples=700, n_features=2, n_informative=2, n_redundant=0, n_classes=2)
# In[497]:
k=2
kmeans=KMeans(k,max_iter=10000,runs=20)
centroids,kmeans_items=kmeans.fit(X,Y)
color_s =["green","blue","navy","maroon",'orange']
for i in range(k):
plt.scatter(kmeans_items[kmeans_items[:,2]==i,0] , kmeans_items[kmeans_items[:,2]==i,1]
,s=100, label = "cluster "+str(i), color =color_s[i])
plt.scatter(centroids[:,0] , centroids[:,1] , s = 300, color = 'red')
plt.title('Our clusters')
plt.show();
# In[498]:
gmm=GaussianMixModel(X,k)
gmm.initialize_means(np.asmatrix(centroids))
gmm.fit();
gmm_result = gmm.predict()
data=pd.DataFrame(X)
data['Predicted'] = gmm_result
for i in range(k):
plt.scatter(data[data['Predicted']==i][0], data[data['Predicted']==i][1]
,s=100, label = "cluster "+str(i), color =color_s[i])
plt.scatter(np.array(gmm.mean_arr[:,0]).flatten() , np.array(gmm.mean_arr[:,1]).flatten() , s = 300, color = 'red')
plt.show();
# In[499]:
X, Y = make_moons(n_samples=700, noise=0.2)
# In[500]:
k=2
kmeans=KMeans(k,max_iter=10000,runs=20)
centroids,kmeans_items=kmeans.fit(X,Y)
color_s =["green","blue","navy","maroon",'orange']
for i in range(k):
plt.scatter(kmeans_items[kmeans_items[:,2]==i,0] , kmeans_items[kmeans_items[:,2]==i,1]
,s=100, label = "cluster "+str(i), color =color_s[i])
plt.scatter(centroids[:,0] , centroids[:,1] , s = 300, color = 'red')
plt.title('Our clusters')
plt.show();
# In[501]:
gmm=GaussianMixModel(X,k)
gmm.initialize_means(np.asmatrix(centroids))
gmm.fit();
gmm_result = gmm.predict()
data=pd.DataFrame(X)
data['Predicted'] = gmm_result
for i in range(k):
plt.scatter(data[data['Predicted']==i][0], data[data['Predicted']==i][1]
,s=100, label = "cluster "+str(i), color =color_s[i])
plt.scatter(np.array(gmm.mean_arr[:,0]).flatten() , np.array(gmm.mean_arr[:,1]).flatten() , s = 300, color = 'red')
plt.show();
# In[505]:
X, Y = make_circles(n_samples=700, noise=0.2)
# In[506]:
k=2
kmeans=KMeans(k,max_iter=10000,runs=20)
centroids,kmeans_items=kmeans.fit(X,Y)
color_s =["green","blue","navy","maroon",'orange']
for i in range(k):
plt.scatter(kmeans_items[kmeans_items[:,2]==i,0] , kmeans_items[kmeans_items[:,2]==i,1]
,s=100, label = "cluster "+str(i), color =color_s[i])
plt.scatter(centroids[:,0] , centroids[:,1] , s = 300, color = 'red')
plt.title('Our clusters')
plt.show();
# In[507]:
gmm=GaussianMixModel(X,k)
gmm.initialize_means(np.asmatrix(centroids))
gmm.fit();
gmm_result = gmm.predict()
data=
|
pd.DataFrame(X)
|
pandas.DataFrame
|
import datetime
import os
import pandas as pd
import sys
import time
import localmodule
# Define constants.
dataset_name = localmodule.get_dataset_name()
models_dir = localmodule.get_models_dir()
oldbird_model_dir = os.path.join(models_dir, "oldbird")
units = localmodule.get_units()
clip_suppressor_modes = ["no-clip-suppressor", "clip-suppressor"]
n_thresholds = 100
# Print header.
start_time = int(time.time())
print(str(datetime.datetime.now()) + " Start.")
print("Merge Tseep and Thrush predictions in " + dataset_name + ".")
print('pandas version: {:s}'.format(pd.__version__))
print("")
# Loop over units.
for unit_str in units:
unit_dir = os.path.join(oldbird_model_dir, unit_str)
# Loop over clip suppressor modes.
for clip_suppressor_str in clip_suppressor_modes:
prediction_name = "_".join(["predictions", clip_suppressor_str])
prediction_dir = os.path.join(unit_dir, prediction_name)
# Loop over thresholds.
for threshold_id in range(n_thresholds):
threshold_str = "th-" + str(threshold_id).zfill(2)
# Load Thrush prediction.
thrush_components_list = [
dataset_name,
"oldbird",
"thrush",
unit_str,
threshold_str,
"predictions"
]
if clip_suppressor_str == "clip-suppressor":
thrush_components_list.append(clip_suppressor_str)
thrush_prediction_name = "_".join(thrush_components_list)
thrush_prediction_path = os.path.join(
prediction_dir, thrush_prediction_name + ".csv")
thrush_df = pd.read_csv(thrush_prediction_path)
# Load Tseep prediction.
tseep_components_list = thrush_components_list
tseep_components_list[2] = "tseep"
tseep_prediction_name = "_".join(tseep_components_list)
tseep_prediction_path = os.path.join(
prediction_dir, tseep_prediction_name + ".csv")
tseep_df =
|
pd.read_csv(tseep_prediction_path)
|
pandas.read_csv
|
import requests
from dateutil.parser import parse
import pandas as pd
from datetime import datetime
import functools
from io import StringIO
class WTD(object):
'''
Simple class to pull data from the World Trading Data into preferred data structure.
'''
class WTDException(Exception):
pass
class WTDDecorators(object):
'''holds decorators for python-wtd'''
@classmethod
def confirm_api_key(cls,f):
'''
confirms that the given api key is at least not in ['',None]
'''
@functools.wraps(f)
def decorated_function(*args,**kwargs):
if args[0].api_key in ['',None]:
raise WTD.WTDException('No API key specified')
return f(*args,**kwargs)
return decorated_function
def __init__(self,api_key=''):
self.api_key = api_key
self.API = 'https://www.worldtradingdata.com/api/v1'
# historical
@WTDDecorators.confirm_api_key
def historical(self,ticker,output='pandas',**kwargs):
'''
get historical data for <ticker> or each stock in <ticker> with args
if output is 'pandas', returns DataFrame of output
if output is 'dict', returns a dictionary representation of the data
other parameters:
sort:
'newest', 'oldest', 'desc', 'asc'
date_from:
date_to
formatted:
'true','false' (def False)
'''
if not output in ['dict','pandas']:
raise WTD.WTDException('WTD.historical: output must be one of "pandas","dict"')
# ensure date params are correct
#params = self._process_date_params(
params = {
'symbol':ticker,
'api_token':self.api_key,
# **kwargs
}
#)
data = requests.get(self.API + '/history', params=params)
data = data.json()
data = data['history']
if output=='dict':
pass
else:
data = pd.DataFrame.from_dict(data, orient='index')
data.index =
|
pd.to_datetime(data.index)
|
pandas.to_datetime
|
from collections import abc, deque
from decimal import Decimal
from io import StringIO
from warnings import catch_warnings
import numpy as np
from numpy.random import randn
import pytest
from pandas.core.dtypes.dtypes import CategoricalDtype
import pandas as pd
from pandas import (
Categorical,
DataFrame,
DatetimeIndex,
Index,
MultiIndex,
Series,
concat,
date_range,
read_csv,
)
import pandas._testing as tm
from pandas.core.arrays import SparseArray
from pandas.core.construction import create_series_with_explicit_dtype
from pandas.tests.extension.decimal import to_decimal
@pytest.fixture(params=[True, False])
def sort(request):
"""Boolean sort keyword for concat and DataFrame.append."""
return request.param
class TestConcatenate:
def test_concat_copy(self):
df = DataFrame(np.random.randn(4, 3))
df2 = DataFrame(np.random.randint(0, 10, size=4).reshape(4, 1))
df3 = DataFrame({5: "foo"}, index=range(4))
# These are actual copies.
result = concat([df, df2, df3], axis=1, copy=True)
for b in result._mgr.blocks:
assert b.values.base is None
# These are the same.
result = concat([df, df2, df3], axis=1, copy=False)
for b in result._mgr.blocks:
if b.is_float:
assert b.values.base is df._mgr.blocks[0].values.base
elif b.is_integer:
assert b.values.base is df2._mgr.blocks[0].values.base
elif b.is_object:
assert b.values.base is not None
# Float block was consolidated.
df4 = DataFrame(np.random.randn(4, 1))
result = concat([df, df2, df3, df4], axis=1, copy=False)
for b in result._mgr.blocks:
if b.is_float:
assert b.values.base is None
elif b.is_integer:
assert b.values.base is df2._mgr.blocks[0].values.base
elif b.is_object:
assert b.values.base is not None
def test_concat_with_group_keys(self):
df = DataFrame(np.random.randn(4, 3))
df2 = DataFrame(np.random.randn(4, 4))
# axis=0
df = DataFrame(np.random.randn(3, 4))
df2 = DataFrame(np.random.randn(4, 4))
result = concat([df, df2], keys=[0, 1])
exp_index = MultiIndex.from_arrays(
[[0, 0, 0, 1, 1, 1, 1], [0, 1, 2, 0, 1, 2, 3]]
)
expected = DataFrame(np.r_[df.values, df2.values], index=exp_index)
tm.assert_frame_equal(result, expected)
result = concat([df, df], keys=[0, 1])
exp_index2 = MultiIndex.from_arrays([[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 1, 2]])
expected = DataFrame(np.r_[df.values, df.values], index=exp_index2)
tm.assert_frame_equal(result, expected)
# axis=1
df = DataFrame(np.random.randn(4, 3))
df2 = DataFrame(np.random.randn(4, 4))
result = concat([df, df2], keys=[0, 1], axis=1)
expected = DataFrame(np.c_[df.values, df2.values], columns=exp_index)
tm.assert_frame_equal(result, expected)
result = concat([df, df], keys=[0, 1], axis=1)
expected = DataFrame(np.c_[df.values, df.values], columns=exp_index2)
tm.assert_frame_equal(result, expected)
def test_concat_keys_specific_levels(self):
df = DataFrame(np.random.randn(10, 4))
pieces = [df.iloc[:, [0, 1]], df.iloc[:, [2]], df.iloc[:, [3]]]
level = ["three", "two", "one", "zero"]
result = concat(
pieces,
axis=1,
keys=["one", "two", "three"],
levels=[level],
names=["group_key"],
)
tm.assert_index_equal(result.columns.levels[0], Index(level, name="group_key"))
tm.assert_index_equal(result.columns.levels[1], Index([0, 1, 2, 3]))
assert result.columns.names == ["group_key", None]
def test_concat_dataframe_keys_bug(self, sort):
t1 = DataFrame(
{"value": Series([1, 2, 3], index=Index(["a", "b", "c"], name="id"))}
)
t2 = DataFrame({"value": Series([7, 8], index=Index(["a", "b"], name="id"))})
# it works
result = concat([t1, t2], axis=1, keys=["t1", "t2"], sort=sort)
assert list(result.columns) == [("t1", "value"), ("t2", "value")]
def test_concat_series_partial_columns_names(self):
# GH10698
foo = Series([1, 2], name="foo")
bar =
|
Series([1, 2])
|
pandas.Series
|
# pylint: disable-msg=E1101,W0612
from datetime import datetime, timedelta
import os
import operator
import unittest
import cStringIO as StringIO
import nose
from numpy import nan
import numpy as np
import numpy.ma as ma
from pandas import Index, Series, TimeSeries, DataFrame, isnull, notnull
from pandas.core.index import MultiIndex
import pandas.core.datetools as datetools
from pandas.util import py3compat
from pandas.util.testing import assert_series_equal, assert_almost_equal
import pandas.util.testing as tm
#-------------------------------------------------------------------------------
# Series test cases
JOIN_TYPES = ['inner', 'outer', 'left', 'right']
class CheckNameIntegration(object):
def test_scalarop_preserve_name(self):
result = self.ts * 2
self.assertEquals(result.name, self.ts.name)
def test_copy_name(self):
result = self.ts.copy()
self.assertEquals(result.name, self.ts.name)
# def test_copy_index_name_checking(self):
# # don't want to be able to modify the index stored elsewhere after
# # making a copy
# self.ts.index.name = None
# cp = self.ts.copy()
# cp.index.name = 'foo'
# self.assert_(self.ts.index.name is None)
def test_append_preserve_name(self):
result = self.ts[:5].append(self.ts[5:])
self.assertEquals(result.name, self.ts.name)
def test_binop_maybe_preserve_name(self):
# names match, preserve
result = self.ts * self.ts
self.assertEquals(result.name, self.ts.name)
result = self.ts * self.ts[:-2]
self.assertEquals(result.name, self.ts.name)
# names don't match, don't preserve
cp = self.ts.copy()
cp.name = 'something else'
result = self.ts + cp
self.assert_(result.name is None)
def test_combine_first_name(self):
result = self.ts.combine_first(self.ts[:5])
self.assertEquals(result.name, self.ts.name)
def test_getitem_preserve_name(self):
result = self.ts[self.ts > 0]
self.assertEquals(result.name, self.ts.name)
result = self.ts[[0, 2, 4]]
self.assertEquals(result.name, self.ts.name)
result = self.ts[5:10]
self.assertEquals(result.name, self.ts.name)
def test_multilevel_name_print(self):
index = MultiIndex(levels=[['foo', 'bar', 'baz', 'qux'],
['one', 'two', 'three']],
labels=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3],
[0, 1, 2, 0, 1, 1, 2, 0, 1, 2]],
names=['first', 'second'])
s = Series(range(0,len(index)), index=index, name='sth')
expected = ["first second",
"foo one 0",
" two 1",
" three 2",
"bar one 3",
" two 4",
"baz two 5",
" three 6",
"qux one 7",
" two 8",
" three 9",
"Name: sth"]
expected = "\n".join(expected)
self.assertEquals(repr(s), expected)
def test_multilevel_preserve_name(self):
index = MultiIndex(levels=[['foo', 'bar', 'baz', 'qux'],
['one', 'two', 'three']],
labels=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3],
[0, 1, 2, 0, 1, 1, 2, 0, 1, 2]],
names=['first', 'second'])
s = Series(np.random.randn(len(index)), index=index, name='sth')
result = s['foo']
result2 = s.ix['foo']
self.assertEquals(result.name, s.name)
self.assertEquals(result2.name, s.name)
def test_name_printing(self):
# test small series
s = Series([0, 1, 2])
s.name = "test"
self.assert_("Name: test" in repr(s))
s.name = None
self.assert_(not "Name:" in repr(s))
# test big series (diff code path)
s = Series(range(0,1000))
s.name = "test"
self.assert_("Name: test" in repr(s))
s.name = None
self.assert_(not "Name:" in repr(s))
def test_pickle_preserve_name(self):
unpickled = self._pickle_roundtrip(self.ts)
self.assertEquals(unpickled.name, self.ts.name)
def _pickle_roundtrip(self, obj):
obj.save('__tmp__')
unpickled = Series.load('__tmp__')
os.remove('__tmp__')
return unpickled
def test_argsort_preserve_name(self):
result = self.ts.argsort()
self.assertEquals(result.name, self.ts.name)
def test_sort_index_name(self):
result = self.ts.sort_index(ascending=False)
self.assertEquals(result.name, self.ts.name)
def test_to_sparse_pass_name(self):
result = self.ts.to_sparse()
self.assertEquals(result.name, self.ts.name)
class SafeForSparse(object):
pass
class TestSeries(unittest.TestCase, CheckNameIntegration):
def setUp(self):
self.ts = tm.makeTimeSeries()
self.ts.name = 'ts'
self.series = tm.makeStringSeries()
self.series.name = 'series'
self.objSeries = tm.makeObjectSeries()
self.objSeries.name = 'objects'
self.empty = Series([], index=[])
def test_constructor(self):
# Recognize TimeSeries
self.assert_(isinstance(self.ts, TimeSeries))
# Pass in Series
derived = Series(self.ts)
self.assert_(isinstance(derived, TimeSeries))
self.assert_(tm.equalContents(derived.index, self.ts.index))
# Ensure new index is not created
self.assertEquals(id(self.ts.index), id(derived.index))
# Pass in scalar
scalar = Series(0.5)
self.assert_(isinstance(scalar, float))
# Mixed type Series
mixed = Series(['hello', np.NaN], index=[0, 1])
self.assert_(mixed.dtype == np.object_)
self.assert_(mixed[1] is np.NaN)
self.assert_(not isinstance(self.empty, TimeSeries))
self.assert_(not isinstance(Series({}), TimeSeries))
self.assertRaises(Exception, Series, np.random.randn(3, 3),
index=np.arange(3))
def test_constructor_empty(self):
empty = Series()
empty2 = Series([])
assert_series_equal(empty, empty2)
empty = Series(index=range(10))
empty2 = Series(np.nan, index=range(10))
assert_series_equal(empty, empty2)
def test_constructor_maskedarray(self):
data = ma.masked_all((3,), dtype=float)
result = Series(data)
expected = Series([nan, nan, nan])
assert_series_equal(result, expected)
data[0] = 0.0
data[2] = 2.0
index = ['a', 'b', 'c']
result = Series(data, index=index)
expected = Series([0.0, nan, 2.0], index=index)
assert_series_equal(result, expected)
def test_constructor_default_index(self):
s = Series([0, 1, 2])
assert_almost_equal(s.index, np.arange(3))
def test_constructor_corner(self):
df = tm.makeTimeDataFrame()
objs = [df, df]
s = Series(objs, index=[0, 1])
self.assert_(isinstance(s, Series))
def test_constructor_cast(self):
self.assertRaises(ValueError, Series, ['a', 'b', 'c'], dtype=float)
def test_constructor_dict(self):
d = {'a' : 0., 'b' : 1., 'c' : 2.}
result = Series(d, index=['b', 'c', 'd', 'a'])
expected = Series([1, 2, nan, 0], index=['b', 'c', 'd', 'a'])
assert_series_equal(result, expected)
def test_constructor_list_of_tuples(self):
data = [(1, 1), (2, 2), (2, 3)]
s = Series(data)
self.assertEqual(list(s), data)
def test_constructor_tuple_of_tuples(self):
data = ((1, 1), (2, 2), (2, 3))
s = Series(data)
self.assertEqual(tuple(s), data)
def test_fromDict(self):
data = {'a' : 0, 'b' : 1, 'c' : 2, 'd' : 3}
series = Series(data)
self.assert_(tm.is_sorted(series.index))
data = {'a' : 0, 'b' : '1', 'c' : '2', 'd' : datetime.now()}
series = Series(data)
self.assert_(series.dtype == np.object_)
data = {'a' : 0, 'b' : '1', 'c' : '2', 'd' : '3'}
series = Series(data)
self.assert_(series.dtype == np.object_)
data = {'a' : '0', 'b' : '1'}
series = Series(data, dtype=float)
self.assert_(series.dtype == np.float64)
def test_setindex(self):
# wrong type
series = self.series.copy()
self.assertRaises(TypeError, setattr, series, 'index', None)
# wrong length
series = self.series.copy()
self.assertRaises(AssertionError, setattr, series, 'index',
np.arange(len(series) - 1))
# works
series = self.series.copy()
series.index = np.arange(len(series))
self.assert_(isinstance(series.index, Index))
def test_array_finalize(self):
pass
def test_fromValue(self):
nans = Series(np.NaN, index=self.ts.index)
self.assert_(nans.dtype == np.float_)
self.assertEqual(len(nans), len(self.ts))
strings = Series('foo', index=self.ts.index)
self.assert_(strings.dtype == np.object_)
self.assertEqual(len(strings), len(self.ts))
d = datetime.now()
dates = Series(d, index=self.ts.index)
self.assert_(dates.dtype == np.object_)
self.assertEqual(len(dates), len(self.ts))
def test_contains(self):
tm.assert_contains_all(self.ts.index, self.ts)
def test_pickle(self):
unp_series = self._pickle_roundtrip(self.series)
unp_ts = self._pickle_roundtrip(self.ts)
assert_series_equal(unp_series, self.series)
assert_series_equal(unp_ts, self.ts)
def _pickle_roundtrip(self, obj):
obj.save('__tmp__')
unpickled = Series.load('__tmp__')
os.remove('__tmp__')
return unpickled
def test_getitem_get(self):
idx1 = self.series.index[5]
idx2 = self.objSeries.index[5]
self.assertEqual(self.series[idx1], self.series.get(idx1))
self.assertEqual(self.objSeries[idx2], self.objSeries.get(idx2))
self.assertEqual(self.series[idx1], self.series[5])
self.assertEqual(self.objSeries[idx2], self.objSeries[5])
self.assert_(self.series.get(-1) is None)
self.assertEqual(self.series[5], self.series.get(self.series.index[5]))
# missing
d = self.ts.index[0] - datetools.bday
self.assertRaises(KeyError, self.ts.__getitem__, d)
def test_iget(self):
s = Series(np.random.randn(10), index=range(0, 20, 2))
for i in range(len(s)):
result = s.iget(i)
exp = s[s.index[i]]
assert_almost_equal(result, exp)
# pass a slice
result = s.iget(slice(1, 3))
expected = s.ix[2:4]
assert_series_equal(result, expected)
def test_getitem_regression(self):
s = Series(range(5), index=range(5))
result = s[range(5)]
assert_series_equal(result, s)
def test_getitem_slice_bug(self):
s = Series(range(10), range(10))
result = s[-12:]
assert_series_equal(result, s)
result = s[-7:]
assert_series_equal(result, s[3:])
result = s[:-12]
assert_series_equal(result, s[:0])
def test_getitem_int64(self):
idx = np.int64(5)
self.assertEqual(self.ts[idx], self.ts[5])
def test_getitem_fancy(self):
slice1 = self.series[[1,2,3]]
slice2 = self.objSeries[[1,2,3]]
self.assertEqual(self.series.index[2], slice1.index[1])
self.assertEqual(self.objSeries.index[2], slice2.index[1])
self.assertEqual(self.series[2], slice1[1])
self.assertEqual(self.objSeries[2], slice2[1])
def test_getitem_boolean(self):
s = self.series
mask = s > s.median()
# passing list is OK
result = s[list(mask)]
expected = s[mask]
assert_series_equal(result, expected)
self.assert_(np.array_equal(result.index, s.index[mask]))
def test_getitem_generator(self):
gen = (x > 0 for x in self.series)
result = self.series[gen]
result2 = self.series[iter(self.series > 0)]
expected = self.series[self.series > 0]
assert_series_equal(result, expected)
assert_series_equal(result2, expected)
def test_getitem_boolean_object(self):
# using column from DataFrame
s = self.series
mask = s > s.median()
omask = mask.astype(object)
# getitem
result = s[omask]
expected = s[mask]
assert_series_equal(result, expected)
# setitem
cop = s.copy()
cop[omask] = 5
s[mask] = 5
assert_series_equal(cop, s)
# nans raise exception
omask[5:10] = np.nan
self.assertRaises(Exception, s.__getitem__, omask)
self.assertRaises(Exception, s.__setitem__, omask, 5)
def test_getitem_setitem_boolean_corner(self):
ts = self.ts
mask_shifted = ts.shift(1, offset=datetools.bday) > ts.median()
self.assertRaises(Exception, ts.__getitem__, mask_shifted)
self.assertRaises(Exception, ts.__setitem__, mask_shifted, 1)
self.assertRaises(Exception, ts.ix.__getitem__, mask_shifted)
self.assertRaises(Exception, ts.ix.__setitem__, mask_shifted, 1)
def test_getitem_setitem_slice_integers(self):
s = Series(np.random.randn(8), index=[2, 4, 6, 8, 10, 12, 14, 16])
result = s[:4]
expected = s.reindex([2, 4, 6, 8])
assert_series_equal(result, expected)
s[:4] = 0
self.assert_((s[:4] == 0).all())
self.assert_(not (s[4:] == 0).any())
def test_getitem_out_of_bounds(self):
# don't segfault, GH #495
self.assertRaises(IndexError, self.ts.__getitem__, len(self.ts))
def test_getitem_box_float64(self):
value = self.ts[5]
self.assert_(isinstance(value, np.float64))
def test_getitem_ambiguous_keyerror(self):
s = Series(range(10), index=range(0, 20, 2))
self.assertRaises(KeyError, s.__getitem__, 1)
self.assertRaises(KeyError, s.ix.__getitem__, 1)
def test_setitem_ambiguous_keyerror(self):
s = Series(range(10), index=range(0, 20, 2))
self.assertRaises(KeyError, s.__setitem__, 1, 5)
self.assertRaises(KeyError, s.ix.__setitem__, 1, 5)
def test_slice(self):
numSlice = self.series[10:20]
numSliceEnd = self.series[-10:]
objSlice = self.objSeries[10:20]
self.assert_(self.series.index[9] not in numSlice.index)
self.assert_(self.objSeries.index[9] not in objSlice.index)
self.assertEqual(len(numSlice), len(numSlice.index))
self.assertEqual(self.series[numSlice.index[0]],
numSlice[numSlice.index[0]])
self.assertEqual(numSlice.index[1], self.series.index[11])
self.assert_(tm.equalContents(numSliceEnd,
np.array(self.series)[-10:]))
# test return view
sl = self.series[10:20]
sl[:] = 0
self.assert_((self.series[10:20] == 0).all())
def test_slice_can_reorder_not_uniquely_indexed(self):
s = Series(1, index=['a', 'a', 'b', 'b', 'c'])
result = s[::-1] # it works!
def test_setitem(self):
self.ts[self.ts.index[5]] = np.NaN
self.ts[[1,2,17]] = np.NaN
self.ts[6] = np.NaN
self.assert_(np.isnan(self.ts[6]))
self.assert_(np.isnan(self.ts[2]))
self.ts[np.isnan(self.ts)] = 5
self.assert_(not np.isnan(self.ts[2]))
# caught this bug when writing tests
series = Series(tm.makeIntIndex(20).astype(float),
index=tm.makeIntIndex(20))
series[::2] = 0
self.assert_((series[::2] == 0).all())
# set item that's not contained
self.assertRaises(Exception, self.series.__setitem__,
'foobar', 1)
def test_set_value(self):
idx = self.ts.index[10]
res = self.ts.set_value(idx, 0)
self.assert_(res is self.ts)
self.assertEqual(self.ts[idx], 0)
res = self.series.set_value('foobar', 0)
self.assert_(res is not self.series)
self.assert_(res.index[-1] == 'foobar')
self.assertEqual(res['foobar'], 0)
def test_setslice(self):
sl = self.ts[5:20]
self.assertEqual(len(sl), len(sl.index))
self.assertEqual(len(sl.index.indexMap), len(sl.index))
def test_basic_getitem_setitem_corner(self):
# invalid tuples, e.g. self.ts[:, None] vs. self.ts[:, 2]
self.assertRaises(Exception, self.ts.__getitem__,
(slice(None, None), 2))
self.assertRaises(Exception, self.ts.__setitem__,
(slice(None, None), 2), 2)
# weird lists. [slice(0, 5)] will work but not two slices
result = self.ts[[slice(None, 5)]]
expected = self.ts[:5]
assert_series_equal(result, expected)
# OK
self.assertRaises(Exception, self.ts.__getitem__,
[5, slice(None, None)])
self.assertRaises(Exception, self.ts.__setitem__,
[5, slice(None, None)], 2)
def test_basic_getitem_with_labels(self):
indices = self.ts.index[[5, 10, 15]]
result = self.ts[indices]
expected = self.ts.reindex(indices)
assert_series_equal(result, expected)
result = self.ts[indices[0]:indices[2]]
expected = self.ts.ix[indices[0]:indices[2]]
assert_series_equal(result, expected)
# integer indexes, be careful
s = Series(np.random.randn(10), index=range(0, 20, 2))
inds = [0, 2, 5, 7, 8]
arr_inds = np.array([0, 2, 5, 7, 8])
result = s[inds]
expected = s.reindex(inds)
assert_series_equal(result, expected)
result = s[arr_inds]
expected = s.reindex(arr_inds)
assert_series_equal(result, expected)
def test_basic_setitem_with_labels(self):
indices = self.ts.index[[5, 10, 15]]
cp = self.ts.copy()
exp = self.ts.copy()
cp[indices] = 0
exp.ix[indices] = 0
assert_series_equal(cp, exp)
cp = self.ts.copy()
exp = self.ts.copy()
cp[indices[0]:indices[2]] = 0
exp.ix[indices[0]:indices[2]] = 0
assert_series_equal(cp, exp)
# integer indexes, be careful
s = Series(np.random.randn(10), index=range(0, 20, 2))
inds = [0, 4, 6]
arr_inds = np.array([0, 4, 6])
cp = s.copy()
exp = s.copy()
s[inds] = 0
s.ix[inds] = 0
assert_series_equal(cp, exp)
cp = s.copy()
exp = s.copy()
s[arr_inds] = 0
s.ix[arr_inds] = 0
assert_series_equal(cp, exp)
inds_notfound = [0, 4, 5, 6]
arr_inds_notfound = np.array([0, 4, 5, 6])
self.assertRaises(Exception, s.__setitem__, inds_notfound, 0)
self.assertRaises(Exception, s.__setitem__, arr_inds_notfound, 0)
def test_ix_getitem(self):
inds = self.series.index[[3,4,7]]
assert_series_equal(self.series.ix[inds], self.series.reindex(inds))
assert_series_equal(self.series.ix[5::2], self.series[5::2])
# slice with indices
d1, d2 = self.ts.index[[5, 15]]
result = self.ts.ix[d1:d2]
expected = self.ts.truncate(d1, d2)
assert_series_equal(result, expected)
# boolean
mask = self.series > self.series.median()
assert_series_equal(self.series.ix[mask], self.series[mask])
# ask for index value
self.assertEquals(self.ts.ix[d1], self.ts[d1])
self.assertEquals(self.ts.ix[d2], self.ts[d2])
def test_ix_getitem_not_monotonic(self):
d1, d2 = self.ts.index[[5, 15]]
ts2 = self.ts[::2][::-1]
self.assertRaises(KeyError, ts2.ix.__getitem__, slice(d1, d2))
self.assertRaises(KeyError, ts2.ix.__setitem__, slice(d1, d2), 0)
def test_ix_getitem_setitem_integer_slice_keyerrors(self):
s = Series(np.random.randn(10), index=range(0, 20, 2))
# this is OK
cp = s.copy()
cp.ix[4:10] = 0
self.assert_((cp.ix[4:10] == 0).all())
# so is this
cp = s.copy()
cp.ix[3:11] = 0
self.assert_((cp.ix[3:11] == 0).values.all())
result = s.ix[4:10]
result2 = s.ix[3:11]
expected = s.reindex([4, 6, 8, 10])
assert_series_equal(result, expected)
assert_series_equal(result2, expected)
# non-monotonic, raise KeyError
s2 = s[::-1]
self.assertRaises(KeyError, s2.ix.__getitem__, slice(3, 11))
self.assertRaises(KeyError, s2.ix.__setitem__, slice(3, 11), 0)
def test_ix_getitem_iterator(self):
idx = iter(self.series.index[:10])
result = self.series.ix[idx]
assert_series_equal(result, self.series[:10])
def test_ix_setitem(self):
inds = self.series.index[[3,4,7]]
result = self.series.copy()
result.ix[inds] = 5
expected = self.series.copy()
expected[[3,4,7]] = 5
assert_series_equal(result, expected)
result.ix[5:10] = 10
expected[5:10] = 10
assert_series_equal(result, expected)
# set slice with indices
d1, d2 = self.series.index[[5, 15]]
result.ix[d1:d2] = 6
expected[5:16] = 6 # because it's inclusive
assert_series_equal(result, expected)
# set index value
self.series.ix[d1] = 4
self.series.ix[d2] = 6
self.assertEquals(self.series[d1], 4)
self.assertEquals(self.series[d2], 6)
def test_ix_setitem_boolean(self):
mask = self.series > self.series.median()
result = self.series.copy()
result.ix[mask] = 0
expected = self.series
expected[mask] = 0
assert_series_equal(result, expected)
def test_ix_setitem_corner(self):
inds = list(self.series.index[[5, 8, 12]])
self.series.ix[inds] = 5
self.assertRaises(Exception, self.series.ix.__setitem__,
inds + ['foo'], 5)
def test_get_set_boolean_different_order(self):
ordered = self.series.order()
# setting
copy = self.series.copy()
copy[ordered > 0] = 0
expected = self.series.copy()
expected[expected > 0] = 0
assert_series_equal(copy, expected)
# getting
sel = self.series[ordered > 0]
exp = self.series[self.series > 0]
assert_series_equal(sel, exp)
def test_repr(self):
str(self.ts)
str(self.series)
str(self.series.astype(int))
str(self.objSeries)
str(Series(tm.randn(1000), index=np.arange(1000)))
str(Series(tm.randn(1000), index=np.arange(1000, 0, step=-1)))
# empty
str(self.empty)
# with NaNs
self.series[5:7] = np.NaN
str(self.series)
# tuple name, e.g. from hierarchical index
self.series.name = ('foo', 'bar', 'baz')
repr(self.series)
biggie = Series(tm.randn(1000), index=np.arange(1000),
name=('foo', 'bar', 'baz'))
repr(biggie)
def test_to_string(self):
from cStringIO import StringIO
buf = StringIO()
s = self.ts.to_string()
retval = self.ts.to_string(buf=buf)
self.assert_(retval is None)
self.assertEqual(buf.getvalue().strip(), s)
# pass float_format
format = '%.4f'.__mod__
result = self.ts.to_string(float_format=format)
result = [x.split()[1] for x in result.split('\n')]
expected = [format(x) for x in self.ts]
self.assertEqual(result, expected)
# empty string
result = self.ts[:0].to_string()
self.assertEqual(result, '')
result = self.ts[:0].to_string(length=0)
self.assertEqual(result, '')
# name and length
cp = self.ts.copy()
cp.name = 'foo'
result = cp.to_string(length=True, name=True)
last_line = result.split('\n')[-1].strip()
self.assertEqual(last_line, "Name: foo, Length: %d" % len(cp))
def test_to_string_mixed(self):
s = Series(['foo', np.nan, -1.23, 4.56])
result = s.to_string()
expected = ('0 foo\n'
'1 NaN\n'
'2 -1.23\n'
'3 4.56')
self.assertEqual(result, expected)
# but don't count NAs as floats
s = Series(['foo', np.nan, 'bar', 'baz'])
result = s.to_string()
expected = ('0 foo\n'
'1 NaN\n'
'2 bar\n'
'3 baz')
self.assertEqual(result, expected)
s = Series(['foo', 5, 'bar', 'baz'])
result = s.to_string()
expected = ('0 foo\n'
'1 5\n'
'2 bar\n'
'3 baz')
self.assertEqual(result, expected)
def test_to_string_float_na_spacing(self):
s = Series([0., 1.5678, 2., -3., 4.])
s[::2] = np.nan
result = s.to_string()
expected = ('0 NaN\n'
'1 1.568\n'
'2 NaN\n'
'3 -3.000\n'
'4 NaN')
self.assertEqual(result, expected)
def test_iter(self):
for i, val in enumerate(self.series):
self.assertEqual(val, self.series[i])
for i, val in enumerate(self.ts):
self.assertEqual(val, self.ts[i])
def test_keys(self):
# HACK: By doing this in two stages, we avoid 2to3 wrapping the call
# to .keys() in a list()
getkeys = self.ts.keys
self.assert_(getkeys() is self.ts.index)
def test_values(self):
self.assert_(np.array_equal(self.ts, self.ts.values))
def test_iteritems(self):
for idx, val in self.series.iteritems():
self.assertEqual(val, self.series[idx])
for idx, val in self.ts.iteritems():
self.assertEqual(val, self.ts[idx])
def test_sum(self):
self._check_stat_op('sum', np.sum)
def test_sum_inf(self):
s = Series(np.random.randn(10))
s2 = s.copy()
s[5:8] = np.inf
s2[5:8] = np.nan
assert_almost_equal(s.sum(), s2.sum())
import pandas.core.nanops as nanops
arr = np.random.randn(100, 100).astype('f4')
arr[:, 2] = np.inf
res = nanops.nansum(arr, axis=1)
expected = nanops._nansum(arr, axis=1)
assert_almost_equal(res, expected)
def test_mean(self):
self._check_stat_op('mean', np.mean)
def test_median(self):
self._check_stat_op('median', np.median)
# test with integers, test failure
int_ts = TimeSeries(np.ones(10, dtype=int), index=range(10))
self.assertAlmostEqual(np.median(int_ts), int_ts.median())
def test_prod(self):
self._check_stat_op('prod', np.prod)
def test_min(self):
self._check_stat_op('min', np.min, check_objects=True)
def test_max(self):
self._check_stat_op('max', np.max, check_objects=True)
def test_std(self):
alt = lambda x: np.std(x, ddof=1)
self._check_stat_op('std', alt)
def test_var(self):
alt = lambda x: np.var(x, ddof=1)
self._check_stat_op('var', alt)
def test_skew(self):
from scipy.stats import skew
alt =lambda x: skew(x, bias=False)
self._check_stat_op('skew', alt)
def test_argsort(self):
self._check_accum_op('argsort')
argsorted = self.ts.argsort()
self.assert_(issubclass(argsorted.dtype.type, np.integer))
def test_cumsum(self):
self._check_accum_op('cumsum')
def test_cumprod(self):
self._check_accum_op('cumprod')
def _check_stat_op(self, name, alternate, check_objects=False):
from pandas import DateRange
import pandas.core.nanops as nanops
def testit():
f = getattr(Series, name)
# add some NaNs
self.series[5:15] = np.NaN
# skipna or no
self.assert_(notnull(f(self.series)))
self.assert_(isnull(f(self.series, skipna=False)))
# check the result is correct
nona = self.series.dropna()
assert_almost_equal(f(nona), alternate(nona))
allna = self.series * nan
self.assert_(np.isnan(f(allna)))
# dtype=object with None, it works!
s = Series([1, 2, 3, None, 5])
f(s)
# check DateRange
if check_objects:
s = Series(DateRange('1/1/2000', periods=10))
res = f(s)
exp = alternate(s)
self.assertEqual(res, exp)
testit()
try:
import bottleneck as bn
nanops._USE_BOTTLENECK = False
testit()
nanops._USE_BOTTLENECK = True
except ImportError:
pass
def _check_accum_op(self, name):
func = getattr(np, name)
self.assert_(np.array_equal(func(self.ts), func(np.array(self.ts))))
# with missing values
ts = self.ts.copy()
ts[::2] = np.NaN
result = func(ts)[1::2]
expected = func(np.array(ts.valid()))
self.assert_(np.array_equal(result, expected))
def test_round(self):
# numpy.round doesn't preserve metadata, probably a numpy bug,
# re: GH #314
result = np.round(self.ts, 2)
expected = Series(np.round(self.ts.values, 2), index=self.ts.index)
assert_series_equal(result, expected)
self.assertEqual(result.name, self.ts.name)
def test_prod_numpy16_bug(self):
s = Series([1., 1., 1.] , index=range(3))
result = s.prod()
self.assert_(not isinstance(result, Series))
def test_quantile(self):
from scipy.stats import scoreatpercentile
q = self.ts.quantile(0.1)
self.assertEqual(q, scoreatpercentile(self.ts.valid(), 10))
q = self.ts.quantile(0.9)
self.assertEqual(q, scoreatpercentile(self.ts.valid(), 90))
def test_describe(self):
_ = self.series.describe()
_ = self.ts.describe()
def test_describe_objects(self):
s = Series(['a', 'b', 'b', np.nan, np.nan, np.nan, 'c', 'd', 'a', 'a'])
result = s.describe()
expected = Series({'count' : 7, 'unique' : 4,
'top' : 'a', 'freq' : 3}, index=result.index)
assert_series_equal(result, expected)
def test_append(self):
appendedSeries = self.series.append(self.ts)
for idx, value in appendedSeries.iteritems():
if idx in self.series.index:
self.assertEqual(value, self.series[idx])
elif idx in self.ts.index:
self.assertEqual(value, self.ts[idx])
else:
self.fail("orphaned index!")
self.assertRaises(Exception, self.ts.append, self.ts)
def test_append_many(self):
pieces = [self.ts[:5], self.ts[5:10], self.ts[10:]]
result = pieces[0].append(pieces[1:])
assert_series_equal(result, self.ts)
def test_all_any(self):
np.random.seed(12345)
ts = tm.makeTimeSeries()
bool_series = ts > 0
self.assert_(not bool_series.all())
self.assert_(bool_series.any())
def test_operators(self):
series = self.ts
other = self.ts[::2]
def _check_op(other, op, pos_only=False):
left = np.abs(series) if pos_only else series
right = np.abs(other) if pos_only else other
cython_or_numpy = op(left, right)
python = left.combine(right, op)
tm.assert_almost_equal(cython_or_numpy, python)
def check(other):
simple_ops = ['add', 'sub', 'mul', 'truediv', 'floordiv',
'gt', 'ge', 'lt', 'le']
for opname in simple_ops:
_check_op(other, getattr(operator, opname))
_check_op(other, operator.pow, pos_only=True)
_check_op(other, lambda x, y: operator.add(y, x))
_check_op(other, lambda x, y: operator.sub(y, x))
_check_op(other, lambda x, y: operator.truediv(y, x))
_check_op(other, lambda x, y: operator.floordiv(y, x))
_check_op(other, lambda x, y: operator.mul(y, x))
_check_op(other, lambda x, y: operator.pow(y, x),
pos_only=True)
check(self.ts * 2)
check(self.ts * 0)
check(self.ts[::2])
check(5)
def check_comparators(other):
_check_op(other, operator.gt)
_check_op(other, operator.ge)
_check_op(other, operator.eq)
_check_op(other, operator.lt)
_check_op(other, operator.le)
check_comparators(5)
check_comparators(self.ts + 1)
def test_operators_empty_int_corner(self):
s1 = Series([], [], dtype=np.int32)
s2 = Series({'x' : 0.})
# it works!
_ = s1 * s2
# NumPy limitiation =(
# def test_logical_range_select(self):
# np.random.seed(12345)
# selector = -0.5 <= self.ts <= 0.5
# expected = (self.ts >= -0.5) & (self.ts <= 0.5)
# assert_series_equal(selector, expected)
def test_idxmin(self):
# test idxmin
# _check_stat_op approach can not be used here because of isnull check.
# add some NaNs
self.series[5:15] = np.NaN
# skipna or no
self.assertEqual(self.series[self.series.idxmin()], self.series.min())
self.assert_(isnull(self.series.idxmin(skipna=False)))
# no NaNs
nona = self.series.dropna()
self.assertEqual(nona[nona.idxmin()], nona.min())
self.assertEqual(nona.index.values.tolist().index(nona.idxmin()),
nona.values.argmin())
# all NaNs
allna = self.series * nan
self.assert_(isnull(allna.idxmin()))
def test_idxmax(self):
# test idxmax
# _check_stat_op approach can not be used here because of isnull check.
# add some NaNs
self.series[5:15] = np.NaN
# skipna or no
self.assertEqual(self.series[self.series.idxmax()], self.series.max())
self.assert_(isnull(self.series.idxmax(skipna=False)))
# no NaNs
nona = self.series.dropna()
self.assertEqual(nona[nona.idxmax()], nona.max())
self.assertEqual(nona.index.values.tolist().index(nona.idxmax()),
nona.values.argmax())
# all NaNs
allna = self.series * nan
self.assert_(isnull(allna.idxmax()))
def test_operators_date(self):
result = self.objSeries + timedelta(1)
result = self.objSeries - timedelta(1)
def test_operators_corner(self):
series = self.ts
empty = Series([], index=Index([]))
result = series + empty
self.assert_(np.isnan(result).all())
result = empty + Series([], index=Index([]))
self.assert_(len(result) == 0)
# TODO: this returned NotImplemented earlier, what to do?
# deltas = Series([timedelta(1)] * 5, index=np.arange(5))
# sub_deltas = deltas[::2]
# deltas5 = deltas * 5
# deltas = deltas + sub_deltas
# float + int
int_ts = self.ts.astype(int)[:-5]
added = self.ts + int_ts
expected = self.ts.values[:-5] + int_ts.values
self.assert_(np.array_equal(added[:-5], expected))
def test_operators_reverse_object(self):
# GH 56
arr = Series(np.random.randn(10), index=np.arange(10),
dtype=object)
def _check_op(arr, op):
result = op(1., arr)
expected = op(1., arr.astype(float))
assert_series_equal(result.astype(float), expected)
_check_op(arr, operator.add)
_check_op(arr, operator.sub)
_check_op(arr, operator.mul)
_check_op(arr, operator.truediv)
_check_op(arr, operator.floordiv)
def test_series_frame_radd_bug(self):
from pandas.util.testing import rands
import operator
# GH 353
vals = Series([rands(5) for _ in xrange(10)])
result = 'foo_' + vals
expected = vals.map(lambda x: 'foo_' + x)
assert_series_equal(result, expected)
frame = DataFrame({'vals' : vals})
result = 'foo_' + frame
expected = DataFrame({'vals' : vals.map(lambda x: 'foo_' + x)})
tm.assert_frame_equal(result, expected)
# really raise this time
self.assertRaises(TypeError, operator.add, datetime.now(), self.ts)
def test_operators_frame(self):
# rpow does not work with DataFrame
df = DataFrame({'A' : self.ts})
tm.assert_almost_equal(self.ts + self.ts, (self.ts + df)['A'])
tm.assert_almost_equal(self.ts ** self.ts, (self.ts ** df)['A'])
def test_operators_combine(self):
def _check_fill(meth, op, a, b, fill_value=0):
exp_index = a.index.union(b.index)
a = a.reindex(exp_index)
b = b.reindex(exp_index)
amask = isnull(a)
bmask = isnull(b)
exp_values = []
for i in range(len(exp_index)):
if amask[i]:
if bmask[i]:
exp_values.append(nan)
continue
exp_values.append(op(fill_value, b[i]))
elif bmask[i]:
if amask[i]:
exp_values.append(nan)
continue
exp_values.append(op(a[i], fill_value))
else:
exp_values.append(op(a[i], b[i]))
result = meth(a, b, fill_value=fill_value)
expected = Series(exp_values, exp_index)
assert_series_equal(result, expected)
a = Series([nan, 1., 2., 3., nan], index=np.arange(5))
b = Series([nan, 1, nan, 3, nan, 4.], index=np.arange(6))
ops = [Series.add, Series.sub, Series.mul, Series.div]
equivs = [operator.add, operator.sub, operator.mul]
if py3compat.PY3:
equivs.append(operator.truediv)
else:
equivs.append(operator.div)
fillvals = [0, 0, 1, 1]
for op, equiv_op, fv in zip(ops, equivs, fillvals):
result = op(a, b)
exp = equiv_op(a, b)
assert_series_equal(result, exp)
_check_fill(op, equiv_op, a, b, fill_value=fv)
def test_combine_first(self):
values = tm.makeIntIndex(20).values.astype(float)
series = Series(values, index=tm.makeIntIndex(20))
series_copy = series * 2
series_copy[::2] = np.NaN
# nothing used from the input
combined = series.combine_first(series_copy)
self.assert_(np.array_equal(combined, series))
# Holes filled from input
combined = series_copy.combine_first(series)
self.assert_(np.isfinite(combined).all())
self.assert_(np.array_equal(combined[::2], series[::2]))
self.assert_(np.array_equal(combined[1::2], series_copy[1::2]))
# mixed types
index = tm.makeStringIndex(20)
floats = Series(tm.randn(20), index=index)
strings = Series(tm.makeStringIndex(10), index=index[::2])
combined = strings.combine_first(floats)
tm.assert_dict_equal(strings, combined, compare_keys=False)
tm.assert_dict_equal(floats[1::2], combined, compare_keys=False)
# corner case
s = Series([1., 2, 3], index=[0, 1, 2])
result = s.combine_first(Series([], index=[]))
assert_series_equal(s, result)
def test_corr(self):
import scipy.stats as stats
# full overlap
self.assertAlmostEqual(self.ts.corr(self.ts), 1)
# partial overlap
self.assertAlmostEqual(self.ts[:15].corr(self.ts[5:]), 1)
# No overlap
self.assert_(np.isnan(self.ts[::2].corr(self.ts[1::2])))
# all NA
cp = self.ts[:10].copy()
cp[:] = np.nan
self.assert_(isnull(cp.corr(cp)))
A = tm.makeTimeSeries()
B = tm.makeTimeSeries()
result = A.corr(B)
expected, _ = stats.pearsonr(A, B)
self.assertAlmostEqual(result, expected)
def test_corr_rank(self):
import scipy
import scipy.stats as stats
# kendall and spearman
A = tm.makeTimeSeries()
B = tm.makeTimeSeries()
A[-5:] = A[:5]
result = A.corr(B, method='kendall')
expected = stats.kendalltau(A, B)[0]
self.assertAlmostEqual(result, expected)
result = A.corr(B, method='spearman')
expected = stats.spearmanr(A, B)[0]
self.assertAlmostEqual(result, expected)
# these methods got rewritten in 0.8
if int(scipy.__version__.split('.')[1]) < 9:
raise nose.SkipTest
# results from R
A = Series([-0.89926396, 0.94209606, -1.03289164, -0.95445587,
0.76910310, -0.06430576, -2.09704447, 0.40660407,
-0.89926396, 0.94209606])
B = Series([-1.01270225, -0.62210117, -1.56895827, 0.59592943,
-0.01680292, 1.17258718, -1.06009347, -0.10222060,
-0.89076239, 0.89372375])
kexp = 0.4319297
sexp = 0.5853767
self.assertAlmostEqual(A.corr(B, method='kendall'), kexp)
self.assertAlmostEqual(A.corr(B, method='spearman'), sexp)
def test_cov(self):
# full overlap
self.assertAlmostEqual(self.ts.cov(self.ts), self.ts.std()**2)
# partial overlap
self.assertAlmostEqual(self.ts[:15].cov(self.ts[5:]), self.ts[5:15].std()**2)
# No overlap
self.assert_(np.isnan(self.ts[::2].cov(self.ts[1::2])))
# all NA
cp = self.ts[:10].copy()
cp[:] = np.nan
self.assert_(isnull(cp.cov(cp)))
def test_copy(self):
ts = self.ts.copy()
ts[::2] = np.NaN
# Did not modify original Series
self.assertFalse(np.isnan(self.ts[0]))
def test_count(self):
self.assertEqual(self.ts.count(), len(self.ts))
self.ts[::2] = np.NaN
self.assertEqual(self.ts.count(), np.isfinite(self.ts).sum())
def test_value_counts_nunique(self):
s = Series(['a', 'b', 'b', 'b', 'b', 'a', 'c', 'd', 'd', 'a'])
hist = s.value_counts()
expected = Series([4, 3, 2, 1], index=['b', 'a', 'd', 'c'])
assert_series_equal(hist, expected)
self.assertEquals(s.nunique(), 4)
# handle NA's properly
s[5:7] = np.nan
hist = s.value_counts()
expected = s.dropna().value_counts()
assert_series_equal(hist, expected)
s = Series({})
hist = s.value_counts()
expected = Series([])
assert_series_equal(hist, expected)
def test_sort(self):
ts = self.ts.copy()
ts.sort()
self.assert_(np.array_equal(ts, self.ts.order()))
self.assert_(np.array_equal(ts.index, self.ts.order().index))
def test_sort_index(self):
import random
rindex = list(self.ts.index)
random.shuffle(rindex)
random_order = self.ts.reindex(rindex)
sorted_series = random_order.sort_index()
assert_series_equal(sorted_series, self.ts)
# descending
sorted_series = random_order.sort_index(ascending=False)
assert_series_equal(sorted_series,
self.ts.reindex(self.ts.index[::-1]))
def test_order(self):
ts = self.ts.copy()
ts[:5] = np.NaN
vals = ts.values
result = ts.order()
self.assert_(np.isnan(result[-5:]).all())
self.assert_(np.array_equal(result[:-5], np.sort(vals[5:])))
result = ts.order(na_last=False)
self.assert_(np.isnan(result[:5]).all())
self.assert_(np.array_equal(result[5:], np.sort(vals[5:])))
# something object-type
ser = Series(['A', 'B'], [1, 2])
# no failure
ser.order()
# ascending=False
ordered = ts.order(ascending=False)
expected = np.sort(ts.valid().values)[::-1]
assert_almost_equal(expected, ordered.valid().values)
ordered = ts.order(ascending=False, na_last=False)
assert_almost_equal(expected, ordered.valid().values)
def test_rank(self):
from scipy.stats import rankdata
self.ts[::2] = np.nan
self.ts[:10][::3] = 4.
ranks = self.ts.rank()
oranks = self.ts.astype('O').rank()
assert_series_equal(ranks, oranks)
mask = np.isnan(self.ts)
filled = self.ts.fillna(np.inf)
exp = rankdata(filled)
exp[mask] = np.nan
assert_almost_equal(ranks, exp)
def test_from_csv(self):
self.ts.to_csv('_foo')
ts = Series.from_csv('_foo')
assert_series_equal(self.ts, ts)
self.series.to_csv('_foo')
series = Series.from_csv('_foo')
assert_series_equal(self.series, series)
outfile = open('_foo', 'w')
outfile.write('1998-01-01|1.0\n1999-01-01|2.0')
outfile.close()
series = Series.from_csv('_foo',sep='|')
checkseries = Series({datetime(1998,1,1): 1.0, datetime(1999,1,1): 2.0})
assert_series_equal(checkseries, series)
series = Series.from_csv('_foo',sep='|',parse_dates=False)
checkseries = Series({'1998-01-01': 1.0, '1999-01-01': 2.0})
assert_series_equal(checkseries, series)
os.remove('_foo')
def test_to_csv(self):
self.ts.to_csv('_foo')
lines = open('_foo', 'U').readlines()
assert(lines[1] != '\n')
os.remove('_foo')
def test_to_dict(self):
self.assert_(np.array_equal(Series(self.ts.to_dict()), self.ts))
def test_clip(self):
val = self.ts.median()
self.assertEqual(self.ts.clip_lower(val).min(), val)
self.assertEqual(self.ts.clip_upper(val).max(), val)
self.assertEqual(self.ts.clip(lower=val).min(), val)
self.assertEqual(self.ts.clip(upper=val).max(), val)
result = self.ts.clip(-0.5, 0.5)
expected = np.clip(self.ts, -0.5, 0.5)
assert_series_equal(result, expected)
self.assert_(isinstance(expected, Series))
def test_valid(self):
ts = self.ts.copy()
ts[::2] = np.NaN
result = ts.valid()
self.assertEqual(len(result), ts.count())
tm.assert_dict_equal(result, ts, compare_keys=False)
def test_isnull(self):
ser = Series([0,5.4,3,nan,-0.001])
assert_series_equal(ser.isnull(), Series([False,False,False,True,False]))
ser = Series(["hi","",nan])
assert_series_equal(ser.isnull(), Series([False,False,True]))
def test_notnull(self):
ser = Series([0,5.4,3,nan,-0.001])
assert_series_equal(ser.notnull(), Series([True,True,True,False,True]))
ser = Series(["hi","",nan])
assert_series_equal(ser.notnull(), Series([True,True,False]))
def test_shift(self):
shifted = self.ts.shift(1)
unshifted = shifted.shift(-1)
tm.assert_dict_equal(unshifted.valid(), self.ts, compare_keys=False)
offset = datetools.bday
shifted = self.ts.shift(1, offset=offset)
unshifted = shifted.shift(-1, offset=offset)
assert_series_equal(unshifted, self.ts)
unshifted = self.ts.shift(0, offset=offset)
assert_series_equal(unshifted, self.ts)
shifted = self.ts.shift(1, timeRule='WEEKDAY')
unshifted = shifted.shift(-1, timeRule='WEEKDAY')
assert_series_equal(unshifted, self.ts)
# corner case
unshifted = self.ts.shift(0)
assert_series_equal(unshifted, self.ts)
def test_shift_int(self):
ts = self.ts.astype(int)
shifted = ts.shift(1)
expected = ts.astype(float).shift(1)
assert_series_equal(shifted, expected)
def test_truncate(self):
offset = datetools.bday
ts = self.ts[::3]
start, end = self.ts.index[3], self.ts.index[6]
start_missing, end_missing = self.ts.index[2], self.ts.index[7]
# neither specified
truncated = ts.truncate()
assert_series_equal(truncated, ts)
# both specified
expected = ts[1:3]
truncated = ts.truncate(start, end)
assert_series_equal(truncated, expected)
truncated = ts.truncate(start_missing, end_missing)
assert_series_equal(truncated, expected)
# start specified
expected = ts[1:]
truncated = ts.truncate(before=start)
assert_series_equal(truncated, expected)
truncated = ts.truncate(before=start_missing)
assert_series_equal(truncated, expected)
# end specified
expected = ts[:3]
truncated = ts.truncate(after=end)
assert_series_equal(truncated, expected)
truncated = ts.truncate(after=end_missing)
assert_series_equal(truncated, expected)
# corner case, empty series returned
truncated = ts.truncate(after=self.ts.index[0] - offset)
assert(len(truncated) == 0)
truncated = ts.truncate(before=self.ts.index[-1] + offset)
assert(len(truncated) == 0)
self.assertRaises(Exception, ts.truncate,
before=self.ts.index[-1] + offset,
after=self.ts.index[0] - offset)
def test_asof(self):
self.ts[5:10] = np.NaN
self.ts[15:20] = np.NaN
val1 = self.ts.asof(self.ts.index[7])
val2 = self.ts.asof(self.ts.index[19])
self.assertEqual(val1, self.ts[4])
self.assertEqual(val2, self.ts[14])
# accepts strings
val1 = self.ts.asof(str(self.ts.index[7]))
self.assertEqual(val1, self.ts[4])
# in there
self.assertEqual(self.ts.asof(self.ts.index[3]), self.ts[3])
# no as of value
d = self.ts.index[0] - datetools.bday
self.assert_(np.isnan(self.ts.asof(d)))
def test_map(self):
index, data = tm.getMixedTypeDict()
source = Series(data['B'], index=data['C'])
target = Series(data['C'][:4], index=data['D'][:4])
merged = target.map(source)
for k, v in merged.iteritems():
self.assertEqual(v, source[target[k]])
# input could be a dict
merged = target.map(source.to_dict())
for k, v in merged.iteritems():
self.assertEqual(v, source[target[k]])
# function
result = self.ts.map(lambda x: x * 2)
self.assert_(np.array_equal(result, self.ts * 2))
def test_map_int(self):
left = Series({'a' : 1., 'b' : 2., 'c' : 3., 'd' : 4})
right = Series({1 : 11, 2 : 22, 3 : 33})
self.assert_(left.dtype == np.float_)
self.assert_(issubclass(right.dtype.type, np.integer))
merged = left.map(right)
self.assert_(merged.dtype == np.float_)
self.assert_(isnull(merged['d']))
self.assert_(not isnull(merged['c']))
def test_map_decimal(self):
from decimal import Decimal
result = self.series.map(lambda x: Decimal(str(x)))
self.assert_(result.dtype == np.object_)
self.assert_(isinstance(result[0], Decimal))
def test_apply(self):
assert_series_equal(self.ts.apply(np.sqrt), np.sqrt(self.ts))
# elementwise-apply
import math
assert_series_equal(self.ts.apply(math.exp), np.exp(self.ts))
# does not return Series
result = self.ts.apply(lambda x: x.values * 2)
assert_series_equal(result, self.ts * 2)
def test_align(self):
def _check_align(a, b, how='left'):
aa, ab = a.align(b, join=how)
join_index = a.index.join(b.index, how=how)
ea = a.reindex(join_index)
eb = b.reindex(join_index)
assert_series_equal(aa, ea)
assert_series_equal(ab, eb)
for kind in JOIN_TYPES:
_check_align(self.ts[2:], self.ts[:-5])
# empty left
_check_align(self.ts[:0], self.ts[:-5])
# empty right
_check_align(self.ts[:-5], self.ts[:0])
# both empty
_check_align(self.ts[:0], self.ts[:0])
def test_align_nocopy(self):
b = self.ts[:5].copy()
# do copy
a = self.ts.copy()
ra, _ = a.align(b, join='left')
ra[:5] = 5
self.assert_(not (a[:5] == 5).any())
# do not copy
a = self.ts.copy()
ra, _ = a.align(b, join='left', copy=False)
ra[:5] = 5
self.assert_((a[:5] == 5).all())
# do copy
a = self.ts.copy()
b = self.ts[:5].copy()
_, rb = a.align(b, join='right')
rb[:3] = 5
self.assert_(not (b[:3] == 5).any())
# do not copy
a = self.ts.copy()
b = self.ts[:5].copy()
_, rb = a.align(b, join='right', copy=False)
rb[:2] = 5
self.assert_((b[:2] == 5).all())
def test_align_sameindex(self):
a, b = self.ts.align(self.ts, copy=False)
self.assert_(a.index is self.ts.index)
self.assert_(b.index is self.ts.index)
# a, b = self.ts.align(self.ts, copy=True)
# self.assert_(a.index is not self.ts.index)
# self.assert_(b.index is not self.ts.index)
def test_reindex(self):
identity = self.series.reindex(self.series.index)
self.assertEqual(id(self.series.index), id(identity.index))
subIndex = self.series.index[10:20]
subSeries = self.series.reindex(subIndex)
for idx, val in subSeries.iteritems():
self.assertEqual(val, self.series[idx])
subIndex2 = self.ts.index[10:20]
subTS = self.ts.reindex(subIndex2)
for idx, val in subTS.iteritems():
self.assertEqual(val, self.ts[idx])
stuffSeries = self.ts.reindex(subIndex)
self.assert_(np.isnan(stuffSeries).all())
# This is extremely important for the Cython code to not screw up
nonContigIndex = self.ts.index[::2]
subNonContig = self.ts.reindex(nonContigIndex)
for idx, val in subNonContig.iteritems():
self.assertEqual(val, self.ts[idx])
def test_reindex_corner(self):
# (don't forget to fix this) I think it's fixed
reindexed_dep = self.empty.reindex(self.ts.index, method='pad')
# corner case: pad empty series
reindexed = self.empty.reindex(self.ts.index, method='pad')
# pass non-Index
reindexed = self.ts.reindex(list(self.ts.index))
assert_series_equal(self.ts, reindexed)
# bad fill method
ts = self.ts[::2]
self.assertRaises(Exception, ts.reindex, self.ts.index, method='foo')
def test_reindex_pad(self):
s = Series(np.arange(10), np.arange(10))
s2 = s[::2]
reindexed = s2.reindex(s.index, method='pad')
reindexed2 = s2.reindex(s.index, method='ffill')
assert_series_equal(reindexed, reindexed2)
expected = Series([0, 0, 2, 2, 4, 4, 6, 6, 8, 8], index=np.arange(10))
assert_series_equal(reindexed, expected)
def test_reindex_backfill(self):
pass
def test_reindex_int(self):
ts = self.ts[::2]
int_ts = Series(np.zeros(len(ts), dtype=int), index=ts.index)
# this should work fine
reindexed_int = int_ts.reindex(self.ts.index)
# if NaNs introduced
self.assert_(reindexed_int.dtype == np.float_)
# NO NaNs introduced
reindexed_int = int_ts.reindex(int_ts.index[::2])
self.assert_(reindexed_int.dtype == np.int_)
def test_reindex_bool(self):
# A series other than float, int, string, or object
ts = self.ts[::2]
bool_ts = Series(np.zeros(len(ts), dtype=bool), index=ts.index)
# this should work fine
reindexed_bool = bool_ts.reindex(self.ts.index)
# if NaNs introduced
self.assert_(reindexed_bool.dtype == np.object_)
# NO NaNs introduced
reindexed_bool = bool_ts.reindex(bool_ts.index[::2])
self.assert_(reindexed_bool.dtype == np.bool_)
def test_reindex_bool_pad(self):
# fail
ts = self.ts[5:]
bool_ts = Series(np.zeros(len(ts), dtype=bool), index=ts.index)
filled_bool = bool_ts.reindex(self.ts.index, method='pad')
self.assert_(isnull(filled_bool[:5]).all())
def test_reindex_like(self):
other = self.ts[::2]
assert_series_equal(self.ts.reindex(other.index),
self.ts.reindex_like(other))
def test_rename(self):
renamer = lambda x: x.strftime('%Y%m%d')
renamed = self.ts.rename(renamer)
self.assertEqual(renamed.index[0], renamer(self.ts.index[0]))
# dict
rename_dict = dict(zip(self.ts.index, renamed.index))
renamed2 = self.ts.rename(rename_dict)
assert_series_equal(renamed, renamed2)
# partial dict
s = Series(np.arange(4), index=['a', 'b', 'c', 'd'])
renamed = s.rename({'b' : 'foo', 'd' : 'bar'})
self.assert_(np.array_equal(renamed.index, ['a', 'foo', 'c', 'bar']))
def test_preserveRefs(self):
seq = self.ts[[5,10,15]]
seq[1] = np.NaN
self.assertFalse(np.isnan(self.ts[10]))
def test_ne(self):
ts = TimeSeries([3, 4, 5, 6, 7], [3, 4, 5, 6, 7], dtype=float)
expected = [True, True, False, True, True]
self.assert_(tm.equalContents(ts.index != 5, expected))
self.assert_(tm.equalContents(~(ts.index == 5), expected))
def test_pad_nan(self):
x = TimeSeries([np.nan, 1., np.nan, 3., np.nan],
['z', 'a', 'b', 'c', 'd'], dtype=float)
x = x.fillna(method='pad')
expected = TimeSeries([np.nan, 1.0, 1.0, 3.0, 3.0],
['z', 'a', 'b', 'c', 'd'], dtype=float)
assert_series_equal(x[1:], expected[1:])
self.assert_(np.isnan(x[0]), np.isnan(expected[0]))
def test_unstack(self):
from numpy import nan
from pandas.util.testing import assert_frame_equal
index = MultiIndex(levels=[['bar', 'foo'], ['one', 'three', 'two']],
labels=[[1, 1, 0, 0], [0, 1, 0, 2]])
s = Series(np.arange(4.), index=index)
unstacked = s.unstack()
expected = DataFrame([[2., nan, 3.], [0., 1., nan]],
index=['bar', 'foo'],
columns=['one', 'three', 'two'])
|
assert_frame_equal(unstacked, expected)
|
pandas.util.testing.assert_frame_equal
|
"""
Estimate results, inc. economic impacts.
Written by <NAME>.
February 2022.
"""
import os
import configparser
import pandas as pd
from tqdm import tqdm
import numpy as np
import geopandas as gpd
import rasterio
import random
from misc import params, technologies, get_countries, get_regions, get_scenarios
CONFIG = configparser.ConfigParser()
CONFIG.read(os.path.join(os.path.dirname(__file__), 'script_config.ini'))
BASE_PATH = CONFIG['file_locations']['base_path']
DATA_RAW = os.path.join(BASE_PATH, 'raw')
DATA_PROCESSED = os.path.join(BASE_PATH, 'processed')
RESULTS = os.path.join(BASE_PATH, '..', 'results')
def query_hazard_layers(country, regions, technologies, scenarios):
"""
Query each hazard layer and estimate fragility.
"""
iso3 = country['iso3']
name = country['country']
regional_level = country['lowest']
gid_level = 'GID_{}'.format(regional_level)
filename = 'fragility_curve.csv'
path_fragility = os.path.join(DATA_RAW, filename)
f_curve = pd.read_csv(path_fragility)
f_curve = f_curve.to_dict('records')
for scenario in scenarios:
# if not scenario == 'data\processed\MWI\hazards\inunriver_rcp8p5_MIROC-ESM-CHEM_2080_rp01000.tif':
# continue
for technology in technologies:
output = []
for idx, region in regions.iterrows():
gid_id = region[gid_level]
scenario_name = os.path.basename(scenario)
# if not gid_id == 'MWI.13.12_1':
# continue
filename = '{}_{}_{}.shp'.format(gid_id, technology, scenario_name)
folder_out = os.path.join(DATA_PROCESSED, iso3, 'regional_data', gid_id, 'scenarios', scenario_name)
path_output = os.path.join(folder_out, filename)
if os.path.exists(path_output):
continue
filename = '{}_{}.shp'.format(technology, gid_id)
folder = os.path.join(DATA_PROCESSED, iso3, 'regional_data', gid_id, 'sites')
path = os.path.join(folder, filename)
if not os.path.exists(path):
continue
sites = gpd.read_file(path, crs='epsg:4326')#[:1]
failures = 0
for idx, site in sites.iterrows():
with rasterio.open(scenario) as src:
src.kwargs = {'nodata':255}
coords = [(site['geometry'].x, site['geometry'].y)]
depth = [sample[0] for sample in src.sample(coords)][0]
fragility = query_fragility_curve(f_curve, depth)
failure_prob = random.uniform(0, 1)
failed = (1 if failure_prob < fragility else 0)
if fragility > 0:
failures += 1
output.append({
'type': 'Feature',
'geometry': site['geometry'],
'properties': {
'radio': site['radio'],
'mcc': site['mcc'],
'net': site['net'],
'area': site['area'],
'cell': site['cell'],
'gid_level': gid_level,
'gid_id': region[gid_level],
'depth': depth,
'scenario': scenario_name,
'fragility': fragility,
'fail_prob': failure_prob,
'failure': failed,
'cost_usd': round(100000 * fragility),
# 'cell_id': site['cell_id'],
},
})
if len(output) == 0:
return
if not os.path.exists(folder_out):
os.makedirs(folder_out)
output = gpd.GeoDataFrame.from_features(output, crs='epsg:4326')
output.to_file(path_output, crs='epsg:4326')
return
def query_fragility_curve(f_curve, depth):
"""
Query the fragility curve.
"""
if depth < 0:
return 0
for item in f_curve:
if item['depth_lower_m'] <= depth < item['depth_upper_m']:
return item['fragility']
else:
continue
print('fragility curve failure: {}'.format(depth))
return 0
def econ_interim_impacts(country, technologies, scenarios):
"""
Estimate economic impacts.
Aqueduct flood scenarios as structured as follows:
floodtype_climatescenario_subsidence_year_returnperiod_projection
"""
iso3 = country['iso3']
filename = 'econ_interim_{}.csv'.format(iso3)
folder_out = os.path.join(RESULTS)
path_output = os.path.join(folder_out, filename)
# if os.path.exists(path_output):
# return
output = []
for scenario in tqdm(scenarios):
for technology in technologies:
scenario = os.path.basename(scenario)
filename = 'sites_{}_{}.csv'.format(technology, scenario)
folder = os.path.join(DATA_PROCESSED, country['iso3'], 'failed_sites')
path = os.path.join(folder, filename)
data = pd.read_csv(path)
data = data.to_dict('records')#[:10000]
### floodtype_climatescenario_subsidence_year_returnperiod_projection
floodtype = scenario.split('_')[0]
climatescenario = scenario.split('_')[1]
subsidence = scenario.split('_')[2]
year = scenario.split('_')[3]
returnperiod = scenario.split('_')[4].strip('.tif')
projection = scenario.split('_')[5:] #not all same length
if floodtype == 'inuncoast': #deal with differences between climate scenarios
projection = '_'.join(projection)
elif floodtype == 'inunriver':
projection = 'inunriver'
else:
print('Did not recognize floodtype')
projection = projection.strip('.tif')
affected_sites = 0
cost = 0
for item in data:
if item['scenario'] == scenario:
if item['fragility'] > 0:
affected_sites += 1
cost += (100000 * item['fragility'])
output.append({
'floodtype': floodtype,
'climatescenario': climatescenario,
'subsidence': subsidence,
'year': year,
'returnperiod': returnperiod,
'projection': projection,
'technology': technology,
'affected_sites': affected_sites,
'cost': cost,
'scenario': scenario,
})
output = pd.DataFrame(output)
output = output.drop_duplicates()
if not os.path.exists(folder_out):
os.mkdir(folder_out)
output.to_csv(path_output, index=False)
return
def econ_final_impacts(country):
"""
Compare economic impacts against historical.
Aqueduct flood scenarios as structured as follows:
floodtype_climatescenario_subsidence_year_returnperiod_projection
"""
iso3 = country['iso3']
filename = 'econ_interim_{}.csv'.format(iso3)
folder_in = os.path.join(RESULTS)
path_in = os.path.join(folder_in, filename)
if not os.path.exists(path_in):
return
data = pd.read_csv(path_in)
data = process_edit_return_periods(data)
data = add_model_average(data, 'cost')
### Add hist baseline to inuncoast
inuncoast = data.loc[data['floodtype'] == 'inuncoast']
historical = inuncoast.loc[inuncoast['climatescenario'] == 'historical']
scenarios = inuncoast.loc[inuncoast['climatescenario'] != 'historical']
historical = historical[['returnperiod', 'technology', 'affected_sites', 'cost']].reset_index()
historical = historical.rename({'affected_sites': 'hist_affected_sites', 'cost': 'hist_cost'}, axis=1)
historical.drop('index', axis=1, inplace=True)
inuncoast = pd.merge(scenarios, historical, how='left', on=['returnperiod', 'technology'])
### Add hist baseline to inunriver
inunriver = data.loc[data['floodtype'] == 'inunriver']
historical = inunriver.loc[inunriver['climatescenario'] == 'historical']
scenarios = inunriver.loc[inunriver['climatescenario'] != 'historical']
historical = historical[['returnperiod', 'technology', 'affected_sites', 'cost']].reset_index()
historical = historical.rename({'affected_sites': 'hist_affected_sites', 'cost': 'hist_cost'}, axis=1)
historical.drop('index', axis=1, inplace=True)
inunriver = pd.merge(scenarios, historical, how='left', on=['returnperiod', 'technology'])
output = pd.concat([inuncoast, inunriver])
output['sites_difference'] = output['affected_sites'] - output['hist_affected_sites']
output['cost_difference'] = output['cost'] - output['hist_cost']
filename = 'econ_final_{}.csv'.format(iso3)
folder_out = os.path.join(RESULTS)
path_output = os.path.join(folder_out, filename)
output.to_csv(path_output, index=False)
return
def process_edit_return_periods(data):
"""
Correct differences in the return period text.
"""
output = []
for idx, item in data.iterrows():
rn_name = item['returnperiod']
if rn_name == 'rp01000' or rn_name == 'rp1000':
item['returnperiod'] = '1000-year'
elif rn_name == 'rp00500' or rn_name == 'rp0500':
item['returnperiod'] = '500-year'
elif rn_name == 'rp00250' or rn_name == 'rp0250':
item['returnperiod'] = '250-year'
elif rn_name == 'rp00100' or rn_name == 'rp0100':
item['returnperiod'] = '100-year'
else:
print('Return period not recognized')
output.append(item)
output = pd.DataFrame(output)
return output
def add_model_average(data, metric):
"""
Take the model average for inunriver.
"""
inuncoast = data.loc[data['floodtype'] == 'inuncoast']
inunriver = data.loc[data['floodtype'] == 'inunriver']
historical = inunriver.loc[data['climatescenario'] == 'historical']
inunriver = inunriver.loc[data['climatescenario'] != 'historical']
scenarios = inunriver['climatescenario'].unique()
years = inunriver['year'].unique()
returnperiods = inunriver['returnperiod'].unique()
technologies = inunriver['technology'].unique()
models = inunriver['subsidence'].unique()
output = []
for scenario in scenarios:
subset_scenarios = inunriver.loc[inunriver['climatescenario'] == scenario]
for year in years:
subset_year = subset_scenarios.loc[subset_scenarios['year'] == year]
for returnperiod in returnperiods:
subset_rp = subset_year.loc[subset_year['returnperiod'] == returnperiod]
if len(subset_rp) == 0:
continue
for technology in technologies:
subset_tech = subset_rp.loc[subset_rp['technology'] == technology]
if len(subset_tech) == 0:
continue
# affected_sites = []
mean_list = []
for model in models:
subset_model = subset_tech.loc[subset_tech['subsidence'] == model]
if len(subset_model) == 0:
continue
# affected_sites.append(subset_model['affected_sites'].values[0])
mean_list.append(subset_model[metric].values[0])
output.append({
'floodtype': 'inunriver',
'climatescenario': scenario,
'subsidence': 'model_mean',
'year': year,
'returnperiod': returnperiod,
'projection': 'nunriver',
'technology': technology,
# 'affected_sites': int(round(np.mean(affected_sites))),
metric: int(round(np.mean(mean_list))),
'scenario': 'model_mean',
})
output = pd.DataFrame(output)
output = pd.concat([inuncoast, historical, inunriver, output])
output = output.drop_duplicates()
return output
def coverage_interim_impacts(country, regions, technologies, scenarios):
"""
Estimate coverage.
Aqueduct flood scenarios as structured as follows:
floodtype_climatescenario_subsidence_year_returnperiod_projection
"""
iso3 = country['iso3']
filename = 'coverage_interim_{}.csv'.format(iso3)
folder_out = os.path.join(RESULTS)
path_output = os.path.join(folder_out, filename)
# if os.path.exists(path_output):
# return
output = []
for scenario in tqdm(scenarios):
scenario = os.path.basename(scenario)
### floodtype_climatescenario_subsidence_year_returnperiod_projection
floodtype = scenario.split('_')[0]
climatescenario = scenario.split('_')[1]
subsidence = scenario.split('_')[2]
year = scenario.split('_')[3]
returnperiod = scenario.split('_')[4].strip('.tif')
projection = scenario.split('_')[5:] #not all same length
if floodtype == 'inuncoast': #deal with differences between climate scenarios
projection = '_'.join(projection)
elif floodtype == 'inunriver':
projection = 'inunriver'
else:
print('Did not recognize floodtype')
projection = projection.strip('.tif')
for technology in tqdm(technologies):
population_covered = 0
for idx, region in regions.iterrows():
regional_level = country['gid_region']
gid_level = 'GID_{}'.format(regional_level)
gid_id = region[gid_level]
filename = 'covered_{}_{}_{}.csv'.format(gid_id, technology, scenario)
folder_out = os.path.join(DATA_PROCESSED, iso3, 'regional_data', gid_id, technology)
path_in = os.path.join(folder_out, filename)
if not os.path.exists(path_in):
continue
data = pd.read_csv(path_in)
pop = data['population'].sum()
if pop > 0:
population_covered += pop
output.append({
'floodtype': floodtype,
'climatescenario': climatescenario,
'subsidence': subsidence,
'year': year,
'returnperiod': returnperiod,
'projection': projection,
'covered_population': population_covered,
'technology': technology,
'scenario': scenario,
})
output = pd.DataFrame(output)
output = output.drop_duplicates()
if not os.path.exists(folder_out):
os.mkdir(folder_out)
output.to_csv(path_output, index=False)
return
def coverage_final_impacts(country):
"""
Compare coverage impacts against historical.
Aqueduct flood scenarios as structured as follows:
floodtype_climatescenario_subsidence_year_returnperiod_projection
"""
iso3 = country['iso3']
filename = 'coverage_interim_{}.csv'.format(iso3)
folder_in = os.path.join(RESULTS)
path_in = os.path.join(folder_in, filename)
if not os.path.exists(path_in):
return
data =
|
pd.read_csv(path_in)
|
pandas.read_csv
|
def secondary_market_monthly(file_path):
from IPython.display import display
import numpy as np
import pandas as pd
pd.set_option('display.unicode.ambiguous_as_wide', True)
pd.set_option('display.unicode.east_asian_width', True)
df = pd.read_excel(file_path)
check = ['满懿(上海)房地产', '上海搜房房天下房地产']
for a in df['中介公司']:
if a in check:
print('recheck agency!', a)
break
num = df['中介公司'].count()
avg_price = df['总价'].mean()
avg_area = df['面积'].mean()
total_amount = df['总价'].sum()
agency = ['上海中原物业', '上海汉宇房地产', '上海我爱我家房地产', '上海太平洋房屋',
'德佑房地产', '上海云房数据', '上海易居房地产', '上海志远房地产']
dict1 = {}
for a in agency:
dict1[a] = [df['总价'][df['中介公司'] == a].count()/num,
df['总价'][df['中介公司'] == a].sum()/total_amount]
result1 = pd.DataFrame(dict1, index = ['单数市占', '金额市占'])
x = [1, 6, 7, 8, 10, 11]
y = ['宝原', '链家', '搜房', '满懿', '房多多', '房好多']
for x1, y1 in zip(x, y):
result1.insert(x1, y1, [0, 0])
dict2 = {'成交套数': num, '套均价格': avg_price/10000, '套均面积': avg_area}
result2 = pd.DataFrame(dict2, index = [file_path[2:4]])
writer =
|
pd.ExcelWriter('result.xlsx')
|
pandas.ExcelWriter
|
# ----------------------------------------------------------------------------
# Copyright (c) 2019, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ----------------------------------------------------------------------------
import dendropy
import unittest
import pandas as pd
import tempfile
import numpy as np
from time import time
import os
from .logger import *
CUR_PATH = os.path.dirname(os.path.abspath(__file__))
if 'TMPDIR' in os.environ:
tmpdir = os.environ['TMPDIR']
else:
tmpdir = tempfile.gettempdir()
def isNotEmpty(s):
return bool(s and s.strip())
class Data():
def __init__(self, seed_num, logger, generate_strategy, tmp_dir, xgen, n_beta, n_binom,
var_method, stat_method, prior_weight, coef, exponent, pseudo, pseudo_cnt, normalized):
if tmp_dir is None:
tmp_dir = tempfile.mkdtemp(dir=tmpdir)
self.tmp_dir = tmp_dir
if logger is not None:
self.logger_ins = logger
else:
self.log_fp = tempfile.mktemp(dir=tmp_dir, prefix='logfile.log')
print(self.log_fp)
log = LOG(self.log_fp)
self.logger_ins = log.get_logger('generator')
self.logger_ins.info("The seed number is set to", seed_num)
np.random.seed(seed_num)
self.logger_ins.info("The generate_strategy is", generate_strategy)
self.logger_ins.info("The xgen is", xgen)
self.logger_ins.info("The n_beta is", n_beta)
self.logger_ins.info("The n_binom is", n_binom)
self.logger_ins.info("The var_method is", var_method)
self.logger_ins.info("The stat_method is", stat_method)
self.logger_ins.info("The prior_weight is", prior_weight)
self.logger_ins.info("The coef is", coef)
self.logger_ins.info("The exponent is", exponent)
self.logger_ins.info("The pseudo is", pseudo)
self.logger_ins.info("The pseudo_cnt is", pseudo_cnt)
self.logger_ins.info("The normalized is", normalized)
if generate_strategy is not None:
# generate_strategy: generation strategy, it could be "augmentation" meaning we are just augmenting data
# without trying to balance out labels. Alternatively, "balancing" meaning we are balancing out labels
self.generate_strategy = generate_strategy
# stat_method: defines the generative procedure. options are "binom" , "beta_binom", "beta". We don't
# recommend using beta. The default is binom
self.stat_method = stat_method
# prior_weight: defines the weight for per class parameter estimation. Default is 0 meaning we only use per individual parameter estimations
self.prior_weight = prior_weight
# coef: The penalty in the tree based variance formula. Default is 200. Larger numbers cause less variance
self.coef = coef
# exponent: The exponent in the tree based variance formula. Default is 1/2. Meaning
self.exponent = exponent
self.pseudo = pseudo
self.xgen = xgen
self.n_beta = n_beta
self.n_binom = n_binom
self.pseudo_cnt = pseudo_cnt
# var_method: options are "br_penalized": priors are estimated based on the tree, or
# "class": priors are estimated based on method of moments (cluster wise).
self.var_method = var_method
# normalized: If normalize biom table at the end or not. Default is False
self.normalized = normalized
if tmp_dir is not None:
self.dirpath = tmp_dir
else:
self.dirpath = tempfile.mkdtemp(dir=tmpdir)
self.logger_ins.info("Temporary directory path is", self.dirpath)
if self.generate_strategy == "augmentation":
self.most_freq_class = None
self.freq_classes = None
def _set_data(self, table, y, tree, sampling_strategy):
t0 = time()
self._load_tree(tree)
self.logger_ins.info("loading the tree took", time() - t0, "seconds")
t0 = time()
table = self._prune_table(table, min_samples=0)
self._set_table(table)
self.logger_ins.info("biom table loaded in", time() - t0, "seconds")
self.logger_ins.info("Number of sOTUs is ", len(self.obs))
self.logger_ins.info("Number of samples is ", len(self.samples))
self._prune_phylo()
if len(set([x.taxon.label for x in self.tree.leaf_nodes()]) - set(self.obs)) != 0:
raise ValueError(
"The set of leaf labels is not the same as observations from biom table"
)
t0 = time()
self._set_labels(y)
self.logger_ins.info("Meta data loaded in", time() - t0, "seconds")
self._set_num_to_select(sampling_strategy)
self._add_pseudo()
self._init_gen()
def _add_pseudo(self):
'''
adds pseudo count to each feature for the training data to avoid zero count
self.pseudo_cnt should be an integer, where we divide it between all features.
'''
self.pseudo_cnt /= self.num_leaves
self.table += self.pseudo_cnt
def _prune_phylo(self):
to_delete_set = set([x.taxon.label for x in self.tree.leaf_nodes()]) - set(self.obs)
if len(to_delete_set) > 0:
self.logger_ins.info("The set of features in the phylogeny and the table are not the same.",
len(to_delete_set), "features will be pruned from the tree.")
self.tree.prune_taxa_with_labels(to_delete_set)
else:
self.logger_ins.info("The set of features in the phylogeny and the table are the same. "
"No feature will be pruned from the tree.")
return
def _prune_table(self, table, min_samples: int = 1):
filter_fn = lambda val, id_, md: np.sum(val) >= min_samples
return table.filter(filter_fn, axis='observation', inplace=False)
def _set_num_to_select(self, sampling_strategy=None):
'''
This function sets the number of samples to be drawn for each class
self.n_samples_to_select: key: class label, values: number of samples to be selected from each class
:return:
'''
# If self.most_freq_class is None or self.freq_classes is None, then we are just augmenting, no need to
# set up n_samples_to_select
self.class_sizes = None
if sampling_strategy:
try:
sampling_strategy_pd = pd.read_csv(sampling_strategy, sep="\t", low_memory=False,
index_col='#GroupID')
self.class_sizes = sampling_strategy_pd.iloc[:, 0]
except ValueError:
print(
"The first column for the sampling strategy TSV (tab-delimited) file should be '#GroupID', and "
"first column correspond to group sizes. Please note that your group IDs should match those "
"in metadata file"
)
exit(1)
if self.generate_strategy == 'augmentation':
self.n_binom_extra = {'all': 0}
else:
self.n_binom_extra = dict()
self.n_samples_to_select = dict()
for c in self.freq_classes:
# n_all: after augmentation, all classes should have n_all + self.most_freq_class number of samples
n_all = self.most_freq_class * (self.xgen)
# check if our logic was correct
if n_all + self.most_freq_class - self.freq_classes[c] < 0:
raise ValueError(
"Please choose a non negative xgen number!"
)
# number of samples to generate equals n_total_samples_to_gen
n_total_samples_to_gen = np.max(n_all + self.most_freq_class - self.freq_classes[c], 0)
if self.class_sizes is not None:
try:
self.logger_ins.info("Reading the total samples to generate for class", c, "from",
sampling_strategy)
n_total_samples_to_gen = np.max(self.class_sizes[c] - self.freq_classes[c], 0)
except KeyError:
print(
"The first column for the sampling strategy TSV (tab-delimited) file should be "
"'#GroupID', and first column correspond to group sizes. Please note that your group IDs "
"should match those in metadata file. Your class labels from meta data file are",
set(self.freq_classes.keys()), "but your class labels in your sampling strategy TSV "
"file are", set(self.class_sizes.index)
)
exit(1)
self.logger_ins.info("Will generate", n_total_samples_to_gen, "for the class", c)
# per each sample we generate self.n_binom*self.n_beta samples. Thus, the number of samples to select is
self.n_samples_to_select[c] = np.max(
(n_total_samples_to_gen) // (self.n_binom * self.n_beta), 0)
# per each sample we generate self.n_binom*self.n_beta samples. If
# n_total_samples_to_gen % (self.n_binom * self.n_beta) != 0, then we need some extra augmentation
self.n_binom_extra[c] = max(
n_total_samples_to_gen - self.n_samples_to_select[c] * self.n_binom * self.n_beta, 0)
self.logger_ins.info("class", c, "Generating", self.n_samples_to_select[c], "samples", "with",
"n_binom:", self.n_binom, "and n_beta:", self.n_beta, "and n_binom_extra",
self.n_binom_extra[c])
def _set_labels(self, labels):
'''
:param labels: labels
creates a data frame from the labels using self.__set_meta_clusters(labels)
Then finds the most frequent class, an store the frequency in self.most_freq_class
Finally sets clusters, a dictionary with keys: class labels, values: sample IDs
:return:
'''
self.meta, self.labels, self.classes, counts = self._set_meta_clusters(labels)
self.freq_classes = dict()
max_cnt = 0
for i, cls in enumerate(self.classes):
self.freq_classes[cls] = counts[i]
if self.freq_classes[cls] > max_cnt:
max_cnt = self.freq_classes[cls]
self.most_freq_class = max_cnt
self.samples = np.asarray(self.samples)
self._set_clusters()
def _set_meta_clusters(self, labels):
'''
:param labels: phenotype labels
creates a data frame from the labels, and fills the missing labels with a label "-1" by default.
:return: data frame (meta), labels, classes: set of labels, counts: number of samples corresponding to each class
'''
labels = np.asarray(labels).ravel()
meta =
|
pd.DataFrame(index=self.samples, columns=['label'], data=labels)
|
pandas.DataFrame
|
import pandas as pd
import requests
import argparse
from datetime import datetime
from time import sleep
from bs4 import BeautifulSoup
sortFilters = {
"LowPrice": {"data": "Prices", "asc": True},
"Alpha": {"data": "Titles", "asc": True},
"LocationAlpha": {"data": "Locations", "asc": True},
"Newest": {"data": "Dates", "asc": False}
}
defaultSort = "LowPrice"
def cl_search(keywords, filterTypes=None, filterLocationData=None, filterPriceData=None, sort=defaultSort, filterFree=False, DEBUG=False):
### RETRIEVE RSS FILE FROM CRAIGSLIST SEARCH
#url_base = 'http://vancouver.craigslist.org/search/sss?format=rss&query='
url_base = "https://vancouver.craigslist.org/search/msa?query="
url_search_base = "https://vancouver.craigslist.org"
if keywords:
searchTerms = keywords
else:
searchTerms = "synthesizer"
titles = []
locations = []
dates = []
prices = []
descriptions = []
urls = []
urls.append(url_base + searchTerms)
### RECURSIVELY SCRAPE ALL PAGES
while len(urls) > 0:
#wait 1 second in between each new url request
sleep(1)
url = urls.pop(0)
rsp = requests.get(url)
soup = BeautifulSoup(rsp.text,"lxml")
next_url = soup.find('a', class_= "button next")
if next_url:
if next_url['href']:
urls.append(url_search_base + next_url['href'])
#return all listings
listings = soup.find_all('li', attrs={'class': 'result-row'})
for listing in listings:
titles.append(listing.find('a', {'class': ["result-title"]}).text.lstrip().rstrip())
date = datetime.strptime(listing.find('time', {'class': ["result-date"]}).text.lstrip().rstrip(), '%b %d')
dates.append(date)
try:
prices.append(int(listing.find('span', {'class': "result-price"}).text.lstrip().rstrip().strip("$")))
except:
prices.append(-1)
try:
locations.append(listing.find('span', {'class': "result-hood"}).text.lstrip().rstrip().strip("(").strip(")").upper())
except:
locations.append('zzz_missing')
#write findings to a dataframa
listings_df =
|
pd.DataFrame({"Dates": dates, "Locations": locations, "Titles": titles, "Prices": prices})
|
pandas.DataFrame
|
"""
Purpose:
Date created: 2021-07-19
Contributor(s):
<NAME>.
"""
from io import StringIO
import urllib.parse as upars
import urllib.request as ureq
import orjson
import requests
import pandas as pd
from io import StringIO
import urllib.request as ureq
import orjson
import pandas as pd
base_url = "https://www.census.gov/naics/resources/js/data/naics-sector-descriptions.json"
with ureq.urlopen(base_url) as resp:
bdata = resp.read()
# data = StringIO(resp.read().decode("utf-8"))
if bdata:
dd = orjson.loads(bdata)
# dd.get("naicsRef")[0].get("table")
# dd.get("naicsRef")[0].get("table").keys()
# dd.get("naicsRef")[0].get("table").get("tableRow")
# orjson.dumps(dd.get("naicsRef"))
# orjson.dumps(dd.get("naicsRef")[0])
df = pd.read_json(orjson.dumps(dd.get("naicsRef")[0].get("table").get("tableRow")))
dfe = df.loc[:, "sectorCode"].str.split("-").explode().reset_index()
pd.merge(dfe, df, how="left", left_on = "sectorCode", right_on = "sectorCode")
pd.merge(dfe, df, how="left", left_index = True, right_index = True)
subsection_base_url = "https://www.census.gov/naics/resources/model/dataHandler.php"
agri_url_sample = "https://www.census.gov/naics/resources/model/dataHandler.php?input=11&chart=2017&search=Y"
qq = upars.urlparse(agri_url_sample)
qq_qry = dict(upars.parse_qsl(qq.query))
argi_subsect_sample = "https://www.census.gov/naics/resources/model/dataHandler.php?=&year=2017&code=11&search=true"
yy = upars.urlparse(argi_subsect_sample)
yy_qry = dict(upars.parse_qsl(yy.query))
code_111111_url = "https://www.census.gov/naics/resources/model/dataHandler.php?=&year=2017&code=11111&search=true"
with ureq.urlopen(base_url) as resp:
data = StringIO(resp.read().decode("utf-8"))
dfs =
|
pd.read_json(data)
|
pandas.read_json
|
#!/usr/bin/env python3
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
import dash_table
import plotly.graph_objs as go
import pandas as pd
import numpy as np
import os
import math
from scipy.stats import mannwhitneyu, ttest_ind
from nutris import nutris
BASEPATH = "/data"
app = dash.Dash(__name__)
app.config['suppress_callback_exceptions']=True
def combine_all_data():
print("getting new data")
survey_df = pd.DataFrame()
#tracking_files = {}
machineLayouts = pd.DataFrame()
timings = pd.DataFrame()
for filename in os.listdir(BASEPATH):
if ".csv" in filename:
if "machineLayout" in filename:
user_id = filename.split("_")[0]
task = filename.split("_")[1]
#the machinelayout is the same for all tasks no need to store it multiple times
#extract the machine layout
machinelayout_df_tmp = pd.read_csv(os.path.join(BASEPATH, filename), sep=';')
machinelayout_df_tmp["user_id"] = user_id
machinelayout_df_tmp["task"] = task
machineLayouts = machineLayouts.append(machinelayout_df_tmp, ignore_index=True)
if "_trackings_" in filename:
user_id = filename.split("_")[0]
task = filename.split("_")[1]
timings_df_tmp = pd.read_csv(os.path.join(BASEPATH, filename), sep=',')
timings = timings.append({"user_id":user_id, "task":task, "time":timings_df_tmp.iloc[-1]["timestamp"] / 1000}, ignore_index=True)
for filename in os.listdir(BASEPATH):
if ".csv" in filename and not "BAK" in filename:
if "_evaluation_" in filename:
survey_df_tmp = pd.read_csv(os.path.join(BASEPATH, filename), index_col="user_id", sep=';')
survey_df = survey_df_tmp.combine_first(survey_df)
elif "_basic_" in filename:
survey_df_tmp = pd.read_csv(os.path.join(BASEPATH, filename), index_col="user_id", sep=';')
survey_df = survey_df_tmp.combine_first(survey_df)
elif "_guess_" in filename:
survey_df_tmp = pd.read_csv(os.path.join(BASEPATH, filename), index_col="user_id", sep=';')
survey_df = survey_df_tmp.combine_first(survey_df)
elif "_task_" in filename:
#extract the nutriscore & label from machine layout if available
survey_df_tmp = pd.read_csv(os.path.join(BASEPATH, filename), index_col="user_id", sep=';')
user_id = str(survey_df_tmp.index[0])
#assuming there is only one row in the survey_task.csv, which is fine if data from typeform
for taskNr in range(1,5):
try:
product = machineLayouts[ (machineLayouts["user_id"] == user_id) & \
(machineLayouts["BoxNr"] == int(survey_df_tmp["t_{}".format(taskNr)].iloc[0]))
].iloc[0]
survey_df_tmp["nutri_label_{}".format(taskNr)] = product["ProductNutriLabel"]
survey_df_tmp["nutri_score_{}".format(taskNr)] = product["ProductNutriScore"]
survey_df_tmp["energy_{}".format(taskNr)] = nutris[product["ProductId"]]["energy"]
survey_df_tmp["sugar_{}".format(taskNr)] = nutris[product["ProductId"]]["sugar"]
survey_df_tmp["sat_fat_{}".format(taskNr)] = nutris[product["ProductId"]]["sat_fat"]
survey_df_tmp["natrium_{}".format(taskNr)] = nutris[product["ProductId"]]["natrium"]
survey_df_tmp["protein_{}".format(taskNr)] = nutris[product["ProductId"]]["protein"]
survey_df_tmp["fiber_{}".format(taskNr)]= nutris[product["ProductId"]]["fiber"]
survey_df_tmp["health_percentage_{}".format(taskNr)] = nutris[product["ProductId"]]["health_percentage"]
survey_df_tmp["time_{}".format(taskNr)] = timings.loc[(timings["user_id"]==user_id) & (timings["task"]==str(taskNr)),"time"].iloc[0]
except:
survey_df_tmp["nutri_label_{}".format(taskNr)] = None
survey_df_tmp["nutri_score_{}".format(taskNr)] = None
survey_df_tmp["energy_{}".format(taskNr)] = None
survey_df_tmp["sugar_{}".format(taskNr)] = None
survey_df_tmp["sat_fat_{}".format(taskNr)] = None
survey_df_tmp["natrium_{}".format(taskNr)] = None
survey_df_tmp["protein_{}".format(taskNr)] = None
survey_df_tmp["fiber_{}".format(taskNr)]= None
survey_df_tmp["health_percentage_{}".format(taskNr)] = None
survey_df_tmp["time_{}".format(taskNr)] = None
survey_df = survey_df_tmp.combine_first(survey_df)
age_classes = {
0: "0.) < 19yrs",
1: "1.) 20 - 29 yrs",
2: "2.) 30 - 49 yrs",
3: "2.) 30 - 49 yrs",
4: "3.) 50 - 65 yrs",
5: "4.) > 65 yrs",
6: "4.) > 65 yrs"}
survey_df["age_class"] = survey_df["age"].apply(lambda x: safe_dict(x, age_classes))
ages = {
0: 18,
1: 25,
2: 35,
2: 45,
3: 57,
4: 72,
5: 85
}
survey_df["age"] = survey_df["age"].apply(lambda x: safe_dict(x, ages))
weights = {
"39-": 35,
"40-49": 45,
"50-59": 55,
"60-69": 65,
"70-79": 75,
"80-89": 85,
"90-99": 95,
"100-109": 105,
"110-119": 115,
"120-129": 125,
"130-139": 135,
"140-149": 145,
"150+": 155
}
survey_df["weight"] = survey_df["weight"].apply(lambda x: safe_dict(x, weights, False))
heights = {
"139-": 1.35,
"140-149": 1.45,
"150-159": 1.55,
"160-169": 1.65,
"170-179": 1.75,
"180-189": 1.85,
"190-199": 1.95,
"200-209": 2.05,
"210+": 2.15
}
survey_df["height"] = survey_df["height"].apply(lambda x: safe_dict(x, heights, False))
genders = {
"male": "0.) Male",
"female": "1.)Female"
}
survey_df["gender"] = survey_df["gender"].apply(lambda x: safe_dict(x, genders, False))
survey_df["bmi"] = survey_df["weight"] / (survey_df["height"] * survey_df["height"])
survey_df["bmi_class"] = survey_df["bmi"].apply(bmi_class)
diets = {
"No I don't follow a certain diet": "None",
"Nein, ich folge keiner bestimmten Diät": "None",
"I avoid certain foods because of an allergy or food intolerance": "Allergy / Intolerance",
"Ich vermeide bestimmte Lebensmittel wegen Allergie oder Unverträglichkeit": "Allergy / Intolerance",
"I eat vegetarian": "Vegiatrian / Vegan",
"Ich esse vegetarisch (ovo-lacto-vegetarisch, lacto-vegetarisch)": "Vegiatrian / Vegan",
"I eat vegan": "Vegiatrian / Vegan",
"Ich esse vegan": "Vegiatrian / Vegan",
"I avoid certain foods for ethical/cultural/religious reasons": "Cultural / Ethnical",
"Ich vermeide bestimmte Lebensmittel aus ethischen, kulturellen oder religiösen Gründen": "Cultural / Ethnical",
"I follow a high carbohydrate diet": "High Carb",
"Ich esse kohlenhydratreich": "High Carb",
"I follow a diet low in carbohydrates": "Low Carb",
"Ich esse kohlenhydrat-arm": "Low Carb",
"I follow a low fat or cholosterol diet": "Low Fat",
"Ich esse fettarm oder cholesterin-arm": "Low Fat",
"I follow a diet with reduced salt consumption": "Low Salt",
"Ich esse salz-reduziert": "Low Salt",
"I follow a diet low in protein": "Low Protein",
"Ich esse protein-arm": "Low Protein",
"I follow a diet rich in protein": "High Protein",
"Ich esse protein-reich": "High Protein",
"I follow an environmentally friendly / sustainable diet": "Sustainable",
"Ich ernähre mich umweltreundlich und nachhaltig": "Sustainable",
}
survey_df["diet"] = survey_df["diet"].apply(lambda x: safe_dict(x, diets, False))
educations = {
"Manditory School": "0:) primary education",
"Middle school": "0:) primary education",
"High school": "1.) secondary education",
"Vocational school": "1.) secondary education",
"master's diploma": "2.) tertiary education",
"College / University": "2.) tertiary education",
"Obligatorische Schule": "0:) primary education",
"Weiterführende Schule": "0:) primary education",
"Matura": "1.) secondary education",
"Berufsschule": "1.) secondary education",
"Meister- / eidg. Diplom": "2.) tertiary education",
"Studium": "2.) tertiary education",
}
survey_df["education"] = survey_df["education"].apply(lambda x: safe_dict(x, educations, False))
snack_frequencies = {
"sehr selten bis nie": "0.) never",
"never":"0.) never",
"once or twice per year":"0.) never",
"ca. monatlich":"1.) monthly",
"monthly":"1.) monthly",
"ca. wöchentlich":"2.) weekly",
"weekly":"2.) weekly",
"ca. 2-3 mal pro Woche":"2.) weekly",
"ca. 4-5 mal pro Woche":"3.) almost daily",
"daily":"3.) almost daily",
"ca. täglich":"3.) almost daily",
}
snack_frequencies_int = {
"sehr selten bis nie": 0,
"never":0,
"once or twice per year":0,
"ca. monatlich":1,
"monthly":1,
"ca. wöchentlich":4,
"weekly":4,
"ca. 2-3 mal pro Woche":10,
"ca. 4-5 mal pro Woche":20,
"daily":31,
"ca. täglich":31,
}
survey_df["snack_frequency_int"] = survey_df["snack_frequency"].apply(lambda x: safe_dict(x, snack_frequencies_int, False))
survey_df["snack_frequency"] = survey_df["snack_frequency"].apply(lambda x: safe_dict(x, snack_frequencies, False))
ar_frequencies = {
"Never used":"0.) Never",
"Noch nie benutz":"0.) Never",
"Tried once or twice":"1.) Few Times",
"Schon ein oder zwei Mal benutzt":"1.) Few Times",
"I use it sometimes":"2.) Sometimes",
"Ich benutze es hin und wieder privat":"2.) Sometimes",
"I worked with it on a project":"3.) Regularly",
"Ich habe an einem Projekt damit gearbeitet":"3.) Regularly",
"I use it regularly for private purpose":"3.) Regularly",
"Ich benutze es regelmäßig privat":"3.) Regularly",
"It is part of my job on a regular basis":"3.) Regularly",
"Ich komme auf der Arbeit regelmäßig damit in Kontakt":"3.) Regularly",
"I am an expert / developer in the field":"4.) Expert",
"Ich bin ein Experte / Entwickler auf dem Feld":"4.) Expert",
}
ar_frequencies_int = {
"Never used":0,
"Noch nie benutz":0,
"Tried once or twice":1,
"Schon ein oder zwei Mal benutzt":1,
"I use it sometimes":2,
"Ich benutze es hin und wieder privat":2,
"I worked with it on a project":3,
"Ich habe an einem Projekt damit gearbeitet":3,
"I use it regularly for private purpose":3,
"Ich benutze es regelmäßig privat":3,
"It is part of my job on a regular basis":3,
"Ich komme auf der Arbeit regelmäßig damit in Kontakt":3,
"I am an expert / developer in the field":4,
"Ich bin ein Experte / Entwickler auf dem Feld":4,
}
survey_df["ar_frequency_int"] = survey_df["ar_frequency"].apply(lambda x: safe_dict(x, ar_frequencies_int, False))
survey_df["ar_frequency"] = survey_df["ar_frequency"].apply(lambda x: safe_dict(x, ar_frequencies, False))
survey_df["BI_avg"] = survey_df[["BI1", "BI2","BI3"]].mean(axis=1, numeric_only=True)
survey_df["EE_avg"] = survey_df[["EE1", "EE2","EE3"]].mean(axis=1, numeric_only=True)
survey_df["FL_avg"] = survey_df[["FL2","FL3"]].mean(axis=1, numeric_only=True)
survey_df["HM_avg"] = survey_df[["HM1", "HM2"]].mean(axis=1, numeric_only=True)
survey_df["IE_avg"] = survey_df[["IE1", "IE2"]].mean(axis=1, numeric_only=True)
survey_df["PE_avg"] = survey_df[["PE1", "PE2","PE3"]].mean(axis=1, numeric_only=True)
survey_df["PI_avg"] = survey_df[["PI1", "PI2","PI3"]].mean(axis=1, numeric_only=True)
survey_df["SI_avg"] = survey_df[["SI1", "SI2","SI3"]].mean(axis=1, numeric_only=True)
survey_df.fillna(value=pd.np.nan, inplace=True)
return survey_df
def render_box_per_col(col, survey_df):
is_test = survey_df["group"] == "Test"
is_control = survey_df["group"] == "Control"
data = []
data.append(go.Box(
x = survey_df[col][is_test],
name="test",
marker = dict(
color = 'rgb(7,40,89)'),
line = dict(
color = 'rgb(7,40,89)')
))
data.append(go.Box(
x = survey_df[col][is_control],
name="control",
marker = dict(
color = 'rgb(107,174,214)'),
line = dict(
color = 'rgb(107,174,214)')
))
graph = dcc.Graph(
figure = go.Figure(
data = data,
layout = go.Layout(
showlegend=True,
legend=go.layout.Legend(
x=0,
y=1.0
),
margin=go.layout.Margin(l=40, r=0, t=40, b=30)
)
),
style={'height': 150},
id='box_{}'.format(col)
)
graph_div = html.Div([graph],
style={'padding-top': '20',
'padding-bottom': '20'})
return graph_div
def data_per_col(col, survey_df):
is_test = survey_df["group"] == "Test"
is_control = survey_df["group"] == "Control"
data = [
go.Histogram(
x = survey_df[col][is_test].sort_values(),
name="test",
opacity=0.75,
marker = dict(
color = 'rgb(7,40,89)'),
),
go.Histogram(
x = survey_df[col][is_control].sort_values(),
name="control",
opacity=0.75,
marker = dict(
color = 'rgb(107,174,214)'),
)
]
return data
def render_hist_per_col(col, survey_df):
data = data_per_col(col, survey_df)
graph = dcc.Graph(
figure = go.Figure(
data = data,
layout = go.Layout(
showlegend=True,
legend=go.layout.Legend(
x=0,
y=1.0
),
margin=go.layout.Margin(l=40, r=0, t=40, b=30)
)
),
style={'height': 300}
)
graph_div = html.Div([graph],
style={'padding-top': '20',
'padding-bottom': '20'})
return graph_div
def render_table(survey_df):
table = dash_table.DataTable(
id='table',
columns=[{"name": i, "id": i} for i in survey_df.columns],
data=survey_df.to_dict("rows"),
)
return table
#def load_user_tracking(user_id, task_id):
# filename = tracking_files[user_id][task_id]
def calc_p_whitney(col, s, ns):
Rg = col.rank()
nt = col[s].count()
nc = col[ns].count()
if (Rg == Rg.iloc[0]).all():
return Rg[s].sum() - nt * (nt + 1) / 2, 0.5, nt, nc
u, p = stats.mannwhitneyu(Rg[s], Rg[ns])
return p
# def calc_p_whitney(colname, survey_df):
# col = survey_df[colname]
# istest = survey_df["group"]=="Test"
# iscontrol = survey_df["group"]=="Control"
# Rg = col.rank()
#
# nt = col[istest].count()
# nc = col[iscontrol].count()
#
# if (Rg == Rg.iloc[0]).all():
# return Rg[istest].sum() - nt * (nt + 1) / 2, 0.5, nt, nc
#
# u, p = mannwhitneyu(Rg[istest], Rg[iscontrol])
# return u, p, nt, nc
def calc_p_t(colname, survey_df):
col = survey_df[colname]
istest = survey_df["group"]=="Test"
iscontrol = survey_df["group"]=="Control"
t, p = ttest_ind(col[istest].values, col[iscontrol].values, axis=0, nan_policy='omit')
return t, p
def table_group(task_nr, survey_df, header):
istest = survey_df["group"] == "Test"
iscontrol = survey_df["group"] == "Control"
isoverweight = survey_df["bmi"] > 25
isnormal = survey_df["bmi"] <= 25
iseducated = survey_df["bmi"] > 25
isliterate = survey_df["FL_avg"] > 4.5
isilliterate = survey_df["FL_avg"] <= 4.5
cols = ["nutri_score",
"energy",
"sat_fat",
"sugar",
"natrium",
"protein",
"fiber",
"health_percentage",
"time"]
data = pd.DataFrame()
for col in cols:
col_name = "{}_{}".format(col, task_nr)
data.loc[col, "N Total"] = "[{}]".format(int(data.loc[col, "N Test"] + data.loc[col, "N Control"]))
data.loc[col, "mean Total"] = "{:.2f}".format(survey_df[col_name].mean())
data.loc[col, "SD Total"] = "({:.2f})".format(survey_df[col_name].std())
p = calc_p_whitney(survey_df["group"], istest, iscontrol)
data.loc[col, "p group"] = "{:.4f}".format(p)
data.loc[col, "N Test"] = "[{}]".format(int(len(survey_df[istest])))
data.loc[col, "mean Test"] = "{:.2f}".format(survey_df[col_name][istest].mean())
data.loc[col, "SD Test"] = "({:.2f})".format(survey_df[col_name][istest].std())
data.loc[col, "N Control"] = "[{}]".format(int(len(survey_df[iscontrol])))
data.loc[col, "mean Control"] = "{:.2f}".format(survey_df[col_name][iscontrol].mean())
data.loc[col, "SD Control"] = "({:.2f})".format(survey_df[col_name][iscontrol].std())
p = calc_p_whitney(survey_df["FL_avg"], isliterate, isilliterate)
data.loc[col, "p FL"] = "{:.4f}".format(p)
data.loc[col, "N FL>4.5"] = "[{}]".format(int(len(survey_df[isliterate])))
data.loc[col, "mean FL>4.5"] = "{:.2f}".format(survey_df[col_name][isliterate].mean())
data.loc[col, "SD FL>4.5"] = "({:.2f})".format(survey_df[col_name][isliterate].std())
data.loc[col, "N FL<=4.5"] = "[{}]".format(int(len(survey_df[isilliterate])))
data.loc[col, "mean FL<=4.5"] = "{:.2f}".format(survey_df[col_name][isilliterate].mean())
data.loc[col, "SD FL<=4.5"] = "({:.2f})".format(survey_df[col_name][isilliterate].std())
p = calc_p_whitney(survey_df["FL_avg"], isliterate, isilliterate)
data.loc[col, "p FL"] = "{:.4f}".format(p)
data.loc[col, "N FL>4.5"] = "[{}]".format(int(len(survey_df[isliterate])))
data.loc[col, "mean FL>4.5"] = "{:.2f}".format(survey_df[col_name][isliterate].mean())
data.loc[col, "SD FL>4.5"] = "({:.2f})".format(survey_df[col_name][isliterate].std())
data.loc[col, "N FL<=4.5"] = "[{}]".format(int(len(survey_df[isilliterate])))
data.loc[col, "mean FL<=4.5"] = "{:.2f}".format(survey_df[col_name][isilliterate].mean())
data.loc[col, "SD FL<=4.5"] = "({:.2f})".format(survey_df[col_name][isilliterate].std())
data["index"] = data.index
data_dict = data.to_dict("rows")
table = dash_table.DataTable(
id='table',
columns=[ {"name": "", "id": "index"},
{"name": "u", "id": "u"},
{"name": "p", "id": "p"},
{"name": "Total mean", "id": "mean Total"},
{"name": "(SD)", "id": "SD Total"},
{"name": "[N]", "id": "Total N"},
{"name": "Test mean", "id": "mean Test"},
{"name": "(SD)", "id": "SD Test"},
{"name": "[N]", "id": "Test N"},
{"name": "Control mean", "id": "mean Control"},
{"name": "(SD)", "id": "SD Control"},
{"name": "[N]", "id": "Control N"}],
data=data_dict,
style_as_list_view=True,
style_cell={'padding': '5px'},
style_header={
'backgroundColor': 'white',
'fontWeight': 'bold'
},
style_cell_conditional=[
{
'if': {'column_id': c},
'textAlign': 'left'
} for c in ['index','SD Total', 'SD Test', 'SD Control', 'Total N', 'Test N', 'Control N']
],
)
ret_div = html.Div([
html.H1("Task {}".format(task_nr)),
html.H2(header),
html.Div( [table],
style={ 'padding-top': '10',
'padding-bottom': '30',
'padding-left': '30',
'padding-right': '5'}),
render_box_per_col("nutri_score_{}".format(task_nr), survey_df),
render_hist_per_col("nutri_label_{}".format(task_nr), survey_df.sort_values(by="nutri_label_{}".format(task_nr)))
])
return ret_div
def creat_mean_desc(col, survey_df, header = None):
data = pd.DataFrame()
istest = survey_df["group"] == "Test"
iscontrol = survey_df["group"] == "Control"
if isinstance(header, str):
title = html.H3(header)
else:
title = html.H3(col)
ret_div = html.Div([title,
html.P("Total mean (SD) \t\t {:.2f} ({:.2f})".format(survey_df[col].mean(), survey_df[col].std())),
html.P("Test mean (SD) \t\t {:.2f} ({:.2f})".format(survey_df[col][istest].mean(), survey_df[col][istest].std())),
html.P("Control mean (SD) \t\t {:.2f} ({:.2f})".format(survey_df[col][iscontrol].mean(), survey_df[col][iscontrol].std())),
render_box_per_col(col, survey_df)])
return ret_div
def create_count_desc(col, survey_df, header=None):
data = pd.DataFrame()
istest = survey_df["group"] == "Test"
iscontrol = survey_df["group"] == "Control"
survey_df.loc[survey_df[col].isna(),col] = "Missing"
data["count Total"] = survey_df[col].value_counts()
data["% Total"] = (data["count Total"] / data["count Total"].sum() * 100).apply(lambda x : "({:.1f}%)".format(x))
data.loc["Total", "count Total"] = data["count Total"].sum()
data["count Test"] = survey_df[col][istest].value_counts()
data["% Test"] = (data["count Test"] / data["count Test"].sum() * 100).apply(lambda x : "({:.1f}%)".format(x))
data.loc["Total", "count Test"] = data["count Test"].sum()
data["count Control"] = survey_df[col][iscontrol].value_counts()
data["% Control"] = (data["count Control"] / data["count Control"].sum() * 100).apply(lambda x : "({:.1f}%)".format(x))
data.loc["Total", "count Control"] = data["count Control"].sum()
data.loc["Total", ["% Total","% Test","% Control"]] = ""
data["index"] = data.index
data = data.sort_index()
data_dict = data.to_dict("rows")
table = dash_table.DataTable(
id='table',
columns=[ {"name": "", "id": "index"},
{"name": "Total N", "id": "count Total"},
{"name": "(%)", "id": "% Total"},
{"name": "Test N", "id": "count Test"},
{"name": "(%)", "id": "% Test"},
{"name": "Control N", "id": "count Control"},
{"name": "(%)", "id": "% Control"},],
data=data_dict,
style_as_list_view=True,
style_cell={'padding': '5px'},
style_header={
'backgroundColor': 'white',
'fontWeight': 'bold'
},
style_cell_conditional=[
{
'if': {'column_id': c},
'textAlign': 'left'
} for c in ['index', '% Total', '% Test', '% Control']
],
)
if isinstance(header, str):
title = html.H3(header)
else:
title = html.H3(col)
ret_div = html.Div([title,
html.Div( [table],
style={ 'padding-top': '10',
'padding-bottom': '30',
'padding-left': '30',
'padding-right': '5'}),
render_hist_per_col(col, survey_df),
])
return ret_div
def get_question_text_save(col, questions_df, question_ids):
try:
question_text = questions_df[" question.text,"][question_ids[col]]
except:
question_text = "Error: Question wasn't found"
return question_text
def create_survey(cols, survey_df, header):
questionsfile = os.path.join(BASEPATH, "questionlayout-evaluation.csv")
questions_df = pd.read_csv(questionsfile, sep=";", index_col="question.id")
questions_df["time_1"] = "task 1"
questions_df["time_2"] = "task 2"
questions_df["time_3"] = "task 3"
questions_df["time_4"] = "task 4"
question_ids = {
"IE1":"jcruLQD1jtsb",
"IE2":"eaTgLd8mTqIl",
"PE1":"q0mA3PRRFjx7",
"PE2":"sBItcnzLbeab",
"PE3":"HNBvOMYBB0aG",
"EE1":"MEMNKBeL1Yx1",
"EE2":"erPaRi4mPyPG",
"EE3":"QVMeswBQSWAi",
"SI1":"xdCMMXgxnem1",
"SI2":"wfA9uqPz8cRt",
"SI3":"xUlfUW6JGEav",
"HM1":"JYEh0RF8Fm8b",
"HM2":"DuGG9VdyhxCd",
"PI1":"Y4v77TAeZzKs",
"PI2":"QVzNIkgWgGxB",
"PI3":"BQXqCdJgdxle",
"BI1":"b4YNQSqEHFaE",
"BI2":"GfV0SwI2TmuK",
"BI3":"PEWOeMEEayNA",
"FL1":"Wiq2wP97n7RO",
"FL2":"zDVqi1Ti9Nwq",
"FL3":"WeELc4DWjE6P",
"time_1":"time_1",
"time_2":"time_2",
"time_3":"time_3",
"time_4":"time_4",
}
question_texts = {col: get_question_text_save(col, questions_df, question_ids) for col in cols}
question_texts["Average"] = "--- Average ---"
survey_df_tmp = survey_df.loc[:,cols]
survey_df_tmp.loc[:,"Average"] = survey_df_tmp.mean(axis=1,numeric_only=True)
survey_df_tmp.loc[:,"group"] = survey_df.loc[:,"group"]
cols.append("Average")
data =
|
pd.DataFrame()
|
pandas.DataFrame
|
from collections import abc, deque
from decimal import Decimal
from io import StringIO
from warnings import catch_warnings
import numpy as np
from numpy.random import randn
import pytest
from pandas.core.dtypes.dtypes import CategoricalDtype
import pandas as pd
from pandas import (
Categorical,
DataFrame,
DatetimeIndex,
Index,
MultiIndex,
Series,
concat,
date_range,
read_csv,
)
import pandas._testing as tm
from pandas.core.arrays import SparseArray
from pandas.core.construction import create_series_with_explicit_dtype
from pandas.tests.extension.decimal import to_decimal
@pytest.fixture(params=[True, False])
def sort(request):
"""Boolean sort keyword for concat and DataFrame.append."""
return request.param
class TestConcatenate:
def test_concat_copy(self):
df = DataFrame(np.random.randn(4, 3))
df2 = DataFrame(np.random.randint(0, 10, size=4).reshape(4, 1))
df3 = DataFrame({5: "foo"}, index=range(4))
# These are actual copies.
result = concat([df, df2, df3], axis=1, copy=True)
for b in result._mgr.blocks:
assert b.values.base is None
# These are the same.
result = concat([df, df2, df3], axis=1, copy=False)
for b in result._mgr.blocks:
if b.is_float:
assert b.values.base is df._mgr.blocks[0].values.base
elif b.is_integer:
assert b.values.base is df2._mgr.blocks[0].values.base
elif b.is_object:
assert b.values.base is not None
# Float block was consolidated.
df4 = DataFrame(np.random.randn(4, 1))
result = concat([df, df2, df3, df4], axis=1, copy=False)
for b in result._mgr.blocks:
if b.is_float:
assert b.values.base is None
elif b.is_integer:
assert b.values.base is df2._mgr.blocks[0].values.base
elif b.is_object:
assert b.values.base is not None
def test_concat_with_group_keys(self):
df = DataFrame(np.random.randn(4, 3))
df2 = DataFrame(np.random.randn(4, 4))
# axis=0
df = DataFrame(np.random.randn(3, 4))
df2 = DataFrame(np.random.randn(4, 4))
result = concat([df, df2], keys=[0, 1])
exp_index = MultiIndex.from_arrays(
[[0, 0, 0, 1, 1, 1, 1], [0, 1, 2, 0, 1, 2, 3]]
)
expected = DataFrame(np.r_[df.values, df2.values], index=exp_index)
tm.assert_frame_equal(result, expected)
result = concat([df, df], keys=[0, 1])
exp_index2 = MultiIndex.from_arrays([[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 1, 2]])
expected = DataFrame(np.r_[df.values, df.values], index=exp_index2)
tm.assert_frame_equal(result, expected)
# axis=1
df = DataFrame(np.random.randn(4, 3))
df2 = DataFrame(np.random.randn(4, 4))
result = concat([df, df2], keys=[0, 1], axis=1)
expected = DataFrame(np.c_[df.values, df2.values], columns=exp_index)
tm.assert_frame_equal(result, expected)
result = concat([df, df], keys=[0, 1], axis=1)
expected = DataFrame(np.c_[df.values, df.values], columns=exp_index2)
tm.assert_frame_equal(result, expected)
def test_concat_keys_specific_levels(self):
df = DataFrame(np.random.randn(10, 4))
pieces = [df.iloc[:, [0, 1]], df.iloc[:, [2]], df.iloc[:, [3]]]
level = ["three", "two", "one", "zero"]
result = concat(
pieces,
axis=1,
keys=["one", "two", "three"],
levels=[level],
names=["group_key"],
)
tm.assert_index_equal(result.columns.levels[0], Index(level, name="group_key"))
tm.assert_index_equal(result.columns.levels[1], Index([0, 1, 2, 3]))
assert result.columns.names == ["group_key", None]
def test_concat_dataframe_keys_bug(self, sort):
t1 = DataFrame(
{"value": Series([1, 2, 3], index=Index(["a", "b", "c"], name="id"))}
)
t2 = DataFrame({"value": Series([7, 8], index=Index(["a", "b"], name="id"))})
# it works
result = concat([t1, t2], axis=1, keys=["t1", "t2"], sort=sort)
assert list(result.columns) == [("t1", "value"), ("t2", "value")]
def test_concat_series_partial_columns_names(self):
# GH10698
foo = Series([1, 2], name="foo")
bar = Series([1, 2])
baz = Series([4, 5])
result = concat([foo, bar, baz], axis=1)
expected = DataFrame(
{"foo": [1, 2], 0: [1, 2], 1: [4, 5]}, columns=["foo", 0, 1]
)
tm.assert_frame_equal(result, expected)
result =
|
concat([foo, bar, baz], axis=1, keys=["red", "blue", "yellow"])
|
pandas.concat
|
import os.path
from glob import glob
import pandas as pd
data_dir = 'data'
lang_files = sorted(glob(os.path.join('..', data_dir, '*_data.csv')))
marker_files = sorted(glob(os.path.join('..', data_dir, '*_markers.csv')))
# Файлов для языков должно быть столько же, сколько файлов для маркеров
assert len(lang_files) == len(
marker_files), "Количество файлов для языков и маркеров не совпадает"
# Наборы полей (столбцов) во всех файлах типа languagename_data должны быть идентичны
lang_field_reference = []
for i, lang_file in enumerate(lang_files):
lang_df = pd.read_csv(lang_file, sep='\t', encoding='utf-8')
lang_fields = lang_df.columns.tolist()
if i == 0:
lang_field_reference = lang_fields
else:
if lang_field_reference != lang_fields:
print(
f"Наборы полей (столбцов) в языковых файлах не совпадают: {lang_file} и {lang_files[0]}")
# Наборы полей (столбцов) во всех файлах типа languagename_markers должны быть идентичны
marker_field_reference = []
for i, marker_file in enumerate(marker_files):
marker_df = pd.read_csv(marker_file, sep='\t', encoding='utf-8')
marker_fields = marker_df.columns.tolist()
if i == 0:
marker_field_reference = marker_fields
else:
if marker_field_reference != marker_fields:
print(
f"Наборы полей (столбцов) в файлах с маркерами не совпадают: {marker_file} и {marker_files[0]}")
sentences = pd.read_csv(os.path.join(
'..', data_dir, '03_sentences.csv'), sep='\t')
languages = pd.read_csv(os.path.join(
'..', data_dir, '01_languages.csv'), sep='\t')
# В файлах типа languagename_data в столбце “stimulus_no” всегда стоит какое-то целое число в интервале от 1 до 54
for lang_file in lang_files:
lang_df = pd.read_csv(lang_file, sep='\t', encoding='utf-8')
for stimulus_no in lang_df.stimulus_no:
if stimulus_no not in range(1, 55):
print(
f"В файле {lang_file} неверное занчение в столбце stimulus_no: {stimulus_no} (должно быть целое число в интервале от 1 до 54)")
# В файлах типа languagename_data в столбце “status” всегда либо main, либо alternate
for lang_file in lang_files:
lang_df = pd.read_csv(lang_file, sep='\t', encoding='utf-8')
for status in lang_df.status:
if status not in {'main', 'alternate'}:
print(
f"В файле {lang_file} неверное занчение в столбце status: {status} (должно быть main или alternate)")
# В файлах типа languagename_data на каждую пару language_no & stimulus_no должна быть ровно одна строка, где status = “main”
for lang_file in lang_files:
lang_df = pd.read_csv(lang_file, sep='\t', encoding='utf-8')
for stimulus_nos in lang_df.stimulus_no.unique():
lang_df_subset = lang_df[lang_df.stimulus_no == stimulus_nos]
if lang_df_subset.status.value_counts()['main'] != 1:
print(
f"В файле {lang_file} стимул {stimulus_nos} имеет больше или меньше одной строки с status = main")
# В файлах типа languagename_data в каждой строке в столбце “causal marker” должно что-то быть
for lang_file in lang_files:
lang_df = pd.read_csv(lang_file, sep='\t', encoding='utf-8')
for i, causal_marker in enumerate(lang_df.causal_marker):
if causal_marker == '' or pd.isnull(causal_marker):
print(
f"В файле {lang_file} нет заполнения в столбце causal_marker в строке {i + 1}")
# В файлах типа languagename_data, если в них есть больше одной строки с одинаковой парой language_no & stimulus_no,
# то во всех этих строках должны быть разные записи в столбце “causal marker” (исключение: запись “n.a.”)
for lang_file in lang_files:
lang_df =
|
pd.read_csv(lang_file, sep='\t', encoding='utf-8')
|
pandas.read_csv
|
import requests
import pandas as pd
import collections
import logging
from pathlib import Path
log = logging.getLogger(Path(__file__).stem)
class WorldBank:
def __init__(self):
self.name = 'world_bank'
self.table = 'country_full'
self.data = None
self.steps = None
def get_data(self):
base_url = 'http://api.worldbank.org/v2/countries/all/indicators/'
series_codes = ['NY.ADJ.NNTY.PC.CD', 'NY.ADJ.DKAP.CD', 'NY.ADJ.AEDU.CD',
'NY.ADJ.NNAT.CD', 'AG.LND.AGRI.ZS', 'VC.BTL.DETH',
'GC.DOD.TOTL.GD.ZS', 'SP.REG.BRTH.RU.ZS', 'SP.REG.BRTH.UR.ZS',
'FP.CPI.TOTL', 'per_si_allsi.cov_pop_tot',
'per_sa_allsa.cov_pop_tot', 'SH.XPD.CHEX.GD.ZS', 'IC.BUS.EASE.XQ',
'SE.TER.CUAT.BA.ZS', 'SL.EMP.TOTL.SP.MA.ZS', 'NE.EXP.GNFS.ZS',
'BX.KLT.DINV.WD.GD.ZS', 'AG.LND.FRST.ZS', 'NY.GDP.PCAP.KD',
'NY.GDP.MKTP.CD', 'NY.GDP.PCAP.PP.CD', 'SI.DST.10TH.10',
'IT.NET.USER.ZS', 'SL.TLF.ACTI.ZS', 'SE.ADT.LITR.MA.ZS',
'MS.MIL.XPND.GD.ZS', 'SH.STA.BASS.ZS', 'SP.POP.TOTL.MA.ZS'
]
params = {
'format': "json",
'page': 1,
'date': '2015:2015'
}
full_df = pd.DataFrame(columns=['indicator', 'country', 'value'])
for code in series_codes:
r = requests.get(base_url + code, params=params, verify=False)
json = r.json()[1]
meta = r.json()[0]
log.info(f'retrieving {code}: {meta["pages"]} to go')
data = [self.flatten(i) for i in json]
df =
|
pd.DataFrame(data)
|
pandas.DataFrame
|
#<EMAIL>
import os
import sys
import time
import yaml
import pandas as pd
from tqdm import tqdm
from collections import OrderedDict
import cv2
from torch import torch, optim, utils
torch.backends.cudnn.benchmark = True
device = torch.device("cuda:0")
import arch
import utilx
trainmap = 'Tr2' #Tr1 Tr2
valmap = 'Va1' #Va1 Va2
config = {
'data_dir' : ['dataset/'+trainmap[:-1]+'Set/', 'dataset/'+valmap[:-1]+'Set/'],
'data_info' : ['dataset/'+trainmap+'/data_infon.yml', 'dataset/'+valmap+'/data_infon.yml'],
'input' : ['dvs_f', 'dvs_l', 'dvs_ri', 'dvs_r', 'rgb_f', 'rgb_l', 'rgb_ri', 'rgb_r'],
'task' : ['depth_f', 'depth_l', 'depth_ri', 'depth_r', 'segmentation_f_min', 'segmentation_l_min', 'segmentation_ri_min', 'segmentation_r_min'],
'mod_dir' : 'model/',
'arch' : 'A0', #A0 or A1
}
#load data info
with open(config['data_info'][0], 'r') as g:
info = yaml.load(g, Loader=yaml.FullLoader)
with open(config['data_info'][1], 'r') as g:
info_val = yaml.load(g, Loader=yaml.FullLoader)
#directory to save the model
config['mod_dir'] += config['arch']
os.makedirs(config['mod_dir'], exist_ok=True)
def train(batches, model, lossf, metricf, optimizer):
#training mode
model.train()
#variable to save the scores
score = {'total_loss': utilx.AverageMeter(),
'total_metric': utilx.AverageMeter(),
'tot_DE_loss': utilx.AverageMeter(),
'tot_DE_metric': utilx.AverageMeter(),
'tot_SS_loss': utilx.AverageMeter(),
'tot_SS_metric': utilx.AverageMeter()}
#for visualization
prog_bar = tqdm(total=len(batches))
for batch_X, batch_Y_true, _ in batches:
#move inputs and GT to the same device as the model
for i in range(len(batch_X)):
batch_X[i] = batch_X[i].double().to(device)
for i in range(len(batch_Y_true)):
batch_Y_true[i] = batch_Y_true[i].double().to(device)
#forward pass
batch_Y_pred = model(batch_X)
#Loss and Metric calculation
tot_DE_loss = lossf(batch_Y_pred[0], batch_Y_true[0])
tot_DE_loss = torch.add(tot_DE_loss, lossf(batch_Y_pred[1], batch_Y_true[1]))
tot_DE_loss = torch.add(tot_DE_loss, lossf(batch_Y_pred[2], batch_Y_true[2]))
tot_DE_loss = torch.div(torch.add(tot_DE_loss, lossf(batch_Y_pred[3], batch_Y_true[3])), 4) #average across 4 views
tot_DE_metric = metricf(batch_Y_pred[0], batch_Y_true[0])
tot_DE_metric = torch.add(tot_DE_metric, metricf(batch_Y_pred[1], batch_Y_true[1]))
tot_DE_metric = torch.add(tot_DE_metric, metricf(batch_Y_pred[2], batch_Y_true[2]))
tot_DE_metric = torch.div(torch.add(tot_DE_metric, metricf(batch_Y_pred[3], batch_Y_true[3])), 4) #average across 4 views
tot_SS_loss = lossf(batch_Y_pred[4], batch_Y_true[4])
tot_SS_loss = torch.add(tot_SS_loss, lossf(batch_Y_pred[5], batch_Y_true[5]))
tot_SS_loss = torch.add(tot_SS_loss, lossf(batch_Y_pred[6], batch_Y_true[6]))
tot_SS_loss = torch.div(torch.add(tot_SS_loss, lossf(batch_Y_pred[7], batch_Y_true[7])), 4) #dirata-rata dari 4 view
tot_SS_metric = metricf(batch_Y_pred[4], batch_Y_true[4])
tot_SS_metric = torch.add(tot_SS_metric, metricf(batch_Y_pred[5], batch_Y_true[5]))
tot_SS_metric = torch.add(tot_SS_metric, metricf(batch_Y_pred[6], batch_Y_true[6]))
tot_SS_metric = torch.div(torch.add(tot_SS_metric, metricf(batch_Y_pred[7], batch_Y_true[7])), 4) #dirata-rata dari 4 view
total_loss = torch.add(tot_DE_loss, tot_SS_loss)
total_metric = torch.add(tot_DE_metric, torch.sub(1,tot_SS_metric))
#update weights
optimizer.zero_grad()
total_loss.backward()
optimizer.step()
#to be saved
score['total_loss'].update(total_loss.item(), 1)
score['total_metric'].update(total_metric.item(), 1)
score['tot_DE_loss'].update(tot_DE_loss.item(), 1)
score['tot_DE_metric'].update(tot_DE_metric.item(), 1)
score['tot_SS_loss'].update(tot_SS_loss.item(), 1)
score['tot_SS_metric'].update(tot_SS_metric.item(), 1)
postfix = OrderedDict([('t_total_l', score['total_loss'].avg),
('t_total_m', score['total_metric'].avg),
('t_DE_l', score['tot_DE_loss'].avg),
('t_DE_m', score['tot_DE_metric'].avg),
('t_SS_l', score['tot_SS_loss'].avg),
('t_SS_m', score['tot_SS_metric'].avg)])
prog_bar.set_postfix(postfix)
prog_bar.update(1)
prog_bar.close()
return postfix
def validate(batches, model, lossf, metricf):
#validation mode
model.eval()
#variable to save the scores
score = {'total_loss': utilx.AverageMeter(),
'total_metric': utilx.AverageMeter(),
'tot_DE_loss': utilx.AverageMeter(),
'tot_DE_metric': utilx.AverageMeter(),
'tot_SS_loss': utilx.AverageMeter(),
'tot_SS_metric': utilx.AverageMeter()}
#for visualization
prog_bar = tqdm(total=len(batches))
with torch.no_grad():
for batch_X, batch_Y_true, _ in batches:
#move inputs and GT to the same device as the model
for i in range(len(batch_X)):
batch_X[i] = batch_X[i].double().to(device)
for i in range(len(batch_Y_true)):
batch_Y_true[i] = batch_Y_true[i].double().to(device)
#forward pass
batch_Y_pred = model(batch_X)
#Loss and Metric calculation
tot_DE_loss = lossf[0](batch_Y_pred[0], batch_Y_true[0])
tot_DE_loss = torch.add(tot_DE_loss, lossf[0](batch_Y_pred[1], batch_Y_true[1]))
tot_DE_loss = torch.add(tot_DE_loss, lossf[0](batch_Y_pred[2], batch_Y_true[2]))
tot_DE_loss = torch.div(torch.add(tot_DE_loss, lossf[0](batch_Y_pred[3], batch_Y_true[3])), 4) #average across 4 views
tot_DE_metric = metricf[0](batch_Y_pred[0], batch_Y_true[0])
tot_DE_metric = torch.add(tot_DE_metric, metricf[0](batch_Y_pred[1], batch_Y_true[1]))
tot_DE_metric = torch.add(tot_DE_metric, metricf[0](batch_Y_pred[2], batch_Y_true[2]))
tot_DE_metric = torch.div(torch.add(tot_DE_metric, metricf[0](batch_Y_pred[3], batch_Y_true[3])), 4) #average across 4 views
tot_SS_loss = lossf[1](batch_Y_pred[4], batch_Y_true[4])
tot_SS_loss = torch.add(tot_SS_loss, lossf[1](batch_Y_pred[5], batch_Y_true[5]))
tot_SS_loss = torch.add(tot_SS_loss, lossf[1](batch_Y_pred[6], batch_Y_true[6]))
tot_SS_loss = torch.div(torch.add(tot_SS_loss, lossf[1](batch_Y_pred[7], batch_Y_true[7])), 4) #dirata-rata dari 4 view
tot_SS_metric = metricf[1](batch_Y_pred[4], batch_Y_true[4])
tot_SS_metric = torch.add(tot_SS_metric, metricf[1](batch_Y_pred[5], batch_Y_true[5]))
tot_SS_metric = torch.add(tot_SS_metric, metricf[1](batch_Y_pred[6], batch_Y_true[6]))
tot_SS_metric = torch.div(torch.add(tot_SS_metric, metricf[1](batch_Y_pred[7], batch_Y_true[7])), 4) #dirata-rata dari 4 view
total_loss = torch.add(tot_DE_loss, tot_SS_loss)
total_metric = torch.add(tot_DE_metric, torch.sub(1,tot_SS_metric))
#to be saved
score['total_loss'].update(total_loss.item(), 1)
score['total_metric'].update(total_metric.item(), 1)
score['tot_DE_loss'].update(tot_DE_loss.item(), 1)
score['tot_DE_metric'].update(tot_DE_metric.item(), 1)
score['tot_SS_loss'].update(tot_SS_loss.item(), 1)
score['tot_SS_metric'].update(tot_SS_metric.item(), 1)
postfix = OrderedDict([('v_total_l', score['total_loss'].avg),
('v_total_m', score['total_metric'].avg),
('v_DE_l', score['tot_DE_loss'].avg),
('v_DE_m', score['tot_DE_metric'].avg),
('v_SS_l', score['tot_SS_loss'].avg),
('v_SS_m', score['tot_SS_metric'].avg)])
prog_bar.set_postfix(postfix)
prog_bar.update(1)
prog_bar.close()
return postfix
#MAIN FUNCTION
def main():
#IMPORT MODEL ARCHITECTURE
if config['arch'] == 'A0':
model = arch0.A0()
elif config['arch'] == 'A1':
model = arch0.A1()
else:
sys.exit("ARCH NOT FOUND............................")
model.double().to(device) #load model ke CUDA chace memory
#loss and metric function
lossf = [utilx.HuberLoss().to(device), utilx.BCEDiceLoss().to(device)]
metricf = [utilx.L1Loss().to(device), utilx.IOUScore().to(device)]
#optimizer and learning rate scheduler
params = filter(lambda p: p.requires_grad, model.parameters())
optima = optim.SGD(params, lr=0.1, momentum=0.9, weight_decay=0.0001)
scheduler = optim.lr_scheduler.ReduceLROnPlateau(optima, mode='min', factor=0.5, patience=5, min_lr=0.00001)
#create batch of train and val data
train_dataset = utilx.datagen(file_ids=info['train_idx'], config=config, data_info=info, input_dir=config['data_dir'][0])
train_batches = utils.data.DataLoader(train_dataset,
batch_size=config['tensor_dim'][0],
shuffle=True,
num_workers=4,
drop_last=False)
val_dataset = utilx.datagen(file_ids=info_val['val_idx'], config=config, data_info=info_val, input_dir=config['data_dir'][1])
val_batches = utils.data.DataLoader(val_dataset,
batch_size=config['tensor_dim'][0],
shuffle=False,
num_workers=4,
drop_last=False)
#create training log
log = OrderedDict([
('epoch', []),
('lrate', []),
('train_total_loss', []),
('val_total_loss', []),
('train_total_metric', []),
('val_total_metric', []),
('train_depth_loss', []),
('val_depth_loss', []),
('train_depth_metric', []),
('val_depth_metric', []),
('train_seg_loss', []),
('val_seg_loss', []),
('train_seg_metric', []),
('val_seg_metric', []),
('best_model', []),
('stop_counter', []),
('elapsed_time', []),
])
#LOOP
lowest_monitored_score = float('inf')
stop_count = 35
while True:
print('\n=======---=======---=======Epoch:%.4d=======---=======---=======' % (epoch))
print("current lr: ", optima.param_groups[0]['lr'])
#train - val
start_time = time.time()
train_log = train(batches=train_batches, model=model, lossf=lossf, metricf=metricf, optimizer=optima)
val_log = validate(batches=val_batches, model=model, lossf=lossf, metricf=metricf)
elapsed_time = time.time() - start_time
#update learning rate
scheduler.step(val_log['v_total_m']) #parameter acuan reduce LR adalah val_total_metric
log['epoch'].append(epoch+1)
log['lrate'].append(current_lr)
log['train_total_loss'].append(train_log['t_total_l'])
log['val_total_loss'].append(val_log['v_total_l'])
log['train_total_metric'].append(train_log['t_total_m'])
log['val_total_metric'].append(val_log['v_total_m'])
log['train_depth_loss'].append(train_log['t_DE_l'])
log['val_depth_loss'].append(val_log['v_DE_l'])
log['train_depth_metric'].append(train_log['t_DE_m'])
log['val_depth_metric'].append(val_log['v_DE_m'])
log['train_seg_loss'].append(train_log['t_SS_l'])
log['val_seg_loss'].append(val_log['v_SS_l'])
log['train_seg_metric'].append(train_log['t_SS_m'])
log['val_seg_metric'].append(val_log['v_SS_m'])
log['elapsed_time'].append(elapsed_time)
print('| t_total_l: %.4f | t_total_m: %.4f | t_DE_l: %.4f | t_DE_m: %.4f | t_SS_l: %.4f | t_SS_m: %.4f |'
% (train_log['t_total_l'], train_log['t_total_m'], train_log['t_DE_l'], train_log['t_DE_m'], train_log['t_SS_l'], train_log['t_SS_m']))
print('| v_total_l: %.4f | v_total_m: %.4f | v_DE_l: %.4f | v_DE_m: %.4f | v_SS_l: %.4f | v_SS_m: %.4f |'
% (val_log['v_total_l'], val_log['v_total_m'], val_log['v_DE_l'], val_log['v_DE_m'], val_log['v_SS_l'], val_log['v_SS_m']))
print('elapsed time: %.4f sec' % (elapsed_time))
#save the best model only
if val_log['v_total_m'] < lowest_monitored_score:
print("v_total_m: %.4f < previous lowest: %.4f" % (val_log['v_total_m'], lowest_monitored_score))
print("model saved!")
torch.save(model.state_dict(), config['mod_dir']+'/model_weights.pth')
lowest_monitored_score = val_log['v_total_m']
#reset stop counter
stop_count = 35
print("stop counter reset: ", stop_count)
log['best_model'].append("BEST")
else:
stop_count -= 1
print("v_total_m: %.4f >= previous lowest: %.4f, training stop in %d epoch" % (val_log['v_total_m'], lowest_monitored_score, stop_count))
log['best_model'].append("")
#update stop counter
log['stop_counter'].append(stop_count)
#paste to csv file
|
pd.DataFrame(log)
|
pandas.DataFrame
|
import unittest
import pandas as pd
import numpy as np
from tickcounter.questionnaire import Encoder, MultiEncoder
from pandas.testing import assert_frame_equal, assert_series_equal
class TestMultiEncoder(unittest.TestCase):
@classmethod
def setUpClass(cls):
super(TestMultiEncoder, cls).setUpClass()
cls.original = pd.read_csv("test/test_data/mental_health/data.csv")
cls.scale_1 = {"No": -1, "Yes": 1, "Don't know": 0, "Some of them": 0, "Not sure": 0, "Maybe": 0}
cls.scale_2 = {"1-5": 1, "6-25": 2, "26-100": 3, "100-500": 4, "500-1000": 5, "More than 1000": 6}
cls.scale_3 = {"Very difficult": -2, "Somewhat difficult": -1, "Don't know": 0, "Somewhat easy": 1, "Very easy": 2}
cls.scale_4 = {"Never": 1, "Rarely": 2, "Sometimes": 3, "Often": 4}
cls.e1 = Encoder({"No": -1, "Yes": 1, "Don't know": 0, "Some of them": 0, "Not sure": 0, "Maybe": 0}, default=0, neutral=0)
cls.e2 = Encoder({"1-5": 1, "6-25": 2, "26-100": 3, "100-500": 4, "500-1000": 5, "More than 1000": 6})
cls.e3 = Encoder({"Very difficult": -2, "Somewhat difficult": -1, "Don't know": 0, "Somewhat easy": 1, "Very easy": 2}, default=0)
cls.e4 = Encoder({"Never": 1, "Rarely": 2, "Sometimes": 3, "Often": 4}, neutral=3)
cls.col_1 = ['self_employed', 'family_history', 'treatment', 'remote_work',
'tech_company', 'benefits', 'care_options', 'wellness_program',
'seek_help', 'anonymity', 'mental_health_consequence',
'phys_health_consequence', 'coworkers', 'supervisor',
'mental_health_interview', 'phys_health_interview',
'mental_vs_physical', 'obs_consequence']
cls.col_2 = ['no_employees']
cls.col_3 = ['leave']
cls.col_4 = ['work_interfere']
cls.me1 = MultiEncoder([TestMultiEncoder.e1,
TestMultiEncoder.e2,
TestMultiEncoder.e3,
TestMultiEncoder.e4,
])
cls.me2 = MultiEncoder(TestMultiEncoder.e3)
cls.me3 = MultiEncoder(TestMultiEncoder.e1)
def setUp(self):
self.df = TestMultiEncoder.original.copy()
def test_transform_default_ss(self):
result_1 = TestMultiEncoder.me2.transform(self.df['self_employed'])
result_2 = TestMultiEncoder.me1.transform(self.df['self_employed'])
assert_frame_equal(self.df, TestMultiEncoder.original)
expected_1 = self.df['self_employed']
expected_2 = self.df['self_employed'].replace(TestMultiEncoder.scale_1)
expected_2 = expected_2.fillna(0)
assert_series_equal(result_1, expected_1, check_dtype=False)
assert_series_equal(result_2, expected_2, check_dtype=False)
def test_transform_default_df(self):
result = TestMultiEncoder.me1.transform(self.df)
assert_frame_equal(self.df, TestMultiEncoder.original)
expected = self.df.copy()
expected[TestMultiEncoder.col_1] = expected[TestMultiEncoder.col_1].replace(TestMultiEncoder.scale_1)
expected[TestMultiEncoder.col_1] = expected[TestMultiEncoder.col_1].fillna(0)
expected[TestMultiEncoder.col_2] = expected[TestMultiEncoder.col_2].replace(TestMultiEncoder.scale_2)
expected[TestMultiEncoder.col_3] = expected[TestMultiEncoder.col_3].replace(TestMultiEncoder.scale_3)
expected[TestMultiEncoder.col_3] = expected[TestMultiEncoder.col_3].fillna(0)
expected[TestMultiEncoder.col_4] = expected[TestMultiEncoder.col_4].replace(TestMultiEncoder.scale_4)
assert_frame_equal(result, expected, check_dtype=False)
def test_transform_rule_map(self):
pass
def test_transform_ignore_list(self):
ignore_list = ['self_employed', 'family_history', 'benefits', 'work_interfere']
result = TestMultiEncoder.me1.transform(self.df, ignore_list = ignore_list)
assert_frame_equal(self.df, TestMultiEncoder.original)
expected = self.df.copy()
expected[TestMultiEncoder.col_1] = expected[TestMultiEncoder.col_1].replace(TestMultiEncoder.scale_1)
expected[TestMultiEncoder.col_1] = expected[TestMultiEncoder.col_1].fillna(0)
expected[TestMultiEncoder.col_2] = expected[TestMultiEncoder.col_2].replace(TestMultiEncoder.scale_2)
expected[TestMultiEncoder.col_3] = expected[TestMultiEncoder.col_3].replace(TestMultiEncoder.scale_3)
expected[TestMultiEncoder.col_3] = expected[TestMultiEncoder.col_3].fillna(0)
expected[TestMultiEncoder.col_4] = expected[TestMultiEncoder.col_4].replace(TestMultiEncoder.scale_4)
expected[ignore_list] = self.df[ignore_list]
assert_frame_equal(result, expected, check_dtype=False)
def test_transform_return_rules(self):
result, rule = TestMultiEncoder.me2.transform(self.df, return_rule=True)
assert_frame_equal(self.df, TestMultiEncoder.original)
expected = self.df.copy()
expected[TestMultiEncoder.col_3] = expected[TestMultiEncoder.col_3].replace(TestMultiEncoder.scale_3)
expected[TestMultiEncoder.col_3] = expected[TestMultiEncoder.col_3].fillna(0)
expected_rule = pd.Series(index=self.df.columns, dtype=str)
expected_rule[TestMultiEncoder.col_3] = TestMultiEncoder.e3.name
assert_frame_equal(result, expected, check_dtype=False)
assert_series_equal(rule, expected_rule)
def test_transform_mode(self):
result_1 = TestMultiEncoder.me1.transform(self.df, mode='any')
result_2, rule = TestMultiEncoder.me1.transform(self.df, mode='strict', return_rule=True)
assert_frame_equal(self.df, TestMultiEncoder.original)
expected_1 = self.df.copy()
expected_1[TestMultiEncoder.col_1] = expected_1[TestMultiEncoder.col_1].replace(TestMultiEncoder.scale_1)
expected_1[TestMultiEncoder.col_1] = expected_1[TestMultiEncoder.col_1].fillna(0)
expected_1[TestMultiEncoder.col_2] = expected_1[TestMultiEncoder.col_2].replace(TestMultiEncoder.scale_2)
expected_1[TestMultiEncoder.col_3] = expected_1[TestMultiEncoder.col_3].replace(TestMultiEncoder.scale_3)
expected_1[TestMultiEncoder.col_3] = expected_1[TestMultiEncoder.col_3].fillna(0)
expected_1[TestMultiEncoder.col_4] = expected_1[TestMultiEncoder.col_4].replace(TestMultiEncoder.scale_4)
expected_2 = expected_1.copy()
expected_2[TestMultiEncoder.col_1] = TestMultiEncoder.original[TestMultiEncoder.col_1]
expected_rule = pd.Series(index=self.df.columns, dtype=str)
expected_rule[TestMultiEncoder.col_2] = TestMultiEncoder.e2.name
expected_rule[TestMultiEncoder.col_3] = TestMultiEncoder.e3.name
expected_rule[TestMultiEncoder.col_4] = TestMultiEncoder.e4.name
assert_frame_equal(result_1, expected_1, check_dtype=False)
assert_frame_equal(result_2, expected_2, check_dtype=False)
assert_series_equal(rule, expected_rule)
def test_transform_mix(self):
# Test when column and ignore list are used together.
# Test when column, ignore list and return rules are used together
pass
def test_transform_columns(self):
# TODO this in code.
pass
def test_count_neutral_ss(self):
# On non-matching series, should return None as there is no matching encoder.
# We cannot assume that we will encode series, unlike single encoder, because we don't know which encoder to use.
result_1 = TestMultiEncoder.me3.count_neutral(self.df[TestMultiEncoder.col_2[0]])
# On matching series
result_2 = TestMultiEncoder.me1.count_neutral(self.df[TestMultiEncoder.col_1[0]])
# On series with no neutral matching
with self.assertWarns(UserWarning):
result_3 = TestMultiEncoder.me2.count_neutral(self.df[TestMultiEncoder.col_3[0]])
assert_frame_equal(self.df, TestMultiEncoder.original)
expected_2 = (self.df[TestMultiEncoder.col_1[0]] == "Don't know") | (self.df[TestMultiEncoder.col_1[0]].isna())
expected_2 = expected_2.astype(int)
expected_2.rename("Neutral count", inplace=True)
self.assertIsNone(result_1)
|
assert_series_equal(result_2, expected_2, check_dtype=False)
|
pandas.testing.assert_series_equal
|
import pandas as pd
import math
from .power import main
def test_int_int():
assert main(base=2, exponent=4)["power"] == 16
def test_series_int():
assert main(
base=pd.Series(
{
"2019-08-01T15:20:12": 4,
"2019-08-01T15:44:12": None,
"2019-08-03T16:20:15": 2,
"2019-08-05T12:00:34": 8,
}
),
exponent=-1,
)["power"].equals(
pd.Series(
{
"2019-08-01T15:20:12": 0.25,
"2019-08-01T15:44:12": None,
"2019-08-03T16:20:15": 0.5,
"2019-08-05T12:00:34": 0.125,
}
)
)
def test_series_series():
assert main(
base=pd.Series(
{
"2019-08-01T15:20:12": 1,
"2019-08-01T15:44:12": None,
"2019-08-03T16:20:15": 2,
"2019-08-05T12:00:34": 4,
}
),
exponent=pd.Series(
{
"2019-08-01T15:20:12": 2,
"2019-08-01T15:44:12": 4,
"2019-08-03T16:20:15": 0,
"2019-08-05T12:00:34": 2,
}
),
)["power"].equals(
pd.Series(
{
"2019-08-01T15:20:12": 1,
"2019-08-01T15:44:12": None,
"2019-08-03T16:20:15": 1,
"2019-08-05T12:00:34": 16,
}
)
)
def test_df_df():
assert main(
base=pd.DataFrame(
{
"a": {
"2019-08-01T15:20:12": 3,
"2019-08-01T15:44:12": 7,
"2019-08-03T16:20:15": 0,
"2019-08-05T12:00:34": 2,
},
"b": {
"2019-08-01T15:20:12": 0,
"2019-08-01T15:44:12": 4,
"2019-08-03T16:20:15": 5,
"2019-08-05T12:00:34": 7,
},
}
),
exponent=pd.DataFrame(
{
"a": {
"2019-08-01T15:20:12": 1,
"2019-08-01T15:44:12": 2,
"2019-08-03T16:20:15": 3,
"2019-08-05T12:00:34": 2,
},
"b": {
"2019-08-01T15:20:12": 1,
"2019-08-01T15:44:12": 3,
"2019-08-03T16:20:15": 2,
"2019-08-05T12:00:34": 0,
},
}
),
)["power"].equals(
pd.DataFrame(
{
"a": {
"2019-08-01T15:20:12": 3,
"2019-08-01T15:44:12": 49,
"2019-08-03T16:20:15": 0,
"2019-08-05T12:00:34": 4,
},
"b": {
"2019-08-01T15:20:12": 0,
"2019-08-01T15:44:12": 64,
"2019-08-03T16:20:15": 25,
"2019-08-05T12:00:34": 1,
},
}
)
)
def test_empty_series_series():
assert (
math.isnan(
main(
base=pd.Series(dtype=float),
exponent=pd.Series(
{
"2019-08-01T15:20:12": 1.0,
"2019-08-01T15:44:12": 27,
"2019-08-03T16:20:15": 3.6,
"2019-08-05T12:00:34": 17,
}
),
)["power"][0]
)
and math.isnan(
main(
base=pd.Series(dtype=float),
exponent=pd.Series(
{
"2019-08-01T15:20:12": 1.0,
"2019-08-01T15:44:12": 27,
"2019-08-03T16:20:15": 3.6,
"2019-08-05T12:00:34": 17,
}
),
)["power"][1]
)
and math.isnan(
main(
base=pd.Series(dtype=float),
exponent=pd.Series(
{
"2019-08-01T15:20:12": 1.0,
"2019-08-01T15:44:12": 27,
"2019-08-03T16:20:15": 3.6,
"2019-08-05T12:00:34": 17,
}
),
)["power"][2]
)
and math.isnan(
main(
base=
|
pd.Series(dtype=float)
|
pandas.Series
|
#%%
import pandas as pd
import glob
import numpy as np
import math
#%%
def parse_single(year):
PUS_start = pd.DataFrame()
useful_cols = [
"WAGP",
"SEX",
"AGEP",
"DECADE",
"RAC2P",
"RAC1P",
"SCHL",
"WKW",
"WKHP",
"OCCP",
"POWSP",
"ST",
"HISP",
]
path = "data/data_raw/%s" % year
PUS_start = pd.concat(
[pd.read_csv(f, usecols=useful_cols) for f in glob.glob(path + "/*.csv")],
ignore_index=True,
)
return PUS_start
def mapping_features(df):
# entry date
df["RACE"] = df["RAC2P"].map(
lambda y: "White"
if y == 1
else "Black"
if y == 2
else "American Indian"
if y <= 29
else "Native Alaskan"
if y <= 37
else y
if y <= 58
else "Hispanic"
if y == 70
else np.nan
)
df["DECADE"] = df["DECADE"].replace(np.nan, 0)
df["DECADE"] = df["DECADE"].map(
lambda y: "Born in US"
if y == 0
else "Before 1950"
if y == 1
else "1950 - 1959"
if y == 2
else "1960 - 1969"
if y == 3
else "1970 - 1979"
if y == 4
else "1980 - 1989"
if y == 5
else "1990 - 1999"
if y == 6
else "2000 - 2009"
if y == 7
else "2010 or later"
if y == 8
else np.nan
)
# Race
df["RAC2P"] = np.where(df["HISP"] == 1, df["RAC2P"], 70)
df["RACE"] = df["RAC2P"].map(
lambda y: "White"
if y == 1
else "Black"
if y == 2
else "American Indian"
if y <= 29
else "Native Alaskan"
if y <= 37
else y
if y <= 58
else "Hispanic"
if y == 70
else np.nan
)
df["RAC2P"] = np.where(df["HISP"] == 1, df["RAC2P"], 70)
df["RACE2"] = df["RAC2P"].map(
lambda y: "White"
if y == 1
else "Black"
if y == 2
else "American Indian"
if y <= 29
else "Native Alaskan"
if y <= 37
else "Asian"
if y <= 58
else "Hispanic"
if y == 70
else np.nan
)
# Sex
df["SEX"] = df["SEX"].map(
lambda y: "Male" if y == 1 else "Female" if y == 2 else "na"
)
# AGE
df["AGE"] = df["AGEP"].map(
lambda y: "0-17"
if y <= 18
else "18-24"
if y <= 24
else "25-54"
if y <= 54
else "55-64"
if y <= 64
else "65+"
)
# Education
df["EDU"] = df["SCHL"].map(
lambda y: "No_Highschool"
if y <= 15
else "Highschool"
if y <= 17
else "Some_College"
if y <= 19
else "Some_College"
if y == 20
else "B.S._Degree"
if y == 21
else "M.S._Degree"
if y == 22
else "PhD_or_Prof"
if y <= 24
else np.nan
)
# Occupation
df["JOB"] = df["OCCP"].map(
lambda y: "Business"
if y <= 960
else "Science"
if y <= 1980
else "Art"
if y <= 2970
else "Healthcare"
if y <= 3550
else "Services"
if y <= 4655
else "Sales"
if y <= 5940
else "Maintenance"
if y <= 7640
else "Production"
if y <= 8990
else "Transport"
if y <= 9760
else "Military"
if y <= 9830
else np.nan
)
return df
# %%
df_raw = parse_single(2018)
#%%
df_raw = parse_single(2018)
df = mapping_features(df_raw)
groupby_col = ["RACE", "DECADE"]
agg_df = df.groupby(groupby_col).count().reset_index()
agg_df = agg_df.iloc[:, 0 : len(groupby_col) + 1]
coding_df = pd.read_csv("data/data_raw/race_coding.csv")
result = pd.merge(agg_df, coding_df, how="left", on="RACE")
result["% Total Pop"] = result["ST"] / result["ST"].sum()
asian_result = result.dropna()
asian_result["% Asian Pop"] = asian_result["ST"] / asian_result["ST"].sum()
recomb_df = pd.DataFrame()
for race in asian_result["Asian"].unique():
subset_df = asian_result[asian_result["Asian"] == race]
subset_df = asian_result[asian_result["Asian"] == race]
asian_result.iloc[:, 1] != "na"
subset_df["% Race Pop"] = subset_df["ST"] / subset_df["ST"].sum()
recomb_df = pd.concat([recomb_df, subset_df])
def panda_strip(x):
r = []
for y in x:
if isinstance(y, str):
y = y.strip()
r.append(y)
return pd.Series(r)
recomb_df = recomb_df.apply(lambda x: panda_strip(x))
recomb_df[["Asian"]] = recomb_df[["Asian"]].apply(lambda x: x.str.split().str[0])
wide_format = recomb_df.pivot(
index="Asian", columns="DECADE", values="% Race Pop"
).reset_index()
wide_format = wide_format[
[
"Asian",
"Born in US",
"Before 1950",
"1950 - 1959",
"1960 - 1969",
"1970 - 1979",
"1980 - 1989",
"1990 - 1999",
"2000 - 2009",
"2010 or later",
]
]
wide_format["% Immigrated"] = 1 - wide_format["Born in US"]
wide_format = wide_format.rename(columns={"Asian": "RACE2"})
wide_format = wide_format.replace(np.nan, 0)
wide_format.to_csv("data/data_output/imm_output.csv")
# %%
df_raw = parse_single(2018)
df = mapping_features(df_raw)
groupby_col = ["RACE2", "DECADE"]
agg_df = df.groupby(groupby_col).count().reset_index()
agg_df = agg_df.iloc[:, 0 : len(groupby_col) + 1]
recomb_df2 = pd.DataFrame()
for race in agg_df["RACE2"].unique():
subset_df = agg_df[agg_df["RACE2"] == race]
subset_df.iloc[:, 1] != "na"
subset_df["% Race Pop"] = subset_df["ST"] / subset_df["ST"].sum()
recomb_df2 = pd.concat([recomb_df2, subset_df])
wide_format2 = recomb_df2.pivot(
index="RACE2", columns="DECADE", values="% Race Pop"
).reset_index()
wide_format2 = wide_format2[
[
"RACE2",
"Born in US",
"Before 1950",
"1950 - 1959",
"1960 - 1969",
"1970 - 1979",
"1980 - 1989",
"1990 - 1999",
"2000 - 2009",
"2010 or later",
]
]
wide_format2["% Immigrated"] = 1 - wide_format2["Born in US"]
wide_format2.to_csv("data/data_output/imm_all_output.csv")
wide_format_comb = pd.concat([wide_format, wide_format2])
for col in wide_format_comb:
if col != "RACE2":
wide_format_comb[col] = wide_format_comb[col].astype(float).map("{:.2%}".format)
wide_format_comb.to_csv("data/data_output/imm_comb_output.csv")
recomb_df = recomb_df.rename(columns={"Asian": "RACE2"})
recomb_df["% Race Pop"] = recomb_df["% Race Pop"].astype(float).map("{:.2%}".format)
recomb_df2["% Race Pop"] = recomb_df2["% Race Pop"].astype(float).map("{:.2%}".format)
recomb_full = pd.concat([recomb_df, recomb_df2])
recomb_full.to_csv("data/data_output/imm_long.csv")
recomb_df.to_csv("data/data_output/imm_long1.csv")
recomb_df2.to_csv("data/data_output/imm_long2.csv")
#%%
df_raw = parse_single(2018)
df = mapping_features(df_raw)
groupby_col = ["RACE", "EDU"]
agg_df = df[df["AGE"] != "0-17"]
agg_df = agg_df.groupby(groupby_col).count().reset_index()
agg_df = agg_df.iloc[:, 0 : len(groupby_col) + 1]
coding_df = pd.read_csv("data/data_raw/race_coding.csv")
result = pd.merge(agg_df, coding_df, how="left", on="RACE")
result["% Total Pop"] = result["ST"] / result["ST"].sum()
asian_result = result.dropna()
asian_result["% Asian Pop"] = asian_result["ST"] / asian_result["ST"].sum()
recomb_df = pd.DataFrame()
for race in asian_result["Asian"].unique():
subset_df = asian_result[asian_result["Asian"] == race]
subset_df = asian_result[asian_result["Asian"] == race]
asian_result.iloc[:, 1] != "na"
subset_df["% Race Pop"] = subset_df["ST"] / subset_df["ST"].sum()
recomb_df = pd.concat([recomb_df, subset_df])
def panda_strip(x):
r = []
for y in x:
if isinstance(y, str):
y = y.strip()
r.append(y)
return pd.Series(r)
recomb_df = recomb_df.apply(lambda x: panda_strip(x))
recomb_df[["Asian"]] = recomb_df[["Asian"]].apply(lambda x: x.str.split().str[0])
wide_format = recomb_df.pivot(
index="Asian", columns="EDU", values="% Race Pop"
).reset_index()
wide_format.loc[wide_format["Asian"] == "", "Asian"] = (
wide_format["Asian"].str.split().str.get(0)
)
wide_format = wide_format[
[
"Asian",
"No_Highschool",
"Highschool",
"Some_College",
"B.S._Degree",
"M.S._Degree",
"PhD_or_Prof",
]
]
wide_format["B.S. Degree +"] = (
1
- wide_format["No_Highschool"]
- wide_format["Highschool"]
- wide_format["Some_College"]
)
wide_format["% Completed Highschool"] = 1 - wide_format["No_Highschool"]
wide_format = wide_format.rename(columns={"Asian": "RACE2"})
wide_format.to_csv("data/data_output/edu_output.csv")
# %%
df_raw = parse_single(2018)
df = mapping_features(df_raw)
groupby_col = ["RACE2", "EDU"]
agg_df = df[df["AGE"] != "0-17"]
agg_df = agg_df.groupby(groupby_col).count().reset_index()
agg_df = agg_df.iloc[:, 0 : len(groupby_col) + 1]
recomb_df2 = pd.DataFrame()
for race in agg_df["RACE2"].unique():
subset_df = agg_df[agg_df["RACE2"] == race]
subset_df.iloc[:, 1] != "na"
subset_df["% Race Pop"] = subset_df["ST"] / subset_df["ST"].sum()
recomb_df2 = pd.concat([recomb_df2, subset_df])
wide_format2 = recomb_df2.pivot(
index="RACE2", columns="EDU", values="% Race Pop"
).reset_index()
wide_format2 = wide_format2[
[
"RACE2",
"No_Highschool",
"Highschool",
"Some_College",
"B.S._Degree",
"M.S._Degree",
"PhD_or_Prof",
]
]
wide_format2["B.S. Degree +"] = (
1
- wide_format2["No_Highschool"]
- wide_format2["Highschool"]
- wide_format2["Some_College"]
)
wide_format2["% Completed Highschool"] = 1 - wide_format2["No_Highschool"]
wide_format2.to_csv("data/data_output/edu_all_output.csv")
wide_format_comb = pd.concat([wide_format, wide_format2])
for col in wide_format_comb:
if col != "RACE2":
wide_format_comb[col] = wide_format_comb[col].astype(float).map("{:.2%}".format)
wide_format_comb.to_csv("data/data_output/edu_comb_output.csv")
recomb_df = recomb_df.rename(columns={"Asian": "RACE2"})
recomb_df["% Race Pop"] = recomb_df["% Race Pop"].astype(float).map("{:.2%}".format)
recomb_df2["% Race Pop"] = recomb_df2["% Race Pop"].astype(float).map("{:.2%}".format)
recomb_full = pd.concat([recomb_df, recomb_df2])
recomb_full.to_csv("data/data_output/edu_long.csv")
recomb_df.to_csv("data/data_output/edu_long1.csv")
recomb_df2.to_csv("data/data_output/edu_long2.csv")
# %%
#####
# OCCUPATION
df_raw = parse_single(2018)
df = mapping_features(df_raw)
groupby_col = ["RACE", "JOB"]
agg_df = df[df["AGE"] != "0-17"]
agg_df = agg_df.groupby(groupby_col).count().reset_index()
agg_df = agg_df.iloc[:, 0 : len(groupby_col) + 1]
coding_df = pd.read_csv("data/data_raw/race_coding.csv")
result = pd.merge(agg_df, coding_df, how="left", on="RACE")
result["% Total Pop"] = result["ST"] / result["ST"].sum()
asian_result = result.dropna()
asian_result["% Asian Pop"] = asian_result["ST"] / asian_result["ST"].sum()
recomb_df = pd.DataFrame()
for race in asian_result["Asian"].unique():
subset_df = asian_result[asian_result["Asian"] == race]
subset_df = asian_result[asian_result["Asian"] == race]
asian_result.iloc[:, 1] != "na"
subset_df["% Race Pop"] = subset_df["ST"] / subset_df["ST"].sum()
recomb_df = pd.concat([recomb_df, subset_df])
recomb_df = recomb_df.apply(lambda x: panda_strip(x))
recomb_df[["Asian"]] = recomb_df[["Asian"]].apply(lambda x: x.str.split().str[0])
wide_format = recomb_df.pivot(
index="Asian", columns="JOB", values="% Race Pop"
).reset_index()
wide_format.loc[wide_format["Asian"] == "", "Asian"] = (
wide_format["Asian"].str.split().str.get(0)
)
wide_format["% STEM"] = wide_format["Science"] + wide_format["Healthcare"]
wide_format = wide_format.rename(columns={"Asian": "RACE2"})
wide_format.to_csv("data/data_output/JOB_output.csv")
# %%
df_raw = parse_single(2018)
df = mapping_features(df_raw)
groupby_col = ["RACE2", "JOB"]
agg_df = df[df["AGE"] != "0-17"]
agg_df = agg_df.groupby(groupby_col).count().reset_index()
agg_df = agg_df.iloc[:, 0 : len(groupby_col) + 1]
recomb_df2 = pd.DataFrame()
for race in agg_df["RACE2"].unique():
subset_df = agg_df[agg_df["RACE2"] == race]
subset_df.iloc[:, 1] != "na"
subset_df["% Race Pop"] = subset_df["ST"] / subset_df["ST"].sum()
recomb_df2 = pd.concat([recomb_df2, subset_df])
wide_format2 = recomb_df2.pivot(
index="RACE2", columns="JOB", values="% Race Pop"
).reset_index()
wide_format2["% STEM"] = wide_format2["Science"] + wide_format2["Healthcare"]
wide_format2.to_csv("data/data_output/JOB_all_output.csv")
wide_format_comb = pd.concat([wide_format, wide_format2])
for col in wide_format_comb:
if col != "RACE2":
wide_format_comb[col] = wide_format_comb[col].astype(float).map("{:.2%}".format)
wide_format_comb.to_csv("data/data_output/JOB_comb_output.csv")
recomb_df = recomb_df.rename(columns={"Asian": "RACE2"})
recomb_df["% Race Pop"] = recomb_df["% Race Pop"].astype(float).map("{:.2%}".format)
recomb_df2["% Race Pop"] = recomb_df2["% Race Pop"].astype(float).map("{:.2%}".format)
recomb_full = pd.concat([recomb_df, recomb_df2])
recomb_full.to_csv("data/data_output/job_long.csv")
recomb_df.to_csv("data/data_output/job_long1.csv")
recomb_df2.to_csv("data/data_output/job_long2.csv")
# %%
#####
# WAGE
def full_time_detect(df):
df = df.loc[df.WKW < 4].copy() # more than 40 weeks a year is considered full time
df = df.loc[df.WKHP >= 35].copy() # >=35 hr a week is considered full time
df = df.loc[df.AGEP >= 18].copy() # lower limit age
df = df.loc[df.AGEP <= 70].copy() # upper limit age
return df
# determine who is considered an outlier
def outlier_wage(df):
# wage_iqr = np.percentile(df.WAGP, 75) - np.percentile(df.WAGP, 25)
# wage_upper = np.percentile(df.WAGP, 75) + wage_iqr * 3
df = df.loc[df.WAGP >= 12500].copy() # used because 12500 is poverty line
df = df.loc[df.WAGP <= 400000].copy() # used as ~1% wage US population
return df
df_raw = parse_single(2018)
df = mapping_features(df_raw)
other = full_time_detect(df)
other = outlier_wage(other)
other = other[["RACE", "WAGP", "RACE2"]]
other.to_csv("data/data_output/wage_raw.csv")
#%%
agg_df = (
other.groupby("RACE")
.agg(count=("WAGP", "size"), mean=("WAGP", "mean"), median=("WAGP", "median"))
.reset_index()
)
agg_df2 = (
other.groupby("RACE2")
.agg(count=("WAGP", "size"), mean=("WAGP", "mean"), median=("WAGP", "median"))
.reset_index()
)
agg_df2["RACE"] = agg_df2["RACE2"]
agg_df3 = agg_df2[agg_df2["RACE"] != "Asian"]
coding_df = pd.read_csv("data/data_raw/race_coding.csv")
result = pd.merge(agg_df, coding_df, how="left", on="RACE")
result = result.apply(lambda x: panda_strip(x))
result[["Asian"]] = result[["Asian"]].apply(lambda x: x.str.split().str[0])
asian = result[0:21].rename(columns={"Asian": "RACE2"})
asian["RACE"] = "Asian"
# other_race = result[21:26].rename(columns={"RACE": "RACE2"})
wage_result = pd.concat([asian, agg_df2])
wage_result.to_csv("data/data_output/wage_asian_output.csv")
wage_result = pd.concat([asian, agg_df3])
wage_result.to_csv("data/data_output/wage_no_asian_output.csv")
#%%
df_raw = parse_single(2018)
df = mapping_features(df_raw)
other = full_time_detect(df)
other = outlier_wage(other)
other = other[["RACE", "WAGP", "RACE2"]]
other.to_csv("data/data_output/wage_raw.csv")
#%%
df_raw = parse_single(2018)
df = mapping_features(df_raw)
other = full_time_detect(df)
other = outlier_wage(other)
other = other[["RACE", "WAGP", "RACE2"]]
other.to_csv("data/data_output/wage_raw.csv")
agg_df = (
other.groupby("RACE")
.agg(count=("WAGP", "size"), mean=("WAGP", "mean"), median=("WAGP", "median"))
.reset_index()
)
agg_df2 = (
other.groupby("RACE2")
.agg(count=("WAGP", "size"), mean=("WAGP", "mean"), median=("WAGP", "median"))
.reset_index()
)
agg_df2["RACE"] = agg_df2["RACE2"]
agg_df3 = agg_df2[agg_df2["RACE"] != "Asian"]
coding_df = pd.read_csv("data/data_raw/race_coding.csv")
result = pd.merge(agg_df, coding_df, how="left", on="RACE")
result = result.apply(lambda x: panda_strip(x))
result[["Asian"]] = result[["Asian"]].apply(lambda x: x.str.split().str[0])
asian = result[0:21].rename(columns={"Asian": "RACE2"})
asian["RACE"] = "Asian"
# other_race = result[21:26].rename(columns={"RACE": "RACE2"})
wage_result = pd.concat([asian, agg_df2])
wage_result.to_csv("data/data_output/wage_asian_output.csv")
wage_result = pd.concat([asian, agg_df3])
wage_result.to_csv("data/data_output/wage_no_asian_output.csv")
#%%
long2 = pd.read_csv("data/data_output/edu_long2.csv")
long2 = long2.groupby("RACE2").sum().reset_index()
long2["% Pop"] = long2["ST"] / long2["ST"].sum()
long2["% Pop"] = long2["% Pop"].astype(float).map("{:.2%}".format)
long2["Race1"] = long2["RACE2"] + " (" + long2["% Pop"] + ")"
long2["Race2"] = long2["RACE2"] + " (" + long2["% Pop"] + ")"
long2 = long2[long2["RACE2"] != "Asian"]
long2
# %%
long1 = pd.read_csv("data/data_output/edu_long1.csv")
long1 = long1.groupby("RACE2").sum().reset_index()
long1["% Pop"] = long1["ST"] / long1["ST"].sum()
long1["% Pop"] = long1["% Pop"].astype(float).map("{:.2%}".format)
long1["Race1"] = "Asian (5.42%)"
long1["Race2"] = long1["RACE2"] + " (" + long1["% Pop"] + ")"
long1
# %%
long_combo =
|
pd.concat([long2, long1])
|
pandas.concat
|
"""
<NAME>, 2019
Class to scrape realtime data from NDBC Buoys -- https://www.ndbc.noaa.gov/realtime.shtml
Creates pandas dataframe objects for specific data types for the last 45 days.
Options to return or pickle dataframes.
Notes:
* Realtime data contains some information that historical data doesnt,
for example, Separation Frequencies in the data_spec dtype.
* You can run 'scrape_all_dtypes' once every 45 days to keep accumulatine realtime data.
"""
import pandas as pd
from .buoy_data_scraper import BuoyDataScraper
class RealtimeScraper(BuoyDataScraper):
DTYPES = {"stdmet": {"url_code":"txt", "name":"Standard Meteorological Data"},
"adcp": {"url_code":"adcp", "name":"Acoustic Doppler Current Profiler Data"},
"cwind": {"url_code":"cwind", "name":"Continuous Winds Data"},
"supl": {"url_code":"supl", "name":"Supplemental Measurements Data"},
"spec": {"url_code":"spec", "name":"Spectral Wave Summary Data"},
"data_spec":{"url_code":"data_spec", "name":"Raw Spectral Wave Data"},
"swdir": {"url_code":"swdir", "name":"Spectral Wave Data (alpha1)"},
"swdir2": {"url_code":"swdir2", "name":"Spectral Wave Data (alpha2)"},
"swr1": {"url_code":"swr1", "name":"Spectral Wave Data (r1)"},
"swr2": {"url_code":"swr2", "name":"Spectral Wave Data (r2)"},
"ocean": {"url_code":"ocean", "name":"Oceanographic"},
"srad": {"url_code":"srad", "name":"Solar Radiation"},
}
BASE_URL = "https://www.ndbc.noaa.gov/data/realtime2/{}.{}"
def __init__(self, buoy_id, data_dir="buoydata/"):
super().__init__(buoy_id)
self.data_dir = "{}{}/realtime/".format(data_dir, buoy_id)
def get_available_dtypes(self, dtypes=DTYPES):
''' Returns list of available realtime data types for this buoy. '''
available_types = []
for dtype in dtypes:
if self._url_valid(self._make_url(dtype)):
available_types.append(dtype)
return available_types
def scrape_dtypes(self, dtypes=None):
'''
Scrapes and saves all data types for this buoy for realtime data (the last 45 days).
Input :
dtypes : Optional, list of dtype strings. Default is all available dtypes.
Output :
saves all dtypes available for this buoy as pandas dataframe pickles.
dtypes with previously saved pickles in data_dir will be updated with new data.
'''
self._create_dir_if_not_exists(self.data_dir)
if not dtypes: dtypes=self.DTYPES
for dtype in self.get_available_dtypes(dtypes):
self.scrape_dtype(dtype, save=True)
def scrape_dtype(self, dtype, save=False, save_path=None):
'''
Scrapes data for a given data type. Calls helper function to scrape specific dtype.
See helper functions below for columns and units of each dtype.
More info at: https://www.ndbc.noaa.gov/measdes.shtml
Inputs :
dtype : string, must be an available data type for this buoy.
save_path (optional) : string representing path to save dataframe to as pickle. Will update pickle if it already exists.
Output :
pandas dataframe. If save_path is specified, also saves pickled dataframe to save_path.
'''
url = self._make_url(dtype)
if self._url_valid(url):
df = getattr(self, dtype)(url)
if save:
if not save_path:
self._create_dir_if_not_exists(self.data_dir)
save_path="{}{}.pkl".format(self.data_dir, dtype)
self._update_pickle(df, save_path)
else:
return df
else:
return pd.DataFrame()
def stdmet(self, url):
'''
Standard Meteorological Data
dtype: "stdmet"
index: datetime64[ns, UTC]
columns: WDIR WSPD GST WVHT DPD APD MWD PRES ATMP WTMP DEWP VIS PTDY TIDE
units: degT m/s m/s m sec sec degT hPa degC degC degC nmi hPa ft
'''
NA_VALS = ['MM']
return self._scrape_norm(url, na_vals=NA_VALS)
def adcp(self, url):
'''
Acoustic Doppler Current Profiler Data
dtype: "adcp"
index: datetime64[ns, UTC]
columns: DEP01 DIR01 SPD01
units: m degT cm/s
'''
NA_VALS = ['MM']
df = self._scrape_norm(url, na_vals=NA_VALS)
return df.iloc[:,0:3].astype('float')
def cwind(self, url):
'''
Continuous Winds Data
dtype: "cwind"
index: datetime64[ns, UTC]
columns: WDIR WSPD GDR GST GTIME
units: degT m/s degT m/s hhmm
'''
NA_VALS = ['MM', 99.0, 999, 9999]
return self._scrape_norm(url, na_vals=NA_VALS).astype('float')
def supl(self, url):
'''
Supplemental Measurements Data
dtype: "supl"
index: datetime64[ns, UTC]
columns: PRES PTIME WSPD WDIR WTIME
units: hPa hhmm m/s degT hhmm
'''
NA_VALS = ['MM']
return self._scrape_norm(url, na_vals=NA_VALS).astype('float')
def spec(self, url):
'''
Spectral Wave Summary Data
dtype: "spec"
index: datetime64[ns, UTC]
columns: WVHT SwH SwP WWH WWP SwD WWD STEEPNESS APD MWD
units: m m sec m sec - degT - sec degT
'''
NA_VALS = ['MM', -99]
return self._scrape_norm(url, na_vals=NA_VALS)
def data_spec(self, url):
'''
Raw Spectral Wave Data
dtype: "data_spec"
index: datetime64[ns, UTC]
columns: sep_freq 0.033 0.038 0.043 ... 0.445 0.465 0.485 (frequencies in Hz)
units: frequency (Hz) Spectral Wave Density/Energy in m^2/Hz for each frequency bin
Note: "sep_freq" (Separation Frequency) is the frequency that separates
wind waves (WWH, WWP, WWD) from swell waves (SWH, SWP,SWD).
'''
NA_VALS = ['MM', 9.999]
# combine the first five date columns YY MM DD hh mm and make index
df = pd.read_csv(url, header=None, na_values=NA_VALS, delim_whitespace=True, skiprows=1, parse_dates={'datetime':[0,1,2,3,4]}, index_col=0)
df.index =
|
pd.to_datetime(df.index,format="%Y %m %d %H %M")
|
pandas.to_datetime
|
# -*- coding: utf-8 -*-
"""
Created on Mon May 10 08:46:30 2021
@author: niven
"""
import os
import glob
from pathlib import Path
import shutil
import datetime
import imageio
import pandas as pd
import geopandas as gpd
import numpy as np
from scipy import stats
from shapely.geometry import Point, Polygon, LineString
from shapely import speedups
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.patches as mpatches
from matplotlib.collections import LineCollection
import matplotlib.cm as cm
from mpl_toolkits.axes_grid1 import make_axes_locatable
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
from src.definitions import ROOT_DIR, filter_Prot, dict_Sale2Yr, cols_prebid, cols_bid, cols_company2
from src.definitions import cols_borehole_pos, cols_borehole
from src.definitions import dict_Brent
from src.data.utils import concatenate_files, df_col2dict, dryhole_label
# %% bid data directories
path_bid_data = ROOT_DIR /'src/data'
assert path_bid_data.exists()
path_scra = ROOT_DIR/'src/data/scra'
if path_scra.exists() == False:
path_scra.mkdir()
# %% block geometry
path_activelease = ROOT_DIR/'src/data/shape_files/activelease'
path_protractions = ROOT_DIR/'src/data/shape_files/protclip'
path_blocks = ROOT_DIR/'src/data/shape_files/blocks'
path_bath = ROOT_DIR/'src/data/shape_files/bathymetry'
gpd_ActiveLease = gpd.read_file(path_activelease/'al_20210201.shp')
gpd_Prot = gpd.read_file(path_protractions/'protclip.shp')
gpd_Blocks = gpd.read_file(path_blocks/'blocks.shp')
gpd_Bath500ft = gpd.read_file(path_bath/'contours_noaa_500ft.shp')
gpd_Blocks['Lon'] = gpd_Blocks.centroid.x
gpd_Blocks['Lat'] = gpd_Blocks.centroid.y
# %% List of Ewave
filter_Ewave = ['KC330','GB740','GB830','GC57','GC66','EW951','EW957','GC31','GC76','GC164','GC390','WR23','WR24',
'WR112','SE129','SE116','KC903','KC560','KC556','KC330']
df_filter = gpd_Blocks.loc[gpd_Blocks['AC_LAB'].isin(filter_Ewave) ].copy()
sorterIndex = dict(zip(filter_Ewave, range(len(filter_Ewave))))
df_filter['Order'] = df_filter['AC_LAB'].map(sorterIndex)
# % Order polygon points
df_filter.sort_values(by=['Order'], ascending = [True], inplace = True)
df_filter.set_index('Order', inplace = True)
df_filter = pd.concat([df_filter, df_filter.iloc[0:1] ], ignore_index=True )
# % extract centroid (block corner estimate)
df_filter['X'] = df_filter.centroid.x
df_filter['Y'] = df_filter.centroid.y + .02 # .02 about 1/2 block shift
poly = Polygon(list(zip(df_filter.X, df_filter.Y))) # in Python 3.x
d = {'Survey': 'Ewave', 'geometry':poly}
#
gdf_Ewave = gpd.GeoDataFrame(d, index=[0], crs=4267)
del d, df_filter, poly, filter_Ewave
# %% Borehole data
path_boreholes = ROOT_DIR / 'src/data/5010.DAT'
assert path_boreholes.exists()
df_Boreholes = pd.read_fwf(path_boreholes, colspecs=cols_borehole_pos, header=None)
df_Boreholes.columns = cols_borehole
# Clean Borehole Dataframe
df_Boreholes['BottomLon'] = df_Boreholes['BottomLon'].apply(lambda x: pd.to_numeric(x, errors='coerce'))
df_Boreholes['BottomLat'] = df_Boreholes['BottomLat'].apply(lambda x: pd.to_numeric(x, errors='coerce'))
df_Boreholes['MD'] = df_Boreholes['MD'].apply(lambda x:
|
pd.to_numeric(x, errors='coerce')
|
pandas.to_numeric
|
from concurrent import futures
import json
import argparse
import time
import random
import itertools
import numpy as np
import os.path
import sys
import pandas as pd
import requests
import requests.exceptions
import re
import logging
from datetime import datetime
LOGGER_NAME = 'fetch_cnpj'
TEMP_DATASET_PATH = os.path.join('data', 'companies-partial.xz')
INFO_DATASET_PATH = os.path.join('data', '{0}-{1}-{2}-companies.xz')
global logger, cnpj_list, num_threads, proxies_list
# source files mapped for extract cnpj
with open(os.path.join(os.path.dirname(os.path.realpath(__file__)),
'table_config.json')) as json_file:
json_config = json.load(json_file)
datasets_cols = json_config['cnpj_cpf']
def configure_logger(verbosity):
logger = logging.getLogger(LOGGER_NAME)
logger.setLevel(verbosity)
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(verbosity)
logger.addHandler(ch)
return logger
def transform_and_translate_data(json_data):
"""
Transform main activity, secondary activity and partners list in
multi columns and translate column names.
"""
try:
data = pd.DataFrame(columns=['atividade_principal',
'data_situacao',
'tipo',
'nome',
'telefone',
'atividades_secundarias',
'situacao',
'bairro',
'logradouro',
'numero',
'cep',
'municipio',
'uf',
'abertura',
'natureza_juridica',
'fantasia',
'cnpj',
'ultima_atualizacao',
'status',
'complemento',
'email',
'efr',
'motivo_situacao',
'situacao_especial',
'data_situacao_especial',
'qsa'])
data = data.append(json_data, ignore_index=True)
except Exception as e:
logger.error("Error trying to transform and translate data:")
logger.error(json_data)
raise e
def decompose_main_activity(value):
struct = value
if struct:
return pd.Series(struct[0]). \
rename_axis({'code': 'main_activity_code',
'text': 'main_activity'})
else:
return pd.Series({}, index=['main_activity_code', 'main_activity'])
def decompose_secondary_activities(value):
struct = value
if struct and struct[0].get('text') != 'Não informada':
new_attributes = [
|
pd.Series(activity)
|
pandas.Series
|
#!/usr/bin/env python
"""Script for generating figures of catalog statistics. Run `QCreport.py -h`
for command line usage.
"""
import os
import sys
import errno
import argparse
from datetime import date, datetime
from math import sqrt, radians, cos
import markdown
import numpy as np
import pandas as pd
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.patches import Polygon
from obspy.geodetics.base import gps2dist_azimuth
# Python 2
try:
from urllib2 import urlopen, HTTPError
# Python 3
except ImportError:
from urllib.request import urlopen, HTTPError
import QCutils as qcu
from decorators import retry, printstatus
###############################################################################
###############################################################################
###############################################################################
@printstatus('Creating basic catalog summary')
def basic_cat_sum(catalog, dirname, dup1, dup2, timewindow, distwindow):
"""Gather basic catalog summary statistics."""
lines = []
lines.append('Catalog name: %s\n\n' % dirname[:-9].upper())
lines.append('First date in catalog: %s\n' % catalog['time'].min())
lines.append('Last date in catalog: %s\n\n' % catalog['time'].max())
lines.append('Total number of events: %s\n\n' % len(catalog))
lines.append('Minimum latitude: %s\n' % catalog['latitude'].min())
lines.append('Maximum latitude: %s\n' % catalog['latitude'].max())
lines.append('Minimum longitude: %s\n' % catalog['longitude'].min())
lines.append('Maximum longitude: %s\n\n' % catalog['longitude'].max())
lines.append('Minimum depth: %s\n' % catalog['depth'].min())
lines.append('Maximum depth: %s\n' % catalog['depth'].max())
lines.append('Number of 0 km depth events: %s\n'
% len(catalog[catalog['depth'] == 0]))
lines.append('Number of NaN depth events: %s\n\n'
% len(catalog[pd.isnull(catalog['depth'])]))
lines.append('Minimum magnitude: %s\n' % catalog['mag'].min())
lines.append('Maximum magnitude: %s\n' % catalog['mag'].max())
lines.append('Number of 0 magnitude events: %s\n'
% len(catalog[catalog['mag'] == 0]))
lines.append('Number of NaN magnitude events: %s\n\n'
% len(catalog[pd.isnull(catalog['mag'])]))
lines.append('Number of possible duplicates (%ss and %skm threshold): %d\n'
% (timewindow, distwindow, dup1))
lines.append('Number of possible duplicates (16s and 100km threshold): %d'
% dup2)
with open('%s_catalogsummary.txt' % dirname, 'w') as sumfile:
for line in lines:
sumfile.write(line)
def largest_ten(catalog, dirname):
"""Make a list of the 10 events with largest magnitude."""
catalog = catalog.sort_values(by='mag', ascending=False)
topten = catalog.head(n=10)
topten = topten[['time', 'id', 'latitude', 'longitude', 'depth', 'mag']]
with open('%s_largestten.txt' % dirname, 'w') as magfile:
for event in topten.itertuples():
line = ' '.join([str(x) for x in event[1:]]) + '\n'
magfile.write(line)
@printstatus('Finding possible duplicates')
def list_duplicates(catalog, dirname, timewindow=2, distwindow=15,
magwindow=None, minmag=-5, locfilter=None):
"""Make a list of possible duplicate events."""
catalog.loc[:, 'convtime'] = [' '.join(x.split('T'))
for x in catalog['time'].tolist()]
catalog.loc[:, 'convtime'] = catalog['convtime'].astype('datetime64[ns]')
catalog = catalog[catalog['mag'] >= minmag]
if locfilter:
catalog = catalog[catalog['place'].str.contains(locfilter, na=False)]
cat = catalog[['time', 'convtime', 'id', 'latitude', 'longitude', 'depth',
'mag']].copy()
cat.loc[:, 'time'] = [qcu.to_epoch(x) for x in cat['time']]
duplines1 = [('Possible duplicates using %ss time threshold and %skm '
'distance threshold\n') % (timewindow, distwindow),
'***********************\n'
'date time id latitude longitude depth magnitude '
'(distance) (Δ time) (Δ magnitude)\n']
duplines2 = [('\n\nPossible duplicates using 16s time threshold and 100km '
'distance threshold\n'),
'***********************\n'
'date time id latitude longitude depth magnitude '
'(distance) (Δ time) (Δ magnitude)\n']
sep = '-----------------------\n'
thresh1dupes, thresh2dupes = 0, 0
for event in cat.itertuples():
trimdf = cat[cat['convtime'].between(event.convtime, event.convtime
+ pd.Timedelta(seconds=16), inclusive=False)]
if len(trimdf) != 0:
for tevent in trimdf.itertuples():
dist = gps2dist_azimuth(event.latitude, event.longitude,
tevent.latitude, tevent.longitude)[0] / 1000.
if dist < 100:
dtime = (event.convtime - tevent.convtime).total_seconds()
dmag = event.mag - tevent.mag
diffs = map('{:.2f}'.format, [dist, dtime, dmag])
dupline1 = ' '.join([str(x) for x in event[1:]]) + ' ' +\
' '.join(diffs) + '\n'
dupline2 = ' '.join([str(x) for x in tevent[1:]]) + '\n'
duplines2.extend((sep, dupline1, dupline2))
thresh2dupes += 1
if (dist < distwindow) and (abs(dtime) < timewindow):
duplines1.extend((sep, dupline1, dupline2))
thresh1dupes += 1
continue
with open('%s_duplicates.txt' % dirname, 'w') as dupfile:
for dupline in duplines1:
dupfile.write(dupline)
for dupline in duplines2:
dupfile.write(dupline)
return thresh1dupes, thresh2dupes
@printstatus('Mapping earthquake locations')
def map_detecs(catalog, dirname, minmag=-5, mindep=-50, title=''):
"""Make scatter plot of detections with magnitudes (if applicable)."""
catalog = catalog[(catalog['mag'] >= minmag)
& (catalog['depth'] >= mindep)].copy()
if len(catalog) == 0:
print('\nCatalog contains no events deeper than %s.' % mindep)
return
# define map bounds
lllat, lllon, urlat, urlon, _, _, _, clon = qcu.get_map_bounds(catalog)
plt.figure(figsize=(12, 7))
mplmap = plt.axes(projection=ccrs.PlateCarree(central_longitude=clon))
mplmap.set_extent([lllon, urlon, lllat, urlat], ccrs.PlateCarree())
mplmap.coastlines('50m', facecolor='none')
# if catalog has magnitude data
if not catalog['mag'].isnull().all():
bins = [0, 5, 6, 7, 8, 15]
binnames = ['< 5', '5-6', '6-7', '7-8', r'$\geq$8']
binsizes = [10, 25, 50, 100, 400]
bincolors = ['g', 'b', 'y', 'r', 'r']
binmarks = ['o', 'o', 'o', 'o', '*']
catalog.loc[:, 'maggroup'] = pd.cut(catalog['mag'], bins,
labels=binnames)
for i, label in enumerate(binnames):
mgmask = catalog['maggroup'] == label
rcat = catalog[mgmask]
lons, lats = list(rcat['longitude']), list(rcat['latitude'])
if len(lons) > 0:
mplmap.scatter(lons, lats, s=binsizes[i], marker=binmarks[i],
c=bincolors[i], label=binnames[i], alpha=0.8,
zorder=10, transform=ccrs.PlateCarree())
plt.legend(loc='lower left', title='Magnitude')
# if catalog does not have magnitude data
else:
lons, lats = list(catalog['longitude']), list(catalog['latitude'])
mplmap.scatter(lons, lats, s=15, marker='x', c='r', zorder=10)
mplmap.add_feature(cfeature.NaturalEarthFeature('cultural',
'admin_1_states_provinces_lines', '50m', facecolor='none',
edgecolor='k', zorder=9))
mplmap.add_feature(cfeature.BORDERS)
plt.title(title, fontsize=20)
plt.subplots_adjust(left=0.05, right=0.95, top=0.95, bottom=0.05)
if mindep != -50:
plt.savefig('%s_morethan%sdetecs.png' % (dirname, mindep), dpi=300)
else:
plt.savefig('%s_mapdetecs.png' % dirname, dpi=300)
plt.close()
@printstatus('Mapping earthquake density')
def map_detec_nums(catalog, dirname, title='', numcolors=16, rmin=77, rmax=490,
minmag=-5, pltevents=True):
"""Map detections and a grid of detection density. rmax=510 is white,
rmin=0 is black.
"""
# generate bounds for map
mask = catalog['mag'] >= minmag
lllat, lllon, urlat, urlon, gridsize, hgridsize, _, clon = \
qcu.get_map_bounds(catalog[mask])
catalog = qcu.add_centers(catalog, gridsize)
groupedlatlons, _, cmax = qcu.group_lat_lons(catalog, minmag=minmag)
# print message if there are no detections with magnitudes above minmag
if cmax == 0:
print("No detections over magnitude %s" % minmag)
# create color gradient from light red to dark red
colors = qcu.range2rgb(rmin, rmax, numcolors)
# put each center into its corresponding color group
colorgroups = list(np.linspace(0, cmax, numcolors))
groupedlatlons.loc[:, 'group'] = np.digitize(groupedlatlons['count'],
colorgroups)
# create map
plt.figure(figsize=(12, 7))
mplmap = plt.axes(projection=ccrs.PlateCarree(central_longitude=clon))
mplmap.set_extent([lllon, urlon, lllat, urlat], ccrs.PlateCarree())
mplmap.coastlines('50m')
mplmap.add_feature(cfeature.BORDERS)
mplmap.add_feature(cfeature.NaturalEarthFeature('cultural',
'admin_1_states_provinces_lines', '50m', facecolor='none',
edgecolor='k', zorder=9))
plt.title(title, fontsize=20)
plt.subplots_adjust(left=0.01, right=0.9, top=0.95, bottom=0.05)
# create color map based on rmin and rmax
cmap = LinearSegmentedColormap.from_list('CM', colors)._resample(numcolors)
# make dummy plot for setting color bar
colormesh = mplmap.pcolormesh(colors, colors, colors, cmap=cmap, alpha=1,
vmin=0, vmax=cmax)
# format color bar
cbticks = [x for x in np.linspace(0, cmax, numcolors+1)]
cbar = plt.colorbar(colormesh, ticks=cbticks)
cbar.ax.set_yticklabels([('%.0f' % x) for x in cbticks])
cbar.set_label('# of detections', rotation=270, labelpad=15)
# plot rectangles with color corresponding to number of detections
for center, _, cgroup in groupedlatlons.itertuples():
minlat, maxlat = center[0]-hgridsize, center[0]+hgridsize
minlon, maxlon = center[1]-hgridsize, center[1]+hgridsize
glats = [minlat, maxlat, maxlat, minlat]
glons = [minlon, minlon, maxlon, maxlon]
color = colors[cgroup-1]
qcu.draw_grid(glats, glons, color, alpha=0.8)
# if provided, plot detection epicenters
if pltevents and not catalog['mag'].isnull().all():
magmask = catalog['mag'] >= minmag
lons = list(catalog['longitude'][magmask])
lats = list(catalog['latitude'][magmask])
mplmap.scatter(lons, lats, c='k', s=7, marker='x', zorder=5)
elif catalog['mag'].isnull().all():
lons = list(catalog['longitude'])
lats = list(catalog['latitude'])
mplmap.scatter(lons, lats, c='k', s=7, marker='x', zorder=5)
plt.savefig('%s_eqdensity.png' % dirname, dpi=300)
plt.close()
@printstatus('Making histogram of given parameter')
def make_hist(catalog, param, binsize, dirname, title='', xlabel='',
countlabel=False, maxval=None):
"""Plot histogram grouped by some parameter."""
paramlist = catalog[pd.notnull(catalog[param])][param].tolist()
minparam, maxparam = min(paramlist), max(paramlist)
paramdown = qcu.round2bin(minparam, binsize, 'down')
paramup = qcu.round2bin(maxparam, binsize, 'up')
numbins = int((paramup-paramdown) / binsize)
labelbuff = float(paramup-paramdown) / numbins * 0.5
diffs = [abs(paramlist[i+1]-paramlist[i]) for i in range(len(paramlist))
if i+1 < len(paramlist)]
diffs = [round(x, 1) for x in diffs if x > 0]
plt.figure(figsize=(10, 6))
plt.title(title, fontsize=20)
plt.xlabel(xlabel, fontsize=14)
plt.ylabel('Count', fontsize=14)
if param == 'ms':
parambins = np.linspace(paramdown, paramup, numbins+1)
plt.xlim(paramdown, paramup)
else:
parambins = np.linspace(paramdown, paramup+binsize,
numbins+2) - binsize/2.
plt.xlim(paramdown-binsize/2., paramup+binsize/2.)
phist = plt.hist(paramlist, parambins, alpha=0.7, color='b', edgecolor='k')
maxbarheight = max([phist[0][x] for x in range(numbins)] or [0])
labely = maxbarheight / 50.
plt.subplots_adjust(left=0.1, right=0.95, top=0.95, bottom=0.11)
if maxval:
plt.xlim(xmax=maxval)
plt.ylim(0, maxbarheight*1.1+0.1)
# put count numbers above the bars if countlabel=True
if countlabel:
for i in range(numbins):
plt.text(phist[1][i]+labelbuff, phist[0][i]+labely,
'%0.f' % phist[0][i], size=12, ha='center')
if maxval:
plt.savefig('%s_zoom%shistogram.png' % (dirname, param), dpi=300)
else:
plt.savefig('%s_%shistogram.png' % (dirname, param), dpi=300)
plt.close()
@printstatus('Making histogram of given time duration')
def make_time_hist(catalog, timelength, dirname, title=''):
"""Make histogram either by hour of the day or by date."""
timelist = catalog['time']
plt.figure(figsize=(10, 6))
plt.title(title, fontsize=20)
plt.ylabel('Count', fontsize=14)
if timelength == 'hour':
lons = np.linspace(-180, 180, 25).tolist()
hours = np.linspace(-12, 12, 25).tolist()
tlonlist = catalog.loc[:, ['longitude', 'time']]
tlonlist.loc[:, 'rLon'] = qcu.round2lon(tlonlist['longitude'])
tlonlist.loc[:, 'hour'] = [int(x.split('T')[1].split(':')[0])
for x in tlonlist['time']]
tlonlist.loc[:, 'rhour'] = [x.hour + hours[lons.index(x.rLon)]
for x in tlonlist.itertuples()]
tlonlist.loc[:, 'rhour'] = [x+24 if x < 0 else x-24 if x > 23 else x
for x in tlonlist['rhour']]
hourlist = tlonlist.rhour.tolist()
hourbins = np.linspace(-0.5, 23.5, 25)
plt.hist(hourlist, hourbins, alpha=1, color='b', edgecolor='k')
plt.xlabel('Hour of the Day', fontsize=14)
plt.xlim(-0.5, 23.5)
elif timelength == 'day':
daylist = [x.split('T')[0] for x in timelist]
daydf = pd.DataFrame({'date': daylist})
daydf['date'] = daydf['date'].astype('datetime64[ns]')
daydf = daydf.groupby([daydf['date'].dt.year,
daydf['date'].dt.month,
daydf['date'].dt.day]).count()
eqdates = daydf.index.tolist()
counts = daydf.date.tolist()
eqdates = [date(x[0], x[1], x[2]) for x in eqdates]
minday, maxday = min(eqdates), max(eqdates)
plt.bar(eqdates, counts, alpha=1, color='b', width=1)
plt.xlabel('Date', fontsize=14)
plt.xlim(minday, maxday)
plt.subplots_adjust(left=0.1, right=0.95, top=0.95, bottom=0.11)
plt.savefig('%s_%shistogram.png' % (dirname, timelength), dpi=300)
plt.close()
@printstatus('Graphing mean time separation')
def graph_time_sep(catalog, dirname):
"""Make bar graph of mean time separation between events by date."""
catalog.loc[:, 'convtime'] = [' '.join(x.split('T')).split('.')[0]
for x in catalog['time'].tolist()]
catalog.loc[:, 'convtime'] = catalog['convtime'].astype('datetime64[ns]')
catalog.loc[:, 'dt'] = catalog.convtime.diff().astype('timedelta64[ns]')
catalog.loc[:, 'dtmin'] = catalog['dt'] / pd.Timedelta(minutes=1)
mindate = catalog['convtime'].min()
maxdate = catalog['convtime'].max()
fig = plt.figure(figsize=(10, 6))
axfull = fig.add_subplot(111)
axfull.set_ylabel('Time separation (min)', fontsize=14, labelpad=20)
axfull.spines['top'].set_color('none')
axfull.spines['bottom'].set_color('none')
axfull.spines['left'].set_color('none')
axfull.spines['right'].set_color('none')
axfull.tick_params(labelcolor='w', top='off', bottom='off',
left='off', right='off')
if maxdate - mindate < pd.Timedelta(days=1460):
# time separation between events
fig.add_subplot(311)
plt.plot(catalog['convtime'], catalog['dtmin'], alpha=1, color='b')
plt.xlabel('Date')
plt.title('Time separation between events')
plt.xlim(mindate, maxdate)
plt.ylim(0)
# maximum monthly time separation
fig.add_subplot(312)
month_max = catalog.resample('1M', on='convtime').max()['dtmin']
months = month_max.index.map(lambda x: x.strftime('%Y-%m')).tolist()
months = [date(int(x[:4]), int(x[-2:]), 1) for x in months]
plt.bar(months, month_max.tolist(), color='b', alpha=1, width=31,
edgecolor='k')
plt.xlabel('Month')
plt.title('Maximum event separation by month')
plt.xlim(mindate - pd.Timedelta(days=15),
maxdate - pd.Timedelta(days=16))
# median monthly time separation
fig.add_subplot(313)
month_med = catalog.resample('1M', on='convtime').median()['dtmin']
plt.bar(months, month_med.tolist(), color='b', alpha=1, width=31,
edgecolor='k')
plt.xlabel('Month')
plt.title('Median event separation by month')
plt.tight_layout()
plt.xlim(mindate - pd.Timedelta(days=15),
maxdate - pd.Timedelta(days=16))
else:
# time separation between events
fig.add_subplot(311)
plt.plot(catalog['convtime'], catalog['dtmin'], alpha=1, color='b')
plt.xlabel('Date')
plt.title('Time separation between events')
plt.xlim(mindate, maxdate)
plt.ylim(0)
# maximum yearly time separation
fig.add_subplot(312)
year_max = catalog.resample('1Y', on='convtime').max()['dtmin']
years = year_max.index.map(lambda x: x.strftime('%Y')).tolist()
years = [date(int(x[:4]), 1, 1) for x in years]
plt.bar(years, year_max.tolist(), color='b', alpha=1, width=365,
edgecolor='k')
plt.xlabel('Year')
plt.title('Maximum event separation by year')
plt.xlim(mindate - pd.Timedelta(days=183),
maxdate - pd.Timedelta(days=183))
# median yearly time separation
fig.add_subplot(313)
year_med = catalog.resample('1Y', on='convtime').median()['dtmin']
plt.bar(years, year_med.tolist(), color='b', alpha=1, width=365,
edgecolor='k')
plt.xlabel('Year')
plt.title('Median event separation by year')
plt.tight_layout()
plt.xlim(mindate - pd.Timedelta(days=183),
maxdate - pd.Timedelta(days=183))
plt.savefig('%s_timeseparation.png' % dirname, dpi=300)
plt.close()
@printstatus('Graphing median magnitude by time')
def med_mag(catalog, dirname):
"""Make a bar graph of median event magnitude by year."""
catalog.loc[:, 'convtime'] = [' '.join(x.split('T')).split('.')[0]
for x in catalog['time'].tolist()]
catalog.loc[:, 'convtime'] = catalog['convtime'].astype('datetime64[ns]')
mindate = catalog['convtime'].min()
maxdate = catalog['convtime'].max()
if maxdate - mindate < pd.Timedelta(days=1460):
month_max = catalog.resample('1M', on='convtime').max()['mag']
months = month_max.index.map(lambda x: x.strftime('%Y-%m')).tolist()
months = [date(int(x[:4]), int(x[-2:]), 1) for x in months]
month_medmag = catalog.resample('1M', on='convtime').median()['mag']
fig = plt.figure(figsize=(10, 6))
ax = fig.add_subplot(111)
ax.tick_params(bottom='off')
plt.bar(months, month_medmag.tolist(), color='b', edgecolor='k',
alpha=1, width=31)
plt.xlabel('Month', fontsize=14)
plt.ylabel('Magnitude', fontsize=14)
plt.title('Monthly Median Magnitude', fontsize=20)
plt.xlim(min(months) - pd.Timedelta(days=15),
max(months) + pd.Timedelta(days=15))
else:
year_max = catalog.resample('1Y', on='convtime').max()['mag']
years = year_max.index.map(lambda x: x.strftime('%Y')).tolist()
years = [date(int(x[:4]), 1, 1) for x in years]
year_medmag = catalog.resample('1Y', on='convtime').median()['mag']
fig = plt.figure(figsize=(10, 6))
ax = fig.add_subplot(111)
ax.tick_params(bottom='off')
plt.bar(years, year_medmag.tolist(), color='b', edgecolor='k', alpha=1,
width=365)
plt.xlabel('Year', fontsize=14)
plt.ylabel('Magnitude', fontsize=14)
plt.title('Yearly Median Magnitude', fontsize=20)
plt.xlim(min(years) - pd.Timedelta(days=183),
max(years) - pd.Timedelta(days=183))
plt.savefig('%s_medianmag' % dirname, dpi=300)
plt.close()
@printstatus('Graphing magnitude completeness')
def cat_mag_comp(catalog, dirname, magbin=0.1):
"""Plot catalog magnitude completeness."""
catalog = catalog[pd.notnull(catalog['mag'])]
mags = np.array(catalog['mag'])
mags = np.around(mags, 1)
minmag, maxmag = min(min(mags), 0), max(mags)
mag_centers = np.arange(minmag, maxmag + 2*magbin, magbin)
cdf = np.zeros(len(mag_centers))
for idx in range(len(cdf)):
cdf[idx] = np.count_nonzero(
~np.isnan(mags[mags >= mag_centers[idx]-0.001]))
mag_edges = np.arange(minmag - magbin/2., maxmag+magbin, magbin)
g_r, _ = np.histogram(mags, mag_edges)
idx = list(g_r).index(max(g_r))
mc_est = mag_centers[idx]
try:
mc_est, bvalue, avalue, lval, mc_bins, std_dev = qcu.WW2000(mc_est,
mags, magbin)
except:
mc_est = mc_est + 0.3
mc_bins = np.arange(0, maxmag + magbin/2., magbin)
bvalue = np.log10(np.exp(1))/(np.average(mags[mags >= mc_est])
- (mc_est-magbin/2.))
avalue = np.log10(len(mags[mags >= mc_est])) + bvalue*mc_est
log_l = avalue-bvalue*mc_bins
lval = 10.**log_l
std_dev = bvalue/sqrt(len(mags[mags >= mc_est]))
plt.figure(figsize=(8, 6))
plt.scatter(mag_centers[:len(g_r)], g_r, edgecolor='r', marker='o',
facecolor='none', label='Incremental')
plt.scatter(mag_centers, cdf, c='k', marker='+', label='Cumulative')
plt.axvline(mc_est, c='r', linestyle='--', label='Mc = %2.1f' % mc_est)
plt.plot(mc_bins, lval, c='k', linestyle='--',
label='B = %1.3f%s%1.3f' % (bvalue, u'\u00B1', std_dev))
ax1 = plt.gca()
ax1.set_yscale('log')
max_count = np.amax(cdf) + 100000
ax1.set_xlim([minmag, maxmag])
ax1.set_ylim([1, max_count])
plt.title('Frequency-Magnitude Distribution', fontsize=18)
plt.xlabel('Magnitude', fontsize=14)
plt.ylabel('Log10 Count', fontsize=14)
plt.legend(numpoints=1)
plt.savefig('%s_catmagcomp.png' % dirname, dpi=300)
plt.close()
@printstatus('Graphing magnitude versus time for each earthquake')
def graph_mag_time(catalog, dirname):
"""Plot magnitudes vs. origin time."""
catalog = catalog[pd.notnull(catalog['mag'])]
catalog.loc[:, 'convtime'] = [' '.join(x.split('T')).split('.')[0]
for x in catalog['time'].tolist()]
catalog.loc[:, 'convtime'] = catalog['convtime'].astype('datetime64[ns]')
times = catalog['time'].copy()
mags = catalog['mag'].copy()
plt.figure(figsize=(10, 6))
plt.xlabel('Date', fontsize=14)
plt.ylabel('Magnitude', fontsize=14)
plt.plot_date(times, mags, alpha=0.7, markersize=2, c='b')
plt.xlim(min(times), max(times))
plt.title('Magnitude vs. Time', fontsize=20)
plt.savefig('%s_magvtime.png' % dirname, dpi=300)
plt.close()
@printstatus('Graphing event count by date and magnitude')
def graph_mag_count(catalog, dirname):
"""Graph event count grouped by magnitude and by date."""
catalog.loc[:, 'convtime'] = [' '.join(x.split('T')).split('.')[0]
for x in catalog['time'].tolist()]
catalog.loc[:, 'convtime'] = catalog['convtime'].astype('datetime64[ns]')
mindate, maxdate = catalog['convtime'].min(), catalog['convtime'].max()
bincond = maxdate - mindate < pd.Timedelta(days=1460)
barwidth = 31 if bincond else 365
timedelt = pd.Timedelta(days=barwidth/2.)
minbin = qcu.round2bin(catalog['mag'].min()-0.1, 1, 'down')
maxbin = qcu.round2bin(catalog['mag'].max()+0.1, 1, 'up')
bins = np.arange(minbin, maxbin+0.1, 1)
catalog.loc[:, 'magbin'] = pd.cut(catalog['mag'], bins=bins, right=True)
maggroups = catalog['magbin'].sort_values().unique()
fig, axlist = plt.subplots(len(maggroups), sharex=True)
fig.set_size_inches(10, 14, forward=True)
for i, mbin in enumerate(maggroups):
trimcat = catalog[catalog['magbin'] == mbin]
if len(trimcat) == 0:
continue
datelist = [x.split('T')[0] for x in trimcat['time']]
datedf = pd.DataFrame({'date': datelist})
datedf['date'] = datedf['date'].astype('datetime64[ns]')
datedf = datedf.groupby([datedf['date'].dt.year,
datedf['date'].dt.month]).count() if bincond\
else datedf.groupby([datedf['date'].dt.year]).count()
evdates = datedf.index.tolist()
counts = datedf.date.tolist()
evdates = [date(x[0], x[1], 1) if bincond else date(x, 1, 1)
for x in evdates]
axlist[i].bar(evdates, counts, alpha=1, color='b', width=barwidth,
edgecolor='k')
axlist[i].set_ylabel('%d-%d' % (bins[i], bins[i+1]), fontsize=10)
plt.xlim(mindate - timedelt, maxdate - timedelt)
plt.ylim(0, max(counts))
axlist[i].get_yaxis().set_label_coords(-0.1, 0.5)
plt.xlabel('Date', fontsize=14)
for ax in axlist[:-1]:
ax.xaxis.set_ticks_position('none')
plt.savefig('%s_magtimecount.png' % dirname, dpi=300)
plt.close()
@printstatus('Graphing cumulative moment release')
def cumul_moment_release(catalog, dirname):
"""Graph cumulative moment release."""
catalog = catalog[
|
pd.notnull(catalog['mag'])
|
pandas.notnull
|
import matplotlib.pyplot as plt
import pandas as pd
from powersimdata.network.model import ModelImmutables, area_to_loadzone
from powersimdata.scenario.scenario import Scenario
from postreise.analyze.generation.capacity import sum_capacity_by_type_zone
from postreise.analyze.generation.summarize import sum_generation_by_type_zone
def plot_bar_generation_vs_capacity(
areas,
area_types=None,
scenario_ids=None,
scenario_names=None,
time_range=None,
time_zone=None,
custom_data=None,
resource_types=None,
resource_labels=None,
horizontal=False,
):
"""Plot any number of scenarios as bar or horizontal bar charts with two columns per
scenario - generation and capacity.
:param list/str areas: list of area(s), each area is one of *loadzone*, *state*,
*state abbreviation*, *interconnect*, *'all'*.
:param list/str area_types: list of area_type(s), each area_type is one of
*'loadzone'*, *'state'*, *'state_abbr'*, *'interconnect'*, defaults to None.
:param int/list/str scenario_ids: list of scenario id(s), defaults to None.
:param list/str scenario_names: list of scenario name(s) of same len as scenario
ids, defaults to None.
:param tuple time_range: [start_timestamp, end_timestamp] where each time stamp
is pandas.Timestamp/numpy.datetime64/datetime.datetime. If None, the entire
time range is used for the given scenario.
:param str time_zone: new time zone, defaults to None, which uses UTC.
:param list custom_data: list of dictionaries with each element being
hand-generated data as returned by :func:`make_gen_cap_custom_data`, defaults
to None.
:param list/str resource_types: list of resource type(s) to show, defaults to None,
which shows all available resources in the area of the corresponding scenario.
:param dict resource_labels: a dictionary with keys being resource_types and values
being labels to show in the plots, defaults to None, which uses
resource_types as labels.
:param bool horizontal: display bars horizontally, default to False.
"""
if isinstance(areas, str):
areas = [areas]
if isinstance(area_types, str):
area_types = [area_types]
if not area_types:
area_types = [None] * len(areas)
if len(areas) != len(area_types):
raise ValueError(
"ERROR: if area_types are provided, it should have the same number of entries with areas."
)
if not scenario_ids:
scenario_ids = []
if isinstance(scenario_ids, (int, str)):
scenario_ids = [scenario_ids]
if isinstance(scenario_names, str):
scenario_names = [scenario_names]
if scenario_names and len(scenario_names) != len(scenario_ids):
raise ValueError(
"ERROR: if scenario names are provided, number of scenario names must match number of scenario ids"
)
if not custom_data:
custom_data = {}
if len(scenario_ids) + len(custom_data) <= 1:
raise ValueError(
"ERROR: must include at least two scenario ids and/or custom data"
)
if isinstance(resource_types, str):
resource_types = [resource_types]
if not resource_labels:
resource_labels = dict()
if not isinstance(resource_labels, dict):
raise TypeError("ERROR: resource_labels should be a dictionary")
all_loadzone_data = {}
scenario_data = {}
for i, sid in enumerate(scenario_ids):
scenario = Scenario(sid)
mi = ModelImmutables(scenario.info["grid_model"])
all_loadzone_data[sid] = {
"gen": sum_generation_by_type_zone(scenario, time_range, time_zone).rename(
columns=mi.zones["id2loadzone"]
),
"cap": sum_capacity_by_type_zone(scenario).rename(
columns=mi.zones["id2loadzone"]
),
}
scenario_data[sid] = {
"name": scenario_names[i] if scenario_names else scenario.info["name"],
"grid_model": mi.model,
"gen": {"label": "Generation", "unit": "TWh", "data": {}},
"cap": {"label": "Capacity", "unit": "GW", "data": {}},
}
for area, area_type in zip(areas, area_types):
for sid in scenario_ids:
loadzone_set = area_to_loadzone(
scenario_data[sid]["grid_model"], area, area_type
)
scenario_data[sid]["gen"]["data"][area] = (
all_loadzone_data[sid]["gen"][loadzone_set]
.sum(axis=1)
.divide(1e6)
.astype("float")
.round(2)
.to_dict()
)
scenario_data[sid]["cap"]["data"][area] = (
all_loadzone_data[sid]["cap"][loadzone_set]
.sum(axis=1)
.divide(1e3)
.astype("float")
.round(2)
.to_dict()
)
for c_data in custom_data:
scenario_data[c_data["name"]] = c_data
for area in areas:
if not resource_types:
area_resource_types = sorted(
set(
r
for sd in scenario_data.values()
for side in ["gen", "cap"]
for r, v in sd[side]["data"][area].items()
if v > 0
)
)
else:
area_resource_types = resource_types
ax_data_list = []
for side in ["gen", "cap"]:
ax_data = {}
for sd in scenario_data.values():
# If we don't have data for a resource type, set it to 0
ax_data[sd["name"]] = [
sd[side]["data"][area].get(r, 0) for r in area_resource_types
]
ax_data_list.append(
{
"title": f"""{sd[side]["label"]} ({sd[side]["unit"]})""",
"labels": [resource_labels.get(r, r) for r in area_resource_types],
"values": ax_data,
"unit": sd[side]["unit"],
}
)
if horizontal:
_construct_hbar_visuals(area, ax_data_list)
else:
_construct_bar_visuals(area, ax_data_list)
def _construct_bar_visuals(zone, ax_data_list):
"""Plot bar chart based on formatted data.
:param str zone: the zone name
:param list ax_data_list: a list of labels and values for each axis of the plot
"""
num_scenarios = len(ax_data_list[0]["values"].keys())
num_resource_types = len(ax_data_list[0]["labels"])
fig, axes = plt.subplots(
1, 2, figsize=(1.5 * num_scenarios * num_resource_types, 6)
)
plt.suptitle(zone, fontsize=30, verticalalignment="bottom")
plt.subplots_adjust(wspace=3 / (num_scenarios * num_resource_types))
for ax_data, ax in zip(ax_data_list, axes):
df = pd.DataFrame(ax_data["values"], index=ax_data["labels"])
df.plot(kind="bar", ax=ax, edgecolor="white", linewidth=2)
ax.set_title(ax_data["title"], fontsize=25)
ax.tick_params(axis="both", which="both", labelsize=20)
ax.spines["right"].set_visible(False)
ax.spines["top"].set_visible(False)
ax.spines["left"].set_visible(False)
ax.set_xlabel("")
ax.set_xticklabels(
ax.get_xticklabels(), rotation=45, horizontalalignment="right"
)
ax.set_yticks([])
ax.set_ylim(top=1.3 * ax.get_ylim()[1])
ax.legend(bbox_to_anchor=(-0.03, -0.4), loc="upper left", fontsize=16)
for p in ax.patches:
b = p.get_bbox()
ax.annotate(
_get_bar_display_val(b.y1),
((b.x1 + b.x0) / 2, b.y1 + 0.02 * ax.get_ylim()[1]),
fontsize=10,
rotation="horizontal",
horizontalalignment="center",
)
axes[1].get_legend().remove()
plt.show()
def _construct_hbar_visuals(zone, ax_data_list):
"""Plot horizontal bar chart based on formatted data.
:param str zone: the zone name.
:param list ax_data_list: a list of labels and values for each axis of the plot
"""
num_scenarios = len(ax_data_list[0]["values"].keys())
num_resource_types = len(ax_data_list[0]["labels"])
fig, axes = plt.subplots(
1, 2, figsize=(20, 0.7 * num_scenarios * num_resource_types)
)
plt.suptitle(zone, fontsize=30, verticalalignment="bottom")
plt.subplots_adjust(wspace=1)
for ax_data, ax in zip(ax_data_list, axes):
df =
|
pd.DataFrame(ax_data["values"], index=ax_data["labels"])
|
pandas.DataFrame
|
#!/usr/bin/python
# _*_coding:utf-8_*_
# Import modules
import numpy as np
import pandas as pd
from collections import defaultdict
from scipy.stats import f_oneway, shapiro, chi2_contingency
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
# Custom modules
from utils import numeric, categorical
from models import forest_cv_rfe
# Normality test
def normality_test(df, variable, alpha=0.03):
""" Calculate Shapiro - Wilks normality test."""
stat, p = shapiro(df.loc[:, [variable]])
if p < alpha:
print("\t- {} looks Gaussian, fail to reject H0.".format(variable))
else:
print("\t- {} doesn't look Gaussian, reject H0.".format(variable))
return None
# Anova test
def anova_test2(df, v_cat, v_num):
# Remove nulls
df = df.loc[df[v_num].notnull(), [v_cat, v_num]].copy()
# Calculate the classes
classes = set(df[v_cat])
# Create the lists
obs = [list(df.loc[df[v_cat] == i, v_num]) for i in classes]
# Calculate anova
try:
anova = f_oneway(*obs)[1]
except TypeError: # Error: df slice with no nulls values there is only on class of the categorical variable.
anova = 0
return anova
def chisquare_test(df, object_variable='Survived', verbosity=False):
# Define the numerical columns to study
cols_list = categorical(df, remove_ov=False)
# Calculate chitest for each categorical variable
if verbosity:
print("Chi-square test is performed with {} for each other categorical variables.".format(object_variable))
print("The results obtained are the following:")
# Result Dictionary
result_dict = {}
# For each other colum in dataset calculate the chi-square test
for col in cols_list:
# Get the survived and not survived
freq = df.groupby([col, object_variable]).size().unstack(fill_value=0).stack()
# Calculate the matrix of frequencies for each class:
v_index = set(df[object_variable])
total_obs = [list(freq[freq.index.get_level_values(1) == i]) for i in v_index]
# Chisquare test
crosstab = np.array(total_obs)
chi_test = chi2_contingency(crosstab)
# V Cramer
obs = np.sum(crosstab)
mini = min(crosstab.shape)-1
# Return results
result_dict[col] = chi_test[0]/(obs*mini)
if verbosity:
print("\t- {}: The p-value is {}".format(col, chi_test[0]/(obs*mini)))
return result_dict
def chisquare_matrix(df):
# Define empty dictionary
matrix = {}
# Determine the categorical variables of the dataframe
categorical_variables = categorical(df, remove_ov=False)
# For each variable calculate the Cramer's V test and add it to dictionary
for column in categorical_variables:
matrix[column] = chisquare_test(df, column)
# Convert dictionary of all test into a dataframe
matrix =
|
pd.DataFrame.from_dict(matrix)
|
pandas.DataFrame.from_dict
|
# -*- coding: utf-8 -*-
"""Deployment Response controller."""
import os
import uuid
import pandas as pd
import requests
from projects import models
from projects.controllers.utils import uuid_alpha
BROKER_URL = os.getenv("BROKER_URL", "http://default-broker.anonymous.svc.cluster.local")
class ResponseController:
def __init__(self, session):
self.session = session
def create_response(self, project_id: str, deployment_id: str, body: dict):
"""
Creates a response entry in logs file.
Parameters
----------
project_id : str
deployment_id : str
body : dict
"""
if "data" in body:
ndarray = pd.DataFrame(body["data"]["ndarray"])
if "names" in body["data"]:
names = body["data"]["names"]
ndarray.columns = names
body = ndarray.to_dict(orient="records")
if isinstance(body, dict):
body = [body]
responses = []
for record in body:
responses.append(
models.Response(
uuid=uuid_alpha(),
deployment_id=deployment_id,
body=record,
)
)
self.session.bulk_save_objects(responses)
self.session.commit()
responses = self.session.query(models.Response) \
.filter_by(deployment_id=deployment_id) \
.order_by(models.Response.created_at.asc()) \
.all()
d = []
if len(responses) > 0:
for response in responses:
d.append(response.body)
data =
|
pd.DataFrame(d)
|
pandas.DataFrame
|
# -*- coding: utf-8 -*-
# pylint: disable=E1101
# flake8: noqa
from datetime import datetime
import csv
import os
import sys
import re
import nose
import platform
from multiprocessing.pool import ThreadPool
from numpy import nan
import numpy as np
from pandas.io.common import DtypeWarning
from pandas import DataFrame, Series, Index, MultiIndex, DatetimeIndex
from pandas.compat import(
StringIO, BytesIO, PY3, range, long, lrange, lmap, u
)
from pandas.io.common import URLError
import pandas.io.parsers as parsers
from pandas.io.parsers import (read_csv, read_table, read_fwf,
TextFileReader, TextParser)
import pandas.util.testing as tm
import pandas as pd
from pandas.compat import parse_date
import pandas.lib as lib
from pandas import compat
from pandas.lib import Timestamp
from pandas.tseries.index import date_range
import pandas.tseries.tools as tools
from numpy.testing.decorators import slow
import pandas.parser
class ParserTests(object):
"""
Want to be able to test either C+Cython or Python+Cython parsers
"""
data1 = """index,A,B,C,D
foo,2,3,4,5
bar,7,8,9,10
baz,12,13,14,15
qux,12,13,14,15
foo2,12,13,14,15
bar2,12,13,14,15
"""
def read_csv(self, *args, **kwargs):
raise NotImplementedError
def read_table(self, *args, **kwargs):
raise NotImplementedError
def setUp(self):
import warnings
warnings.filterwarnings(action='ignore', category=FutureWarning)
self.dirpath = tm.get_data_path()
self.csv1 = os.path.join(self.dirpath, 'test1.csv')
self.csv2 = os.path.join(self.dirpath, 'test2.csv')
self.xls1 = os.path.join(self.dirpath, 'test.xls')
def construct_dataframe(self, num_rows):
df = DataFrame(np.random.rand(num_rows, 5), columns=list('abcde'))
df['foo'] = 'foo'
df['bar'] = 'bar'
df['baz'] = 'baz'
df['date'] = pd.date_range('20000101 09:00:00',
periods=num_rows,
freq='s')
df['int'] = np.arange(num_rows, dtype='int64')
return df
def generate_multithread_dataframe(self, path, num_rows, num_tasks):
def reader(arg):
start, nrows = arg
if not start:
return pd.read_csv(path, index_col=0, header=0, nrows=nrows,
parse_dates=['date'])
return pd.read_csv(path,
index_col=0,
header=None,
skiprows=int(start) + 1,
nrows=nrows,
parse_dates=[9])
tasks = [
(num_rows * i / num_tasks,
num_rows / num_tasks) for i in range(num_tasks)
]
pool = ThreadPool(processes=num_tasks)
results = pool.map(reader, tasks)
header = results[0].columns
for r in results[1:]:
r.columns = header
final_dataframe = pd.concat(results)
return final_dataframe
def test_converters_type_must_be_dict(self):
with tm.assertRaisesRegexp(TypeError, 'Type converters.+'):
self.read_csv(StringIO(self.data1), converters=0)
def test_empty_decimal_marker(self):
data = """A|B|C
1|2,334|5
10|13|10.
"""
self.assertRaises(ValueError, read_csv, StringIO(data), decimal='')
def test_empty_thousands_marker(self):
data = """A|B|C
1|2,334|5
10|13|10.
"""
self.assertRaises(ValueError, read_csv, StringIO(data), thousands='')
def test_multi_character_decimal_marker(self):
data = """A|B|C
1|2,334|5
10|13|10.
"""
self.assertRaises(ValueError, read_csv, StringIO(data), thousands=',,')
def test_empty_string(self):
data = """\
One,Two,Three
a,1,one
b,2,two
,3,three
d,4,nan
e,5,five
nan,6,
g,7,seven
"""
df = self.read_csv(StringIO(data))
xp = DataFrame({'One': ['a', 'b', np.nan, 'd', 'e', np.nan, 'g'],
'Two': [1, 2, 3, 4, 5, 6, 7],
'Three': ['one', 'two', 'three', np.nan, 'five',
np.nan, 'seven']})
tm.assert_frame_equal(xp.reindex(columns=df.columns), df)
df = self.read_csv(StringIO(data), na_values={'One': [], 'Three': []},
keep_default_na=False)
xp = DataFrame({'One': ['a', 'b', '', 'd', 'e', 'nan', 'g'],
'Two': [1, 2, 3, 4, 5, 6, 7],
'Three': ['one', 'two', 'three', 'nan', 'five',
'', 'seven']})
tm.assert_frame_equal(xp.reindex(columns=df.columns), df)
df = self.read_csv(
StringIO(data), na_values=['a'], keep_default_na=False)
xp = DataFrame({'One': [np.nan, 'b', '', 'd', 'e', 'nan', 'g'],
'Two': [1, 2, 3, 4, 5, 6, 7],
'Three': ['one', 'two', 'three', 'nan', 'five', '',
'seven']})
tm.assert_frame_equal(xp.reindex(columns=df.columns), df)
df = self.read_csv(StringIO(data), na_values={'One': [], 'Three': []})
xp = DataFrame({'One': ['a', 'b', np.nan, 'd', 'e', np.nan, 'g'],
'Two': [1, 2, 3, 4, 5, 6, 7],
'Three': ['one', 'two', 'three', np.nan, 'five',
np.nan, 'seven']})
tm.assert_frame_equal(xp.reindex(columns=df.columns), df)
# GH4318, passing na_values=None and keep_default_na=False yields
# 'None' as a na_value
data = """\
One,Two,Three
a,1,None
b,2,two
,3,None
d,4,nan
e,5,five
nan,6,
g,7,seven
"""
df = self.read_csv(
StringIO(data), keep_default_na=False)
xp = DataFrame({'One': ['a', 'b', '', 'd', 'e', 'nan', 'g'],
'Two': [1, 2, 3, 4, 5, 6, 7],
'Three': ['None', 'two', 'None', 'nan', 'five', '',
'seven']})
tm.assert_frame_equal(xp.reindex(columns=df.columns), df)
def test_read_csv(self):
if not compat.PY3:
if compat.is_platform_windows():
prefix = u("file:///")
else:
prefix = u("file://")
fname = prefix + compat.text_type(self.csv1)
# it works!
read_csv(fname, index_col=0, parse_dates=True)
def test_dialect(self):
data = """\
label1,label2,label3
index1,"a,c,e
index2,b,d,f
"""
dia = csv.excel()
dia.quoting = csv.QUOTE_NONE
df = self.read_csv(StringIO(data), dialect=dia)
data = '''\
label1,label2,label3
index1,a,c,e
index2,b,d,f
'''
exp = self.read_csv(StringIO(data))
exp.replace('a', '"a', inplace=True)
tm.assert_frame_equal(df, exp)
def test_dialect_str(self):
data = """\
fruit:vegetable
apple:brocolli
pear:tomato
"""
exp = DataFrame({
'fruit': ['apple', 'pear'],
'vegetable': ['brocolli', 'tomato']
})
dia = csv.register_dialect('mydialect', delimiter=':') # noqa
df = self.read_csv(StringIO(data), dialect='mydialect')
tm.assert_frame_equal(df, exp)
csv.unregister_dialect('mydialect')
def test_1000_sep(self):
data = """A|B|C
1|2,334|5
10|13|10.
"""
expected = DataFrame({
'A': [1, 10],
'B': [2334, 13],
'C': [5, 10.]
})
df = self.read_csv(StringIO(data), sep='|', thousands=',')
tm.assert_frame_equal(df, expected)
df = self.read_table(StringIO(data), sep='|', thousands=',')
tm.assert_frame_equal(df, expected)
def test_1000_sep_with_decimal(self):
data = """A|B|C
1|2,334.01|5
10|13|10.
"""
expected = DataFrame({
'A': [1, 10],
'B': [2334.01, 13],
'C': [5, 10.]
})
tm.assert_equal(expected.A.dtype, 'int64')
tm.assert_equal(expected.B.dtype, 'float')
tm.assert_equal(expected.C.dtype, 'float')
df = self.read_csv(
|
StringIO(data)
|
pandas.compat.StringIO
|
import pandas as pd
import numpy as np
from math import isnan
from sklearn import svm
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import cross_val_score
from sklearn.metrics import roc_curve
from evaluator import confusion_metric_drawer
from matplotlib import pyplot as plt
clipData = pd.read_csv('../data/clipTrainPure.csv', index_col=0)
trainSet = clipData[['nx', 'ny', 'rsx', 'rsy', 'lsx', 'lsy', 'rhx', 'rhy', 'lhx', 'lhy', 'rkx', 'rky', 'lkx', 'lky']]
labelTrain = clipData['label']
# print(np.array(labelTrain).tolist())
svc = svm.SVC(kernel='rbf')
svc.fit(trainSet, labelTrain)
testDf =
|
pd.read_csv('../data/clipTestPure.csv', index_col=0)
|
pandas.read_csv
|
import GoH.utilities
import json
import os
import pandas as pd
def queue_docs(base_dir, test, model_scheme, period):
"""
base_dir, model_scheme, period
"""
corpus_index = os.path.join(base_dir, 'corpora/{}/{}.txt'.format(model_scheme, period))
dtm = os.path.join(base_dir, 'dataframes/{}/{}-{}_dtm.csv'.format(test, model_scheme, period))
topic_labels = os.path.join(base_dir, 'dataframes/{}/{}-{}_topicLabels.csv'.format(test, model_scheme, period))
metadata = os.path.join(base_dir,'2017-05-corpus-stats/2017-05-Composite-OCR-statistics.csv')
return (corpus_index, dtm, topic_labels, metadata)
def doc_list(index_filename):
"""
"""
with open(index_filename) as data_file:
data = json.load(data_file)
docs =
|
pd.DataFrame.from_dict(data, orient='index')
|
pandas.DataFrame.from_dict
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/10/15 0015
# @Author : justin.郑 <EMAIL>
# @File : movie.py
# @Desc : 影视数据
# EBOT艺恩票房智库 https://www.endata.com.cn
import json
import os
import pandas as pd
import requests
import execjs
from gopup.movie.cons import headers
from gopup.utils.date_utils import today, day_last_date
def realtime_boxoffice():
"""
获取实时电影票房数据
数据来源:EBOT艺恩票房智库 https://www.endata.com.cn/BoxOffice
:return:
DataFrame
BoxOffice 实时票房(万)
Irank 排名
MovieName 影片名
boxPer 票房占比 (%)
movieDay 上映天数
sumBoxOffice 累计票房(万)
default_url 影片海报
"""
try:
url = "https://www.endata.com.cn/API/GetData.ashx"
data = {
"tdate": today(),
"MethodName": "BoxOffice_GetHourBoxOffice"
}
r = requests.post(url=url, data=data, headers=headers)
js = get_js('webDES.js')
docjs = execjs.compile(js)
res = docjs.call("webInstace.shell", r.text)
res_dict = json.loads(res)
if res_dict['Status'] == 1:
tmp = res_dict['Data']['Table1']
res_pd = pd.DataFrame(tmp)
res_pd = res_pd.drop(columns=['moblie_url', 'larger_url', 'mId', 'MovieImg'])
return res_pd
except Exception as e:
return None
def day_boxoffice(date=None):
"""
获取单日电影票房数据
数据来源:EBOT艺恩票房智库 https://www.endata.com.cn/BoxOffice
:param date: 日期
:return:
DataFrame
Irank 排名
MovieName 影片名
BoxOffice 单日票房(万)
BoxOffice_Up 环比变化
SumBoxOffice 累计票房(万)
default_url 影片海报
AvgPrice 平均票价
AvpPeoPle 场均人次
RapIndex 口碑指数
MovieDay 上映天数
"""
try:
if date == None:
edate = today()
else:
edate = date
sdate = day_last_date(edate, days=1)
url = "https://www.endata.com.cn/API/GetData.ashx"
data = {
"sdate": sdate,
"edate": edate,
"MethodName": "BoxOffice_GetDayBoxOffice"
}
r = requests.post(url=url, data=data, headers=headers)
js = get_js('webDES.js')
docjs = execjs.compile(js)
res = docjs.call("webInstace.shell", r.text)
res_dict = json.loads(res)
if res_dict['Status'] == 1:
tmp = res_dict['Data']['Table']
res_pd = pd.DataFrame(tmp)
res_pd = res_pd.drop(columns=['MovieImg', 'moblie_url', 'larger_url', 'MovieID', 'Director', 'BoxOffice1', 'IRank_pro', 'RapIndex'])
return res_pd
except Exception as e:
return None
def day_cinema(date=None):
"""
获取单日影院票房
:param date:
:return:
DataFrame
RowNum 排名
CinemaName 影院名称
TodayBox 单日票房(元)
TodayShowCount 单日场次
AvgPeople 场均人次
price 场均票价(元)
Attendance 上座率
"""
try:
url = "https://www.endata.com.cn/API/GetData.ashx"
data = {
"date": date,
"rowNum1": 1,
"rowNum2": 100,
"MethodName": "BoxOffice_GetCinemaDayBoxOffice"
}
r = requests.post(url=url, data=data, headers=headers)
js = get_js('webDES.js')
docjs = execjs.compile(js)
res = docjs.call("webInstace.shell", r.text)
res_dict = json.loads(res)
if res_dict['Status'] == 1:
tmp = res_dict['Data']['Table']
res_pd =
|
pd.DataFrame(tmp)
|
pandas.DataFrame
|
import numpy as np
import pytest
import pandas as pd
from pandas import (
Categorical,
DataFrame,
Index,
Series,
)
import pandas._testing as tm
dt_data = [
pd.Timestamp("2011-01-01"),
pd.Timestamp("2011-01-02"),
pd.Timestamp("2011-01-03"),
]
tz_data = [
pd.Timestamp("2011-01-01", tz="US/Eastern"),
pd.Timestamp("2011-01-02", tz="US/Eastern"),
pd.Timestamp("2011-01-03", tz="US/Eastern"),
]
td_data = [
pd.Timedelta("1 days"),
pd.Timedelta("2 days"),
pd.Timedelta("3 days"),
]
period_data = [
pd.Period("2011-01", freq="M"),
pd.Period("2011-02", freq="M"),
pd.Period("2011-03", freq="M"),
]
data_dict = {
"bool": [True, False, True],
"int64": [1, 2, 3],
"float64": [1.1, np.nan, 3.3],
"category": Categorical(["X", "Y", "Z"]),
"object": ["a", "b", "c"],
"datetime64[ns]": dt_data,
"datetime64[ns, US/Eastern]": tz_data,
"timedelta64[ns]": td_data,
"period[M]": period_data,
}
class TestConcatAppendCommon:
"""
Test common dtype coercion rules between concat and append.
"""
@pytest.fixture(params=sorted(data_dict.keys()))
def item(self, request):
key = request.param
return key, data_dict[key]
item2 = item
def _check_expected_dtype(self, obj, label):
"""
Check whether obj has expected dtype depending on label
considering not-supported dtypes
"""
if isinstance(obj, Index):
assert obj.dtype == label
elif isinstance(obj, Series):
if label.startswith("period"):
assert obj.dtype == "Period[M]"
else:
assert obj.dtype == label
else:
raise ValueError
def test_dtypes(self, item):
# to confirm test case covers intended dtypes
typ, vals = item
self._check_expected_dtype(Index(vals), typ)
self._check_expected_dtype(Series(vals), typ)
def test_concatlike_same_dtypes(self, item):
# GH 13660
typ1, vals1 = item
vals2 = vals1
vals3 = vals1
if typ1 == "category":
exp_data = Categorical(list(vals1) + list(vals2))
exp_data3 = Categorical(list(vals1) + list(vals2) + list(vals3))
else:
exp_data = vals1 + vals2
exp_data3 = vals1 + vals2 + vals3
# ----- Index ----- #
# index.append
res = Index(vals1).append(Index(vals2))
exp = Index(exp_data)
tm.assert_index_equal(res, exp)
# 3 elements
res = Index(vals1).append([Index(vals2), Index(vals3)])
exp = Index(exp_data3)
tm.assert_index_equal(res, exp)
# index.append name mismatch
i1 = Index(vals1, name="x")
i2 = Index(vals2, name="y")
res = i1.append(i2)
exp = Index(exp_data)
tm.assert_index_equal(res, exp)
# index.append name match
i1 = Index(vals1, name="x")
i2 = Index(vals2, name="x")
res = i1.append(i2)
exp = Index(exp_data, name="x")
tm.assert_index_equal(res, exp)
# cannot append non-index
with pytest.raises(TypeError, match="all inputs must be Index"):
Index(vals1).append(vals2)
with pytest.raises(TypeError, match="all inputs must be Index"):
Index(vals1).append([Index(vals2), vals3])
# ----- Series ----- #
# series.append
res = Series(vals1)._append(Series(vals2), ignore_index=True)
exp = Series(exp_data)
tm.assert_series_equal(res, exp, check_index_type=True)
# concat
res = pd.concat([Series(vals1), Series(vals2)], ignore_index=True)
tm.assert_series_equal(res, exp, check_index_type=True)
# 3 elements
res = Series(vals1)._append([Series(vals2), Series(vals3)], ignore_index=True)
exp = Series(exp_data3)
tm.assert_series_equal(res, exp)
res = pd.concat(
[Series(vals1), Series(vals2), Series(vals3)],
ignore_index=True,
)
tm.assert_series_equal(res, exp)
# name mismatch
s1 = Series(vals1, name="x")
s2 = Series(vals2, name="y")
res = s1._append(s2, ignore_index=True)
exp = Series(exp_data)
tm.assert_series_equal(res, exp, check_index_type=True)
res = pd.concat([s1, s2], ignore_index=True)
tm.assert_series_equal(res, exp, check_index_type=True)
# name match
s1 = Series(vals1, name="x")
s2 = Series(vals2, name="x")
res = s1._append(s2, ignore_index=True)
exp = Series(exp_data, name="x")
tm.assert_series_equal(res, exp, check_index_type=True)
res = pd.concat([s1, s2], ignore_index=True)
tm.assert_series_equal(res, exp, check_index_type=True)
# cannot append non-index
msg = (
r"cannot concatenate object of type '.+'; "
"only Series and DataFrame objs are valid"
)
with pytest.raises(TypeError, match=msg):
Series(vals1)._append(vals2)
with pytest.raises(TypeError, match=msg):
Series(vals1)._append([Series(vals2), vals3])
with pytest.raises(TypeError, match=msg):
pd.concat([Series(vals1), vals2])
with pytest.raises(TypeError, match=msg):
pd.concat([Series(vals1), Series(vals2), vals3])
def test_concatlike_dtypes_coercion(self, item, item2, request):
# GH 13660
typ1, vals1 = item
typ2, vals2 = item2
vals3 = vals2
# basically infer
exp_index_dtype = None
exp_series_dtype = None
if typ1 == typ2:
# same dtype is tested in test_concatlike_same_dtypes
return
elif typ1 == "category" or typ2 == "category":
# The `vals1 + vals2` below fails bc one of these is a Categorical
# instead of a list; we have separate dedicated tests for categorical
return
warn = None
# specify expected dtype
if typ1 == "bool" and typ2 in ("int64", "float64"):
# series coerces to numeric based on numpy rule
# index doesn't because bool is object dtype
exp_series_dtype = typ2
mark = pytest.mark.xfail(reason="GH#39187 casting to object")
request.node.add_marker(mark)
warn = FutureWarning
elif typ2 == "bool" and typ1 in ("int64", "float64"):
exp_series_dtype = typ1
mark = pytest.mark.xfail(reason="GH#39187 casting to object")
request.node.add_marker(mark)
warn = FutureWarning
elif (
typ1 == "datetime64[ns, US/Eastern]"
or typ2 == "datetime64[ns, US/Eastern]"
or typ1 == "timedelta64[ns]"
or typ2 == "timedelta64[ns]"
):
exp_index_dtype = object
exp_series_dtype = object
exp_data = vals1 + vals2
exp_data3 = vals1 + vals2 + vals3
# ----- Index ----- #
# index.append
with tm.assert_produces_warning(warn, match="concatenating bool-dtype"):
# GH#39817
res = Index(vals1).append(Index(vals2))
exp = Index(exp_data, dtype=exp_index_dtype)
tm.assert_index_equal(res, exp)
# 3 elements
res = Index(vals1).append([Index(vals2), Index(vals3)])
exp = Index(exp_data3, dtype=exp_index_dtype)
tm.assert_index_equal(res, exp)
# ----- Series ----- #
# series._append
with tm.assert_produces_warning(warn, match="concatenating bool-dtype"):
# GH#39817
res = Series(vals1)._append(Series(vals2), ignore_index=True)
exp = Series(exp_data, dtype=exp_series_dtype)
tm.assert_series_equal(res, exp, check_index_type=True)
# concat
with tm.assert_produces_warning(warn, match="concatenating bool-dtype"):
# GH#39817
res = pd.concat([Series(vals1), Series(vals2)], ignore_index=True)
tm.assert_series_equal(res, exp, check_index_type=True)
# 3 elements
with tm.assert_produces_warning(warn, match="concatenating bool-dtype"):
# GH#39817
res = Series(vals1)._append(
[Series(vals2), Series(vals3)], ignore_index=True
)
exp = Series(exp_data3, dtype=exp_series_dtype)
tm.assert_series_equal(res, exp)
with tm.assert_produces_warning(warn, match="concatenating bool-dtype"):
# GH#39817
res = pd.concat(
[Series(vals1), Series(vals2), Series(vals3)],
ignore_index=True,
)
tm.assert_series_equal(res, exp)
def test_concatlike_common_coerce_to_pandas_object(self):
# GH 13626
# result must be Timestamp/Timedelta, not datetime.datetime/timedelta
dti = pd.DatetimeIndex(["2011-01-01", "2011-01-02"])
tdi = pd.TimedeltaIndex(["1 days", "2 days"])
exp = Index(
[
pd.Timestamp("2011-01-01"),
pd.Timestamp("2011-01-02"),
pd.Timedelta("1 days"),
pd.Timedelta("2 days"),
]
)
res = dti.append(tdi)
tm.assert_index_equal(res, exp)
assert isinstance(res[0], pd.Timestamp)
assert isinstance(res[-1], pd.Timedelta)
dts = Series(dti)
tds = Series(tdi)
res = dts._append(tds)
tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1]))
assert isinstance(res.iloc[0], pd.Timestamp)
assert isinstance(res.iloc[-1], pd.Timedelta)
res = pd.concat([dts, tds])
tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1]))
assert isinstance(res.iloc[0], pd.Timestamp)
assert isinstance(res.iloc[-1], pd.Timedelta)
def test_concatlike_datetimetz(self, tz_aware_fixture):
tz = tz_aware_fixture
# GH 7795
dti1 = pd.DatetimeIndex(["2011-01-01", "2011-01-02"], tz=tz)
dti2 = pd.DatetimeIndex(["2012-01-01", "2012-01-02"], tz=tz)
exp = pd.DatetimeIndex(
["2011-01-01", "2011-01-02", "2012-01-01", "2012-01-02"], tz=tz
)
res = dti1.append(dti2)
tm.assert_index_equal(res, exp)
dts1 = Series(dti1)
dts2 = Series(dti2)
res = dts1._append(dts2)
tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1]))
res = pd.concat([dts1, dts2])
tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1]))
@pytest.mark.parametrize("tz", ["UTC", "US/Eastern", "Asia/Tokyo", "EST5EDT"])
def test_concatlike_datetimetz_short(self, tz):
# GH#7795
ix1 = pd.date_range(start="2014-07-15", end="2014-07-17", freq="D", tz=tz)
ix2 = pd.DatetimeIndex(["2014-07-11", "2014-07-21"], tz=tz)
df1 = DataFrame(0, index=ix1, columns=["A", "B"])
df2 = DataFrame(0, index=ix2, columns=["A", "B"])
exp_idx = pd.DatetimeIndex(
["2014-07-15", "2014-07-16", "2014-07-17", "2014-07-11", "2014-07-21"],
tz=tz,
)
exp = DataFrame(0, index=exp_idx, columns=["A", "B"])
tm.assert_frame_equal(df1._append(df2), exp)
tm.assert_frame_equal(pd.concat([df1, df2]), exp)
def test_concatlike_datetimetz_to_object(self, tz_aware_fixture):
tz = tz_aware_fixture
# GH 13660
# different tz coerces to object
dti1 = pd.DatetimeIndex(["2011-01-01", "2011-01-02"], tz=tz)
dti2 = pd.DatetimeIndex(["2012-01-01", "2012-01-02"])
exp = Index(
[
pd.Timestamp("2011-01-01", tz=tz),
pd.Timestamp("2011-01-02", tz=tz),
pd.Timestamp("2012-01-01"),
pd.Timestamp("2012-01-02"),
],
dtype=object,
)
res = dti1.append(dti2)
tm.assert_index_equal(res, exp)
dts1 = Series(dti1)
dts2 = Series(dti2)
res = dts1._append(dts2)
tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1]))
res = pd.concat([dts1, dts2])
tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1]))
# different tz
dti3 = pd.DatetimeIndex(["2012-01-01", "2012-01-02"], tz="US/Pacific")
exp = Index(
[
pd.Timestamp("2011-01-01", tz=tz),
pd.Timestamp("2011-01-02", tz=tz),
pd.Timestamp("2012-01-01", tz="US/Pacific"),
pd.Timestamp("2012-01-02", tz="US/Pacific"),
],
dtype=object,
)
res = dti1.append(dti3)
tm.assert_index_equal(res, exp)
dts1 = Series(dti1)
dts3 = Series(dti3)
res = dts1._append(dts3)
tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1]))
res = pd.concat([dts1, dts3])
tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1]))
def test_concatlike_common_period(self):
# GH 13660
pi1 = pd.PeriodIndex(["2011-01", "2011-02"], freq="M")
pi2 = pd.PeriodIndex(["2012-01", "2012-02"], freq="M")
exp = pd.PeriodIndex(["2011-01", "2011-02", "2012-01", "2012-02"], freq="M")
res = pi1.append(pi2)
tm.assert_index_equal(res, exp)
ps1 = Series(pi1)
ps2 = Series(pi2)
res = ps1._append(ps2)
tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1]))
res = pd.concat([ps1, ps2])
tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1]))
def test_concatlike_common_period_diff_freq_to_object(self):
# GH 13221
pi1 = pd.PeriodIndex(["2011-01", "2011-02"], freq="M")
pi2 = pd.PeriodIndex(["2012-01-01", "2012-02-01"], freq="D")
exp = Index(
[
pd.Period("2011-01", freq="M"),
pd.Period("2011-02", freq="M"),
pd.Period("2012-01-01", freq="D"),
pd.Period("2012-02-01", freq="D"),
],
dtype=object,
)
res = pi1.append(pi2)
tm.assert_index_equal(res, exp)
ps1 = Series(pi1)
ps2 = Series(pi2)
res = ps1._append(ps2)
tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1]))
res = pd.concat([ps1, ps2])
tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1]))
def test_concatlike_common_period_mixed_dt_to_object(self):
# GH 13221
# different datetimelike
pi1 = pd.PeriodIndex(["2011-01", "2011-02"], freq="M")
tdi = pd.TimedeltaIndex(["1 days", "2 days"])
exp = Index(
[
pd.Period("2011-01", freq="M"),
pd.Period("2011-02", freq="M"),
pd.Timedelta("1 days"),
pd.Timedelta("2 days"),
],
dtype=object,
)
res = pi1.append(tdi)
tm.assert_index_equal(res, exp)
ps1 = Series(pi1)
tds = Series(tdi)
res = ps1._append(tds)
tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1]))
res = pd.concat([ps1, tds])
tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1]))
# inverse
exp = Index(
[
pd.Timedelta("1 days"),
pd.Timedelta("2 days"),
pd.Period("2011-01", freq="M"),
pd.Period("2011-02", freq="M"),
],
dtype=object,
)
res = tdi.append(pi1)
tm.assert_index_equal(res, exp)
ps1 = Series(pi1)
tds = Series(tdi)
res = tds._append(ps1)
tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1]))
res = pd.concat([tds, ps1])
tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1]))
def test_concat_categorical(self):
# GH 13524
# same categories -> category
s1 = Series([1, 2, np.nan], dtype="category")
s2 = Series([2, 1, 2], dtype="category")
exp = Series([1, 2, np.nan, 2, 1, 2], dtype="category")
tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), exp)
tm.assert_series_equal(s1._append(s2, ignore_index=True), exp)
# partially different categories => not-category
s1 = Series([3, 2], dtype="category")
s2 = Series([2, 1], dtype="category")
exp = Series([3, 2, 2, 1])
tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), exp)
tm.assert_series_equal(s1._append(s2, ignore_index=True), exp)
# completely different categories (same dtype) => not-category
s1 = Series([10, 11, np.nan], dtype="category")
s2 = Series([np.nan, 1, 3, 2], dtype="category")
exp =
|
Series([10, 11, np.nan, np.nan, 1, 3, 2], dtype=np.float64)
|
pandas.Series
|
########################################################################################################################
# |||||||||||||||||||||||||||||||||||||||||||||||||| AQUITANIA ||||||||||||||||||||||||||||||||||||||||||||||||||||||| #
# |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| #
# |||| To be a thinker means to go by the factual evidence of a case, not by the judgment of others |||||||||||||||||| #
# |||| As there is no group stomach to digest collectively, there is no group mind to think collectively. |||||||||||| #
# |||| Each man must accept responsibility for his own life, each must be sovereign by his own judgment. ||||||||||||| #
# |||| If a man believes a claim to be true, then he must hold to this belief even though society opposes him. ||||||| #
# |||| Not only know what you want, but be willing to break all established conventions to accomplish it. |||||||||||| #
# |||| The merit of a design is the only credential that you require. |||||||||||||||||||||||||||||||||||||||||||||||| #
# |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| #
########################################################################################################################
"""
.. moduleauthor:: <NAME>
This class was created on late December 2017, that was when I started working with AI using only Random Forest
algorithms.
Going through a big refactor on 17th February 2018, create AbstractModel class, removed a lot of content inside of this
class, it was almost doing everything alone, now I moved out a lot of its functionality, and it is being designed to be
a piece of a whole system of models and predictors.
"""
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from aquitania.brains.models.abstract_model import AbstractModel
class RandomForestClf(AbstractModel):
"""
RandomForest class gets a list of currencies a signal and exits and creates an algorithm to predict patterns.
"""
def __init__(self, **kwargs):
if len(kwargs) == 0:
kwargs = {'n_jobs': -1, 'max_features': .5, 'n_estimators': 25, 'min_samples_leaf': 25}
self.kwargs = kwargs
super().__init__(RandomForestClassifier(**kwargs))
def fit(self, X, y):
self.clf.fit(X, y)
self.importance_of_columns = self.clf.feature_importances_
super().fit(X, y)
def predict(self, X):
return self.clf.predict_proba(X).T[1]
def get_feature_importance(self):
return
|
pd.Series(self.importance_of_columns, index=self.features)
|
pandas.Series
|
# ms_mint/io.py
import pandas as pd
import numpy as np
import io
import logging
import pymzml
from pathlib import Path as P
from datetime import date
from pyteomics import mzxml, mzml
from functools import lru_cache
try:
from pyteomics import mzmlb
MZMLB_AVAILABLE = True
except:
logging.warning('Cound not import pyteomics.mzmlb')
MZMLB_AVAILABLE = False
MS_FILE_COLUMNS = ['scan_id', 'ms_level', 'polarity', 'scan_time_min', 'mz', 'intensity']
@lru_cache(100)
def ms_file_to_df(fn, read_only:bool=False, time_unit='seconds'):
assert time_unit in ['minutes', 'seconds']
fn = str(fn)
if fn.lower().endswith('.mzxml'):
df = mzxml_to_df(fn, read_only=read_only)
elif fn.lower().endswith('.mzml'):
df = mzml_to_df(fn, read_only=read_only, time_unit=time_unit)
elif fn.lower().endswith('hdf'):
df =
|
pd.read_hdf(fn)
|
pandas.read_hdf
|
from tqdm import tqdm
from functools import partial
import multiprocessing
import pandas as pd
import numpy as np
import argparse
import os
def step0_extract(filename):
df = pd.read_csv(filename, low_memory=False)
print('Total size:\t\t\t\t\t', len(df))
df = df[df['TransactionType'] == 'FI-InvoicedDocument']
print('Total size (transaction type filter):\t\t', len(df))
df = df[['DocumentKey', 'CustomerKey', 'DocumentDate', 'DueDate', 'ClearingDate', 'InvoicedAmount']].dropna()
print('Total size (dropna filter):\t\t\t', len(df))
for col in ['DocumentKey']:
df[col] = df[col].apply(lambda x: x.split('|')[2])
for col in ['DocumentDate', 'DueDate', 'ClearingDate']:
df[col] = pd.to_datetime(df[col])
for col in ['DocumentKey', 'CustomerKey', 'InvoicedAmount']:
df[col] = pd.to_numeric(df[col])
df = df[(df['DocumentDate'] < df['DueDate']) & (df['DocumentDate'] < df['ClearingDate'])]
df = df[df['InvoicedAmount'] >= 1000]
print('Total size (Date and Invoice Amount filters):\t', len(df), '\n')
return df
def step1_organize(filename):
def group(x): return x.groupby(['CustomerKey', 'DueDate'])
def order(x): return x.sort_values(by=['DueDate'], ascending=True, ignore_index=True)
def merge(x1, x2): return pd.merge(order(x1), order(x2), how='left', on=['CustomerKey', 'DueDate'])
df = pd.read_csv(filename, parse_dates=['DocumentDate', 'DueDate', 'ClearingDate'], low_memory=False)
df['OS'] = ((df['ClearingDate'] - (df['DueDate'] - pd.to_timedelta(arg=df['DueDate'].dt.weekday, unit='D')))
.astype('timedelta64[D]') > 0).astype(int)
df_doc = order(group(df)['DocumentDate'].min().reset_index())
df_cle = order(group(df)['ClearingDate'].max().reset_index())
df_gp = pd.DataFrame({
'CustomerKey': df_doc['CustomerKey'].values,
'DocumentDate': df_doc['DocumentDate'].values,
'DueDate': df_doc['DueDate'].values,
'ClearingDate': df_cle['ClearingDate'].values,
})
df_gp = merge(df_gp, group(df).size().reset_index(name='InvoiceCount'))
df_gp = merge(df_gp, group(df[df['OS'] == 1]).size().reset_index(name='OSInvoiceCount'))
df_gp['OSInvoiceCount'] = df_gp['OSInvoiceCount'].fillna(0).astype(int)
df_gp['R_OSInvoiceCount'] = df_gp['OSInvoiceCount'] / df_gp['InvoiceCount']
df_gp['R_OSInvoiceCount'] = df_gp['R_OSInvoiceCount'].fillna(0)
df_gp = merge(df_gp, group(df)['InvoicedAmount'].sum().reset_index(name='InvoiceAmount'))
df_gp = merge(df_gp, group(df[df['OS'] == 1])['InvoicedAmount'].sum().reset_index(name='OSInvoiceAmount'))
df_gp['OSInvoiceAmount'] = df_gp['OSInvoiceAmount'].fillna(0)
df_gp['R_OSInvoiceAmount'] = df_gp['OSInvoiceAmount'] / df_gp['InvoiceAmount']
df_gp['R_OSInvoiceAmount'] = df_gp['R_OSInvoiceAmount'].fillna(0)
return df_gp
def step2_generate(filename):
df = pd.read_csv(filename, parse_dates=['DocumentDate', 'DueDate', 'ClearingDate'], low_memory=False)
df['DaysToEndMonth'] = ((df['DueDate'] + pd.offsets.MonthEnd(0)) - df['DueDate']).dt.days
df['DaysLate'] = ((df['ClearingDate'] - df['DueDate']).dt.days).clip(lower=0)
df['DaysLateAM'] = (df['DaysLate'] - df['DaysToEndMonth']).clip(lower=0)
df['PaymentCategory'] = 0
df.loc[(df['DaysLate'] > 0) & (df['DaysLateAM'] <= 0), 'PaymentCategory'] = 1
df.loc[(df['DaysLate'] > 0) & (df['DaysLateAM'] > 0), 'PaymentCategory'] = 2
features = []
with multiprocessing.Pool(multiprocessing.cpu_count()) as pool:
for x in tqdm(pool.imap(partial(_historic), df[['CustomerKey', 'DueDate']].values), total=len(df)):
features.append(x)
pool.close()
pool.join()
df = pd.merge(df,
|
pd.DataFrame(features)
|
pandas.DataFrame
|
from collections import OrderedDict
import datetime
from datetime import timedelta
from io import StringIO
import json
import os
import numpy as np
import pytest
from pandas.compat import is_platform_32bit, is_platform_windows
import pandas.util._test_decorators as td
import pandas as pd
from pandas import DataFrame, DatetimeIndex, Series, Timestamp, read_json
import pandas._testing as tm
_seriesd = tm.getSeriesData()
_tsd = tm.getTimeSeriesData()
_frame = DataFrame(_seriesd)
_intframe = DataFrame({k: v.astype(np.int64) for k, v in _seriesd.items()})
_tsframe = DataFrame(_tsd)
_cat_frame = _frame.copy()
cat = ["bah"] * 5 + ["bar"] * 5 + ["baz"] * 5 + ["foo"] * (len(_cat_frame) - 15)
_cat_frame.index = pd.CategoricalIndex(cat, name="E")
_cat_frame["E"] = list(reversed(cat))
_cat_frame["sort"] = np.arange(len(_cat_frame), dtype="int64")
_mixed_frame = _frame.copy()
def assert_json_roundtrip_equal(result, expected, orient):
if orient == "records" or orient == "values":
expected = expected.reset_index(drop=True)
if orient == "values":
expected.columns = range(len(expected.columns))
tm.assert_frame_equal(result, expected)
@pytest.mark.filterwarnings("ignore:the 'numpy' keyword is deprecated:FutureWarning")
class TestPandasContainer:
@pytest.fixture(autouse=True)
def setup(self):
self.intframe = _intframe.copy()
self.tsframe = _tsframe.copy()
self.mixed_frame = _mixed_frame.copy()
self.categorical = _cat_frame.copy()
yield
del self.intframe
del self.tsframe
del self.mixed_frame
def test_frame_double_encoded_labels(self, orient):
df = DataFrame(
[["a", "b"], ["c", "d"]],
index=['index " 1', "index / 2"],
columns=["a \\ b", "y / z"],
)
result = read_json(df.to_json(orient=orient), orient=orient)
expected = df.copy()
assert_json_roundtrip_equal(result, expected, orient)
@pytest.mark.parametrize("orient", ["split", "records", "values"])
def test_frame_non_unique_index(self, orient):
df = DataFrame([["a", "b"], ["c", "d"]], index=[1, 1], columns=["x", "y"])
result = read_json(df.to_json(orient=orient), orient=orient)
expected = df.copy()
assert_json_roundtrip_equal(result, expected, orient)
@pytest.mark.parametrize("orient", ["index", "columns"])
def test_frame_non_unique_index_raises(self, orient):
df = DataFrame([["a", "b"], ["c", "d"]], index=[1, 1], columns=["x", "y"])
msg = f"DataFrame index must be unique for orient='{orient}'"
with pytest.raises(ValueError, match=msg):
df.to_json(orient=orient)
@pytest.mark.parametrize("orient", ["split", "values"])
@pytest.mark.parametrize(
"data",
[
[["a", "b"], ["c", "d"]],
[[1.5, 2.5], [3.5, 4.5]],
[[1, 2.5], [3, 4.5]],
[[Timestamp("20130101"), 3.5], [Timestamp("20130102"), 4.5]],
],
)
def test_frame_non_unique_columns(self, orient, data):
df = DataFrame(data, index=[1, 2], columns=["x", "x"])
result = read_json(
df.to_json(orient=orient), orient=orient, convert_dates=["x"]
)
if orient == "values":
expected = pd.DataFrame(data)
if expected.iloc[:, 0].dtype == "datetime64[ns]":
# orient == "values" by default will write Timestamp objects out
# in milliseconds; these are internally stored in nanosecond,
# so divide to get where we need
# TODO: a to_epoch method would also solve; see GH 14772
expected.iloc[:, 0] = expected.iloc[:, 0].astype(np.int64) // 1000000
elif orient == "split":
expected = df
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize("orient", ["index", "columns", "records"])
def test_frame_non_unique_columns_raises(self, orient):
df = DataFrame([["a", "b"], ["c", "d"]], index=[1, 2], columns=["x", "x"])
msg = f"DataFrame columns must be unique for orient='{orient}'"
with pytest.raises(ValueError, match=msg):
df.to_json(orient=orient)
def test_frame_default_orient(self, float_frame):
assert float_frame.to_json() == float_frame.to_json(orient="columns")
@pytest.mark.parametrize("dtype", [False, float])
@pytest.mark.parametrize("convert_axes", [True, False])
@pytest.mark.parametrize("numpy", [True, False])
def test_roundtrip_simple(self, orient, convert_axes, numpy, dtype, float_frame):
data = float_frame.to_json(orient=orient)
result = pd.read_json(
data, orient=orient, convert_axes=convert_axes, numpy=numpy, dtype=dtype
)
expected = float_frame
assert_json_roundtrip_equal(result, expected, orient)
@pytest.mark.parametrize("dtype", [False, np.int64])
@pytest.mark.parametrize("convert_axes", [True, False])
@pytest.mark.parametrize("numpy", [True, False])
def test_roundtrip_intframe(self, orient, convert_axes, numpy, dtype):
data = self.intframe.to_json(orient=orient)
result = pd.read_json(
data, orient=orient, convert_axes=convert_axes, numpy=numpy, dtype=dtype
)
expected = self.intframe.copy()
if (
numpy
and (is_platform_32bit() or is_platform_windows())
and not dtype
and orient != "split"
):
# TODO: see what is causing roundtrip dtype loss
expected = expected.astype(np.int32)
assert_json_roundtrip_equal(result, expected, orient)
@pytest.mark.parametrize("dtype", [None, np.float64, np.int, "U3"])
@pytest.mark.parametrize("convert_axes", [True, False])
@pytest.mark.parametrize("numpy", [True, False])
def test_roundtrip_str_axes(self, orient, convert_axes, numpy, dtype):
df = DataFrame(
np.zeros((200, 4)),
columns=[str(i) for i in range(4)],
index=[str(i) for i in range(200)],
dtype=dtype,
)
# TODO: do we even need to support U3 dtypes?
if numpy and dtype == "U3" and orient != "split":
pytest.xfail("Can't decode directly to array")
data = df.to_json(orient=orient)
result = pd.read_json(
data, orient=orient, convert_axes=convert_axes, numpy=numpy, dtype=dtype
)
expected = df.copy()
if not dtype:
expected = expected.astype(np.int64)
# index columns, and records orients cannot fully preserve the string
# dtype for axes as the index and column labels are used as keys in
# JSON objects. JSON keys are by definition strings, so there's no way
# to disambiguate whether those keys actually were strings or numeric
# beforehand and numeric wins out.
# TODO: Split should be able to support this
if convert_axes and (orient in ("split", "index", "columns")):
expected.columns = expected.columns.astype(np.int64)
expected.index = expected.index.astype(np.int64)
elif orient == "records" and convert_axes:
expected.columns = expected.columns.astype(np.int64)
assert_json_roundtrip_equal(result, expected, orient)
@pytest.mark.parametrize("convert_axes", [True, False])
@pytest.mark.parametrize("numpy", [True, False])
def test_roundtrip_categorical(self, orient, convert_axes, numpy):
# TODO: create a better frame to test with and improve coverage
if orient in ("index", "columns"):
pytest.xfail(f"Can't have duplicate index values for orient '{orient}')")
data = self.categorical.to_json(orient=orient)
if numpy and orient in ("records", "values"):
pytest.xfail(f"Orient {orient} is broken with numpy=True")
result = pd.read_json(
data, orient=orient, convert_axes=convert_axes, numpy=numpy
)
expected = self.categorical.copy()
expected.index = expected.index.astype(str) # Categorical not preserved
expected.index.name = None # index names aren't preserved in JSON
if not numpy and orient == "index":
expected = expected.sort_index()
assert_json_roundtrip_equal(result, expected, orient)
@pytest.mark.parametrize("convert_axes", [True, False])
@pytest.mark.parametrize("numpy", [True, False])
def test_roundtrip_empty(self, orient, convert_axes, numpy, empty_frame):
data = empty_frame.to_json(orient=orient)
result = pd.read_json(
data, orient=orient, convert_axes=convert_axes, numpy=numpy
)
expected = empty_frame.copy()
# TODO: both conditions below are probably bugs
if convert_axes:
expected.index = expected.index.astype(float)
expected.columns = expected.columns.astype(float)
if numpy and orient == "values":
expected = expected.reindex([0], axis=1).reset_index(drop=True)
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize("convert_axes", [True, False])
@pytest.mark.parametrize("numpy", [True, False])
def test_roundtrip_timestamp(self, orient, convert_axes, numpy):
# TODO: improve coverage with date_format parameter
data = self.tsframe.to_json(orient=orient)
result = pd.read_json(
data, orient=orient, convert_axes=convert_axes, numpy=numpy
)
expected = self.tsframe.copy()
if not convert_axes: # one off for ts handling
# DTI gets converted to epoch values
idx = expected.index.astype(np.int64) // 1000000
if orient != "split": # TODO: handle consistently across orients
idx = idx.astype(str)
expected.index = idx
assert_json_roundtrip_equal(result, expected, orient)
@pytest.mark.parametrize("convert_axes", [True, False])
@pytest.mark.parametrize("numpy", [True, False])
def test_roundtrip_mixed(self, orient, convert_axes, numpy):
if numpy and orient != "split":
pytest.xfail("Can't decode directly to array")
index = pd.Index(["a", "b", "c", "d", "e"])
values = {
"A": [0.0, 1.0, 2.0, 3.0, 4.0],
"B": [0.0, 1.0, 0.0, 1.0, 0.0],
"C": ["foo1", "foo2", "foo3", "foo4", "foo5"],
"D": [True, False, True, False, True],
}
df = DataFrame(data=values, index=index)
data = df.to_json(orient=orient)
result = pd.read_json(
data, orient=orient, convert_axes=convert_axes, numpy=numpy
)
expected = df.copy()
expected = expected.assign(**expected.select_dtypes("number").astype(np.int64))
if not numpy and orient == "index":
expected = expected.sort_index()
assert_json_roundtrip_equal(result, expected, orient)
@pytest.mark.parametrize(
"data,msg,orient",
[
('{"key":b:a:d}', "Expected object or value", "columns"),
# too few indices
(
'{"columns":["A","B"],'
'"index":["2","3"],'
'"data":[[1.0,"1"],[2.0,"2"],[null,"3"]]}',
r"Shape of passed values is \(3, 2\), indices imply \(2, 2\)",
"split",
),
# too many columns
(
'{"columns":["A","B","C"],'
'"index":["1","2","3"],'
'"data":[[1.0,"1"],[2.0,"2"],[null,"3"]]}',
"3 columns passed, passed data had 2 columns",
"split",
),
# bad key
(
'{"badkey":["A","B"],'
'"index":["2","3"],'
'"data":[[1.0,"1"],[2.0,"2"],[null,"3"]]}',
r"unexpected key\(s\): badkey",
"split",
),
],
)
def test_frame_from_json_bad_data_raises(self, data, msg, orient):
with pytest.raises(ValueError, match=msg):
read_json(StringIO(data), orient=orient)
@pytest.mark.parametrize("dtype", [True, False])
@pytest.mark.parametrize("convert_axes", [True, False])
@pytest.mark.parametrize("numpy", [True, False])
def test_frame_from_json_missing_data(self, orient, convert_axes, numpy, dtype):
num_df = DataFrame([[1, 2], [4, 5, 6]])
result = read_json(
num_df.to_json(orient=orient),
orient=orient,
convert_axes=convert_axes,
dtype=dtype,
)
assert np.isnan(result.iloc[0, 2])
obj_df = DataFrame([["1", "2"], ["4", "5", "6"]])
result = read_json(
obj_df.to_json(orient=orient),
orient=orient,
convert_axes=convert_axes,
dtype=dtype,
)
if not dtype: # TODO: Special case for object data; maybe a bug?
assert result.iloc[0, 2] is None
else:
assert np.isnan(result.iloc[0, 2])
@pytest.mark.parametrize("inf", [np.inf, np.NINF])
@pytest.mark.parametrize("dtype", [True, False])
def test_frame_infinity(self, orient, inf, dtype):
# infinities get mapped to nulls which get mapped to NaNs during
# deserialisation
df = DataFrame([[1, 2], [4, 5, 6]])
df.loc[0, 2] = inf
result = read_json(df.to_json(), dtype=dtype)
assert np.isnan(result.iloc[0, 2])
@pytest.mark.skipif(
is_platform_32bit(), reason="not compliant on 32-bit, xref #15865"
)
@pytest.mark.parametrize(
"value,precision,expected_val",
[
(0.95, 1, 1.0),
(1.95, 1, 2.0),
(-1.95, 1, -2.0),
(0.995, 2, 1.0),
(0.9995, 3, 1.0),
(0.99999999999999944, 15, 1.0),
],
)
def test_frame_to_json_float_precision(self, value, precision, expected_val):
df = pd.DataFrame([dict(a_float=value)])
encoded = df.to_json(double_precision=precision)
assert encoded == f'{{"a_float":{{"0":{expected_val}}}}}'
def test_frame_to_json_except(self):
df = DataFrame([1, 2, 3])
msg = "Invalid value 'garbage' for option 'orient'"
with pytest.raises(ValueError, match=msg):
df.to_json(orient="garbage")
def test_frame_empty(self):
df = DataFrame(columns=["jim", "joe"])
assert not df._is_mixed_type
tm.assert_frame_equal(
read_json(df.to_json(), dtype=dict(df.dtypes)), df, check_index_type=False
)
# GH 7445
result = pd.DataFrame({"test": []}, index=[]).to_json(orient="columns")
expected = '{"test":{}}'
assert result == expected
def test_frame_empty_mixedtype(self):
# mixed type
df = DataFrame(columns=["jim", "joe"])
df["joe"] = df["joe"].astype("i8")
assert df._is_mixed_type
tm.assert_frame_equal(
read_json(df.to_json(), dtype=dict(df.dtypes)), df, check_index_type=False
)
def test_frame_mixedtype_orient(self): # GH10289
vals = [
[10, 1, "foo", 0.1, 0.01],
[20, 2, "bar", 0.2, 0.02],
[30, 3, "baz", 0.3, 0.03],
[40, 4, "qux", 0.4, 0.04],
]
df = DataFrame(
vals, index=list("abcd"), columns=["1st", "2nd", "3rd", "4th", "5th"]
)
assert df._is_mixed_type
right = df.copy()
for orient in ["split", "index", "columns"]:
inp = df.to_json(orient=orient)
left = read_json(inp, orient=orient, convert_axes=False)
tm.assert_frame_equal(left, right)
right.index = np.arange(len(df))
inp = df.to_json(orient="records")
left = read_json(inp, orient="records", convert_axes=False)
tm.assert_frame_equal(left, right)
right.columns = np.arange(df.shape[1])
inp = df.to_json(orient="values")
left = read_json(inp, orient="values", convert_axes=False)
tm.assert_frame_equal(left, right)
def test_v12_compat(self, datapath):
df = DataFrame(
[
[1.56808523, 0.65727391, 1.81021139, -0.17251653],
[-0.2550111, -0.08072427, -0.03202878, -0.17581665],
[1.51493992, 0.11805825, 1.629455, -1.31506612],
[-0.02765498, 0.44679743, 0.33192641, -0.27885413],
[0.05951614, -2.69652057, 1.28163262, 0.34703478],
],
columns=["A", "B", "C", "D"],
index=pd.date_range("2000-01-03", "2000-01-07"),
)
df["date"] = pd.Timestamp("19920106 18:21:32.12")
df.iloc[3, df.columns.get_loc("date")] = pd.Timestamp("20130101")
df["modified"] = df["date"]
df.iloc[1, df.columns.get_loc("modified")] = pd.NaT
dirpath = datapath("io", "json", "data")
v12_json = os.path.join(dirpath, "tsframe_v012.json")
df_unser = pd.read_json(v12_json)
tm.assert_frame_equal(df, df_unser)
df_iso = df.drop(["modified"], axis=1)
v12_iso_json = os.path.join(dirpath, "tsframe_iso_v012.json")
df_unser_iso = pd.read_json(v12_iso_json)
tm.assert_frame_equal(df_iso, df_unser_iso)
def test_blocks_compat_GH9037(self):
index = pd.date_range("20000101", periods=10, freq="H")
df_mixed = DataFrame(
OrderedDict(
float_1=[
-0.92077639,
0.77434435,
1.25234727,
0.61485564,
-0.60316077,
0.24653374,
0.28668979,
-2.51969012,
0.95748401,
-1.02970536,
],
int_1=[
19680418,
75337055,
99973684,
65103179,
79373900,
40314334,
21290235,
4991321,
41903419,
16008365,
],
str_1=[
"78c608f1",
"64a99743",
"13d2ff52",
"ca7f4af2",
"97236474",
"bde7e214",
"1a6bde47",
"b1190be5",
"7a669144",
"8d64d068",
],
float_2=[
-0.0428278,
-1.80872357,
3.36042349,
-0.7573685,
-0.48217572,
0.86229683,
1.08935819,
0.93898739,
-0.03030452,
1.43366348,
],
str_2=[
"14f04af9",
"d085da90",
"4bcfac83",
"81504caf",
"2ffef4a9",
"08e2f5c4",
"07e1af03",
"addbd4a7",
"1f6a09ba",
"4bfc4d87",
],
int_2=[
86967717,
98098830,
51927505,
20372254,
12601730,
20884027,
34193846,
10561746,
24867120,
76131025,
],
),
index=index,
)
# JSON deserialisation always creates unicode strings
df_mixed.columns = df_mixed.columns.astype("unicode")
df_roundtrip = pd.read_json(df_mixed.to_json(orient="split"), orient="split")
tm.assert_frame_equal(
df_mixed,
df_roundtrip,
check_index_type=True,
check_column_type=True,
by_blocks=True,
check_exact=True,
)
def test_frame_nonprintable_bytes(self):
# GH14256: failing column caused segfaults, if it is not the last one
class BinaryThing:
def __init__(self, hexed):
self.hexed = hexed
self.binary = bytes.fromhex(hexed)
def __str__(self) -> str:
return self.hexed
hexed = "574b4454ba8c5eb4f98a8f45"
binthing = BinaryThing(hexed)
# verify the proper conversion of printable content
df_printable = DataFrame({"A": [binthing.hexed]})
assert df_printable.to_json() == f'{{"A":{{"0":"{hexed}"}}}}'
# check if non-printable content throws appropriate Exception
df_nonprintable = DataFrame({"A": [binthing]})
msg = "Unsupported UTF-8 sequence length when encoding string"
with pytest.raises(OverflowError, match=msg):
df_nonprintable.to_json()
# the same with multiple columns threw segfaults
df_mixed = DataFrame({"A": [binthing], "B": [1]}, columns=["A", "B"])
with pytest.raises(OverflowError):
df_mixed.to_json()
# default_handler should resolve exceptions for non-string types
result = df_nonprintable.to_json(default_handler=str)
expected = f'{{"A":{{"0":"{hexed}"}}}}'
assert result == expected
assert (
df_mixed.to_json(default_handler=str)
== f'{{"A":{{"0":"{hexed}"}},"B":{{"0":1}}}}'
)
def test_label_overflow(self):
# GH14256: buffer length not checked when writing label
result = pd.DataFrame({"bar" * 100000: [1], "foo": [1337]}).to_json()
expected = f'{{"{"bar" * 100000}":{{"0":1}},"foo":{{"0":1337}}}}'
assert result == expected
def test_series_non_unique_index(self):
s = Series(["a", "b"], index=[1, 1])
msg = "Series index must be unique for orient='index'"
with pytest.raises(ValueError, match=msg):
s.to_json(orient="index")
tm.assert_series_equal(
s, read_json(s.to_json(orient="split"), orient="split", typ="series")
)
unser = read_json(s.to_json(orient="records"), orient="records", typ="series")
tm.assert_numpy_array_equal(s.values, unser.values)
def test_series_default_orient(self, string_series):
assert string_series.to_json() == string_series.to_json(orient="index")
@pytest.mark.parametrize("numpy", [True, False])
def test_series_roundtrip_simple(self, orient, numpy, string_series):
data = string_series.to_json(orient=orient)
result = pd.read_json(data, typ="series", orient=orient, numpy=numpy)
expected = string_series
if orient in ("values", "records"):
expected = expected.reset_index(drop=True)
if orient != "split":
expected.name = None
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("dtype", [False, None])
@pytest.mark.parametrize("numpy", [True, False])
def test_series_roundtrip_object(self, orient, numpy, dtype, object_series):
data = object_series.to_json(orient=orient)
result = pd.read_json(
data, typ="series", orient=orient, numpy=numpy, dtype=dtype
)
expected = object_series
if orient in ("values", "records"):
expected = expected.reset_index(drop=True)
if orient != "split":
expected.name = None
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("numpy", [True, False])
def test_series_roundtrip_empty(self, orient, numpy, empty_series):
data = empty_series.to_json(orient=orient)
result = pd.read_json(data, typ="series", orient=orient, numpy=numpy)
expected = empty_series
if orient in ("values", "records"):
expected = expected.reset_index(drop=True)
else:
expected.index = expected.index.astype(float)
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("numpy", [True, False])
def test_series_roundtrip_timeseries(self, orient, numpy, datetime_series):
data = datetime_series.to_json(orient=orient)
result = pd.read_json(data, typ="series", orient=orient, numpy=numpy)
expected = datetime_series
if orient in ("values", "records"):
expected = expected.reset_index(drop=True)
if orient != "split":
expected.name = None
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("dtype", [np.float64, np.int])
@pytest.mark.parametrize("numpy", [True, False])
def test_series_roundtrip_numeric(self, orient, numpy, dtype):
s = Series(range(6), index=["a", "b", "c", "d", "e", "f"])
data = s.to_json(orient=orient)
result = pd.read_json(data, typ="series", orient=orient, numpy=numpy)
expected = s.copy()
if orient in ("values", "records"):
expected = expected.reset_index(drop=True)
tm.assert_series_equal(result, expected)
def test_series_to_json_except(self):
s = Series([1, 2, 3])
msg = "Invalid value 'garbage' for option 'orient'"
with pytest.raises(ValueError, match=msg):
s.to_json(orient="garbage")
def test_series_from_json_precise_float(self):
s = Series([4.56, 4.56, 4.56])
result = read_json(s.to_json(), typ="series", precise_float=True)
tm.assert_series_equal(result, s, check_index_type=False)
def test_series_with_dtype(self):
# GH 21986
s = Series([4.56, 4.56, 4.56])
result = read_json(s.to_json(), typ="series", dtype=np.int64)
expected = Series([4] * 3)
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize(
"dtype,expected",
[
(True, Series(["2000-01-01"], dtype="datetime64[ns]")),
(False, Series([946684800000])),
],
)
def test_series_with_dtype_datetime(self, dtype, expected):
s = Series(["2000-01-01"], dtype="datetime64[ns]")
data = s.to_json()
result = pd.read_json(data, typ="series", dtype=dtype)
tm.assert_series_equal(result, expected)
def test_frame_from_json_precise_float(self):
df = DataFrame([[4.56, 4.56, 4.56], [4.56, 4.56, 4.56]])
result = read_json(df.to_json(), precise_float=True)
tm.assert_frame_equal(
result, df, check_index_type=False, check_column_type=False
)
def test_typ(self):
s = Series(range(6), index=["a", "b", "c", "d", "e", "f"], dtype="int64")
result = read_json(s.to_json(), typ=None)
tm.assert_series_equal(result, s)
def test_reconstruction_index(self):
df = DataFrame([[1, 2, 3], [4, 5, 6]])
result = read_json(df.to_json())
tm.assert_frame_equal(result, df)
df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}, index=["A", "B", "C"])
result = read_json(df.to_json())
tm.assert_frame_equal(result, df)
def test_path(self, float_frame):
with tm.ensure_clean("test.json") as path:
for df in [
float_frame,
self.intframe,
self.tsframe,
self.mixed_frame,
]:
df.to_json(path)
read_json(path)
def test_axis_dates(self, datetime_series):
# frame
json = self.tsframe.to_json()
result = read_json(json)
tm.assert_frame_equal(result, self.tsframe)
# series
json = datetime_series.to_json()
result = read_json(json, typ="series")
tm.assert_series_equal(result, datetime_series, check_names=False)
assert result.name is None
def test_convert_dates(self, datetime_series):
# frame
df = self.tsframe.copy()
df["date"] = Timestamp("20130101")
json = df.to_json()
result =
|
read_json(json)
|
pandas.read_json
|
"""
Responsible for handling requests for pages from the website and delegating the analysis
and visualisation as required.
"""
from collections import defaultdict
from operator import pos
from typing import Iterable
from numpy import isnan
import pandas as pd
from cachetools import func
from django.shortcuts import render
from django.http import Http404
from django.contrib.auth.decorators import login_required
from app.messages import warning
from app.models import (
timing,
user_watchlist,
cached_all_stocks_cip,
valid_quotes_only,
all_stocks,
Timeframe,
validate_user,
stocks_by_sector,
)
from app.data import (
cache_plot,
make_pe_trends_eps_df,
make_pe_trends_positive_pe_df,
pe_trends_df,
)
from app.plots import (
plot_heatmap,
plot_series,
plot_market_wide_sector_performance,
plot_market_cap_distribution,
plot_sector_field,
plot_sector_top_eps_contributors,
plot_sector_monthly_mean_returns,
)
from lazydict import LazyDictionary
def bin_market_cap(row):
mc = row[
0
] # NB: expressed in millions $AUD already (see plot_market_cap_distribution() below)
if mc < 2000:
return "small"
elif mc > 10000:
return "large"
elif mc is not None:
return "med"
else:
return "NA"
def make_quote_df(quotes, asx_codes: Iterable[str], prefix: str):
df = pd.DataFrame.from_dict(
{
q.asx_code: (q.market_cap / (1000 * 1000), q.last_price, q.number_of_shares)
for q in quotes
if q.market_cap is not None and q.asx_code in asx_codes
},
orient="index",
columns=["market_cap", "last_price", "shares"],
)
if len(df) == 0:
raise Http404(f"No data present in {len(quotes)} quotes.")
df["bin"] = df.apply(bin_market_cap, axis=1)
df["market"] = prefix
return df
@login_required
def market_sentiment(request, n_days=21, n_top_bottom=20, sector_n_days=365):
validate_user(request.user)
assert n_days > 0
assert n_top_bottom > 0
def market_cap_data_factory(ld: LazyDictionary) -> pd.DataFrame:
dates = ld["sector_timeframe"].all_dates()
# print(dates)
assert len(dates) > 90
result_df = None
adjusted_dates = []
for the_date in [dates[0], dates[-1], dates[-30], dates[-90]]:
quotes, actual_trading_date = valid_quotes_only(
the_date, ensure_date_has_data=True
)
df = make_quote_df(quotes, ld["asx_codes"], actual_trading_date)
result_df = df if result_df is None else result_df.append(df)
if the_date != actual_trading_date:
adjusted_dates.append(the_date)
if len(adjusted_dates) > 0:
warning(
request,
"Some dates were not trading days, adjusted: {}".format(adjusted_dates),
)
return result_df
ld = LazyDictionary()
ld["asx_codes"] = lambda ld: all_stocks()
ld["sector_timeframe"] = lambda ld: Timeframe(past_n_days=sector_n_days)
ld["timeframe"] = lambda ld: Timeframe(past_n_days=n_days)
ld["sector_df"] = lambda ld: cached_all_stocks_cip(ld["sector_timeframe"])
ld["sector_cumsum_df"] = lambda ld: ld["sector_df"].cumsum(axis=1)
ld["cip_df"] = lambda ld: ld["sector_df"].filter(
items=ld["timeframe"].all_dates(), axis=1
)
ld["market_cap_df"] = lambda ld: market_cap_data_factory(ld)
ld["stocks_by_sector"] = lambda ld: stocks_by_sector()
sentiment_plot = cache_plot(
f"market-sentiment-{ld['timeframe'].description}",
lambda ld: plot_heatmap(ld["timeframe"], ld),
datasets=ld,
)
sector_descr = ld["sector_timeframe"].description
sector_performance_plot = cache_plot(
f"sector-performance-{sector_descr}",
lambda ld: plot_market_wide_sector_performance(ld),
datasets=ld,
)
market_cap_dist_plot = cache_plot(
f"market-cap-dist-{sector_descr}",
lambda ld: plot_market_cap_distribution(ld),
datasets=ld,
)
df = ld["sector_cumsum_df"].transpose()
df.index = pd.to_datetime(df.index, format="%Y-%m-%d")
df = (
df.resample(
"BM",
)
.asfreq()
.diff(periods=1)
)
ld["monthly_returns_by_stock"] = df
# print(df)
context = {
"sentiment_uri": sentiment_plot,
"n_days": ld["timeframe"].n_days,
"n_stocks_plotted": len(ld["asx_codes"]),
"n_top_bottom": n_top_bottom,
"watched": user_watchlist(request.user),
"sector_performance_uri": sector_performance_plot,
"sector_timeframe": ld["sector_timeframe"],
"sector_performance_title": "Cumulative sector avg. performance: {}".format(
ld["sector_timeframe"].description
),
"title": "Market sentiment",
"market_cap_distribution_uri": market_cap_dist_plot,
"monthly_sector_mean_returns": plot_sector_monthly_mean_returns(ld),
}
return render(request, "market_sentiment_view.html", context=context)
@login_required
def show_pe_trends(request):
"""
Display a plot of per-sector PE trends across stocks in each sector
ref: https://www.commsec.com.au/education/learn/choosing-investments/what-is-price-to-earnings-pe-ratio.html
"""
validate_user(request.user)
def make_pe_trends_market_avg_df(ld: LazyDictionary) -> pd.DataFrame:
df = ld["data_df"]
ss = ld["stocks_by_sector"]
pe_pos_df, _ = make_pe_trends_positive_pe_df(df, ss)
market_avg_pe_df = pe_pos_df.mean(axis=0, numeric_only=True).to_frame(
name="market_pe"
) # avg P/E by date series
market_avg_pe_df["date"] = pd.to_datetime(market_avg_pe_df.index)
return market_avg_pe_df
def sector_eps_data_factory(ld: LazyDictionary) -> pd.DataFrame:
df = ld["data_df"]
n_stocks = df["asx_code"].nunique()
pe_df, positive_pe_stocks = ld["positive_pe_tuple"]
eps_df = ld["eps_df"]
ss = ld["stocks_by_sector"]
# print(positive_pe_stocks)
eps_stocks = set(eps_df.index)
ss_dict = {row.asx_code: row.sector_name for row in ss.itertuples()}
# print(ss_dict)
trading_dates = set(pe_df.columns)
trading_dates.remove("sector_name")
sector_counts_all_stocks = ss["sector_name"].value_counts()
all_sectors = set(ss["sector_name"].unique())
breakdown_by_sector_pe_pos_stocks_only = pe_df["sector_name"].value_counts()
# print(breakdown_by_sector_pe_pos_stocks_only)
sector_counts_pe_pos_stocks_only = {
s[0]: s[1] for s in breakdown_by_sector_pe_pos_stocks_only.items()
}
# print(sector_counts_pe_pos_stocks_only)
# print(sector_counts_all_stocks)
# print(sector_counts_pe_pos_stocks_only)
records = []
for ymd in filter(
lambda d: d in trading_dates, ld["timeframe"].all_dates()
): # needed to avoid KeyError raised during DataFrame.at[] calls below
sum_pe_per_sector = defaultdict(float)
sum_eps_per_sector = defaultdict(float)
for stock in filter(lambda code: code in ss_dict, positive_pe_stocks):
sector = ss_dict[stock]
assert isinstance(sector, str)
if stock in eps_stocks:
eps = eps_df.at[stock, ymd]
if isnan(eps):
continue
sum_eps_per_sector[sector] += eps
if stock in positive_pe_stocks:
pe = pe_df.at[stock, ymd]
if isnan(pe):
continue
assert pe >= 0.0
sum_pe_per_sector[sector] += pe
# print(len(sector_counts_all_stocks))
# print(len(sum_eps_per_sector))
assert len(sector_counts_pe_pos_stocks_only) >= len(sum_pe_per_sector)
assert len(sector_counts_all_stocks) >= len(sum_eps_per_sector)
for sector in all_sectors:
pe_sum = sum_pe_per_sector.get(sector, None)
n_pe = sector_counts_pe_pos_stocks_only.get(sector, None)
pe_mean = pe_sum / n_pe if pe_sum is not None else None
eps_sum = sum_eps_per_sector.get(sector, None)
records.append(
{
"date": ymd,
"sector": sector,
"mean_pe": pe_mean,
"sum_pe": pe_sum,
"sum_eps": eps_sum,
"n_stocks": n_stocks,
"n_sector_stocks_pe_only": n_pe,
}
)
df =
|
pd.DataFrame.from_records(records)
|
pandas.DataFrame.from_records
|
import warnings
import numpy as np
import pandas as pd
from pandas.api.types import (
is_categorical_dtype,
is_datetime64tz_dtype,
is_interval_dtype,
is_period_dtype,
is_scalar,
is_sparse,
union_categoricals,
)
from ..utils import is_arraylike, typename
from ._compat import PANDAS_GT_100
from .core import DataFrame, Index, Scalar, Series, _Frame
from .dispatch import (
categorical_dtype_dispatch,
concat,
concat_dispatch,
get_parallel_type,
group_split_dispatch,
hash_object_dispatch,
is_categorical_dtype_dispatch,
make_meta,
make_meta_obj,
meta_nonempty,
tolist_dispatch,
union_categoricals_dispatch,
)
from .extensions import make_array_nonempty, make_scalar
from .utils import (
_empty_series,
_nonempty_scalar,
_scalar_from_dtype,
is_categorical_dtype,
is_float_na_dtype,
is_integer_na_dtype,
)
##########
# Pandas #
##########
@make_scalar.register(np.dtype)
def _(dtype):
return _scalar_from_dtype(dtype)
@make_scalar.register(pd.Timestamp)
@make_scalar.register(pd.Timedelta)
@make_scalar.register(pd.Period)
@make_scalar.register(pd.Interval)
def _(x):
return x
@make_meta.register((pd.Series, pd.DataFrame))
def make_meta_pandas(x, index=None):
return x.iloc[:0]
@make_meta.register(pd.Index)
def make_meta_index(x, index=None):
return x[0:0]
meta_object_types = (pd.Series, pd.DataFrame, pd.Index, pd.MultiIndex)
try:
import scipy.sparse as sp
meta_object_types += (sp.spmatrix,)
except ImportError:
pass
@make_meta_obj.register(meta_object_types)
def make_meta_object(x, index=None):
"""Create an empty pandas object containing the desired metadata.
Parameters
----------
x : dict, tuple, list, pd.Series, pd.DataFrame, pd.Index, dtype, scalar
To create a DataFrame, provide a `dict` mapping of `{name: dtype}`, or
an iterable of `(name, dtype)` tuples. To create a `Series`, provide a
tuple of `(name, dtype)`. If a pandas object, names, dtypes, and index
should match the desired output. If a dtype or scalar, a scalar of the
same dtype is returned.
index : pd.Index, optional
Any pandas index to use in the metadata. If none provided, a
`RangeIndex` will be used.
Examples
--------
>>> make_meta([('a', 'i8'), ('b', 'O')]) # doctest: +SKIP
Empty DataFrame
Columns: [a, b]
Index: []
>>> make_meta(('a', 'f8')) # doctest: +SKIP
Series([], Name: a, dtype: float64)
>>> make_meta('i8') # doctest: +SKIP
1
"""
if is_arraylike(x) and x.shape:
return x[:0]
if index is not None:
index = make_meta(index)
if isinstance(x, dict):
return pd.DataFrame(
{c: _empty_series(c, d, index=index) for (c, d) in x.items()}, index=index
)
if isinstance(x, tuple) and len(x) == 2:
return _empty_series(x[0], x[1], index=index)
elif isinstance(x, (list, tuple)):
if not all(isinstance(i, tuple) and len(i) == 2 for i in x):
raise ValueError(
"Expected iterable of tuples of (name, dtype), got {0}".format(x)
)
return pd.DataFrame(
{c: _empty_series(c, d, index=index) for (c, d) in x},
columns=[c for c, d in x],
index=index,
)
elif not hasattr(x, "dtype") and x is not None:
# could be a string, a dtype object, or a python type. Skip `None`,
# because it is implictly converted to `dtype('f8')`, which we don't
# want here.
try:
dtype = np.dtype(x)
return _scalar_from_dtype(dtype)
except Exception:
# Continue on to next check
pass
if is_scalar(x):
return _nonempty_scalar(x)
raise TypeError("Don't know how to create metadata from {0}".format(x))
@meta_nonempty.register(object)
def meta_nonempty_object(x):
"""Create a nonempty pandas object from the given metadata.
Returns a pandas DataFrame, Series, or Index that contains two rows
of fake data.
"""
if is_scalar(x):
return _nonempty_scalar(x)
else:
raise TypeError(
"Expected Pandas-like Index, Series, DataFrame, or scalar, "
"got {0}".format(typename(type(x)))
)
@meta_nonempty.register(pd.DataFrame)
def meta_nonempty_dataframe(x):
idx = meta_nonempty(x.index)
dt_s_dict = dict()
data = dict()
for i, c in enumerate(x.columns):
series = x.iloc[:, i]
dt = series.dtype
if dt not in dt_s_dict:
dt_s_dict[dt] = _nonempty_series(x.iloc[:, i], idx=idx)
data[i] = dt_s_dict[dt]
res = pd.DataFrame(data, index=idx, columns=np.arange(len(x.columns)))
res.columns = x.columns
if PANDAS_GT_100:
res.attrs = x.attrs
return res
_numeric_index_types = (pd.Int64Index, pd.Float64Index, pd.UInt64Index)
@meta_nonempty.register(pd.Index)
def _nonempty_index(idx):
typ = type(idx)
if typ is pd.RangeIndex:
return pd.RangeIndex(2, name=idx.name)
elif typ in _numeric_index_types:
return typ([1, 2], name=idx.name)
elif typ is pd.Index:
return pd.Index(["a", "b"], name=idx.name)
elif typ is pd.DatetimeIndex:
start = "1970-01-01"
# Need a non-monotonic decreasing index to avoid issues with
# partial string indexing see https://github.com/dask/dask/issues/2389
# and https://github.com/pandas-dev/pandas/issues/16515
# This doesn't mean `_meta_nonempty` should ever rely on
# `self.monotonic_increasing` or `self.monotonic_decreasing`
try:
return pd.date_range(
start=start, periods=2, freq=idx.freq, tz=idx.tz, name=idx.name
)
except ValueError: # older pandas versions
data = [start, "1970-01-02"] if idx.freq is None else None
return pd.DatetimeIndex(
data, start=start, periods=2, freq=idx.freq, tz=idx.tz, name=idx.name
)
elif typ is pd.PeriodIndex:
return pd.period_range(
start="1970-01-01", periods=2, freq=idx.freq, name=idx.name
)
elif typ is pd.TimedeltaIndex:
start = np.timedelta64(1, "D")
try:
return pd.timedelta_range(
start=start, periods=2, freq=idx.freq, name=idx.name
)
except ValueError: # older pandas versions
start = np.timedelta64(1, "D")
data = [start, start + 1] if idx.freq is None else None
return pd.TimedeltaIndex(
data, start=start, periods=2, freq=idx.freq, name=idx.name
)
elif typ is pd.CategoricalIndex:
if len(idx.categories) == 0:
data = pd.Categorical(_nonempty_index(idx.categories), ordered=idx.ordered)
else:
data = pd.Categorical.from_codes(
[-1, 0], categories=idx.categories, ordered=idx.ordered
)
return pd.CategoricalIndex(data, name=idx.name)
elif typ is pd.MultiIndex:
levels = [_nonempty_index(l) for l in idx.levels]
codes = [[0, 0] for i in idx.levels]
try:
return pd.MultiIndex(levels=levels, codes=codes, names=idx.names)
except TypeError: # older pandas versions
return pd.MultiIndex(levels=levels, labels=codes, names=idx.names)
raise TypeError(
"Don't know how to handle index of type {0}".format(typename(type(idx)))
)
@meta_nonempty.register(pd.Series)
def _nonempty_series(s, idx=None):
# TODO: Use register dtypes with make_array_nonempty
if idx is None:
idx = _nonempty_index(s.index)
dtype = s.dtype
if len(s) > 0:
# use value from meta if provided
data = [s.iloc[0]] * 2
elif is_datetime64tz_dtype(dtype):
entry = pd.Timestamp("1970-01-01", tz=dtype.tz)
data = [entry, entry]
elif is_categorical_dtype(dtype):
if len(s.cat.categories):
data = [s.cat.categories[0]] * 2
cats = s.cat.categories
else:
data = _nonempty_index(s.cat.categories)
cats = s.cat.categories[:0]
data = pd.Categorical(data, categories=cats, ordered=s.cat.ordered)
elif is_integer_na_dtype(dtype):
data = pd.array([1, None], dtype=dtype)
elif is_float_na_dtype(dtype):
data = pd.array([1.0, None], dtype=dtype)
elif is_period_dtype(dtype):
# pandas 0.24.0+ should infer this to be Series[Period[freq]]
freq = dtype.freq
data = [pd.Period("2000", freq), pd.Period("2001", freq)]
elif is_sparse(dtype):
entry = _scalar_from_dtype(dtype.subtype)
if PANDAS_GT_100:
data = pd.array([entry, entry], dtype=dtype)
else:
data = pd.SparseArray([entry, entry], dtype=dtype)
elif is_interval_dtype(dtype):
entry = _scalar_from_dtype(dtype.subtype)
data = pd.array([entry, entry], dtype=dtype)
elif type(dtype) in make_array_nonempty._lookup:
data = make_array_nonempty(dtype)
else:
entry = _scalar_from_dtype(dtype)
data = np.array([entry, entry], dtype=dtype)
out = pd.Series(data, name=s.name, index=idx)
if PANDAS_GT_100:
out.attrs = s.attrs
return out
@union_categoricals_dispatch.register(
(pd.DataFrame, pd.Series, pd.Index, pd.Categorical)
)
def union_categoricals_pandas(to_union, sort_categories=False, ignore_order=False):
return pd.api.types.union_categoricals(
to_union, sort_categories=sort_categories, ignore_order=ignore_order
)
@get_parallel_type.register(pd.Series)
def get_parallel_type_series(_):
return Series
@get_parallel_type.register(pd.DataFrame)
def get_parallel_type_dataframe(_):
return DataFrame
@get_parallel_type.register(pd.Index)
def get_parallel_type_index(_):
return Index
@get_parallel_type.register(_Frame)
def get_parallel_type_frame(o):
return get_parallel_type(o._meta)
@get_parallel_type.register(object)
def get_parallel_type_object(_):
return Scalar
@hash_object_dispatch.register((pd.DataFrame, pd.Series, pd.Index))
def hash_object_pandas(
obj, index=True, encoding="utf8", hash_key=None, categorize=True
):
return pd.util.hash_pandas_object(
obj, index=index, encoding=encoding, hash_key=hash_key, categorize=categorize
)
@group_split_dispatch.register((pd.DataFrame, pd.Series, pd.Index))
def group_split_pandas(df, c, k, ignore_index=False):
indexer, locations = pd._libs.algos.groupsort_indexer(
c.astype(np.int64, copy=False), k
)
df2 = df.take(indexer)
locations = locations.cumsum()
parts = [
df2.iloc[a:b].reset_index(drop=True) if ignore_index else df2.iloc[a:b]
for a, b in zip(locations[:-1], locations[1:])
]
return dict(zip(range(k), parts))
@concat_dispatch.register((pd.DataFrame, pd.Series, pd.Index))
def concat_pandas(
dfs,
axis=0,
join="outer",
uniform=False,
filter_warning=True,
ignore_index=False,
**kwargs
):
ignore_order = kwargs.pop("ignore_order", False)
if axis == 1:
return
|
pd.concat(dfs, axis=axis, join=join, **kwargs)
|
pandas.concat
|
# Copyright 1999-2021 Alibaba Group Holding Ltd.
#
# 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 pandas as pd
import pytest
from mars import opcodes
from mars.config import options, option_context
from mars.core import OutputType, tile
from mars.core.operand import OperandStage
from mars.dataframe import eval as mars_eval, cut, to_numeric
from mars.dataframe.base import to_gpu, to_cpu, astype
from mars.dataframe.core import DATAFRAME_TYPE, SERIES_TYPE, SERIES_CHUNK_TYPE, \
INDEX_TYPE, CATEGORICAL_TYPE, CATEGORICAL_CHUNK_TYPE
from mars.dataframe.datasource.dataframe import from_pandas as from_pandas_df
from mars.dataframe.datasource.series import from_pandas as from_pandas_series
from mars.dataframe.datasource.index import from_pandas as from_pandas_index
from mars.tensor.core import TENSOR_TYPE
def test_to_gpu():
# test dataframe
data = pd.DataFrame(np.random.rand(10, 10), index=np.random.randint(-100, 100, size=(10,)),
columns=[np.random.bytes(10) for _ in range(10)])
df = from_pandas_df(data)
cdf = to_gpu(df)
assert df.index_value == cdf.index_value
assert df.columns_value == cdf.columns_value
assert cdf.op.gpu is True
pd.testing.assert_series_equal(df.dtypes, cdf.dtypes)
df, cdf = tile(df, cdf)
assert df.nsplits == cdf.nsplits
assert df.chunks[0].index_value == cdf.chunks[0].index_value
assert df.chunks[0].columns_value == cdf.chunks[0].columns_value
assert cdf.chunks[0].op.gpu is True
pd.testing.assert_series_equal(df.chunks[0].dtypes, cdf.chunks[0].dtypes)
assert cdf is to_gpu(cdf)
# test series
sdata = data.iloc[:, 0]
series = from_pandas_series(sdata)
cseries = to_gpu(series)
assert series.index_value == cseries.index_value
assert cseries.op.gpu is True
series, cseries = tile(series, cseries)
assert series.nsplits == cseries.nsplits
assert series.chunks[0].index_value == cseries.chunks[0].index_value
assert cseries.chunks[0].op.gpu is True
assert cseries is to_gpu(cseries)
def test_to_cpu():
data = pd.DataFrame(np.random.rand(10, 10), index=np.random.randint(-100, 100, size=(10,)),
columns=[np.random.bytes(10) for _ in range(10)])
df = from_pandas_df(data)
cdf = to_gpu(df)
df2 = to_cpu(cdf)
assert df.index_value == df2.index_value
assert df.columns_value == df2.columns_value
assert df2.op.gpu is False
pd.testing.assert_series_equal(df.dtypes, df2.dtypes)
df, df2 = tile(df, df2)
assert df.nsplits == df2.nsplits
assert df.chunks[0].index_value == df2.chunks[0].index_value
assert df.chunks[0].columns_value == df2.chunks[0].columns_value
assert df2.chunks[0].op.gpu is False
pd.testing.assert_series_equal(df.chunks[0].dtypes, df2.chunks[0].dtypes)
assert df2 is to_cpu(df2)
def test_rechunk():
raw = pd.DataFrame(np.random.rand(10, 10))
df = from_pandas_df(raw, chunk_size=3)
df2 = tile(df.rechunk(4))
assert df2.shape == (10, 10)
assert len(df2.chunks) == 9
assert df2.chunks[0].shape == (4, 4)
pd.testing.assert_index_equal(df2.chunks[0].index_value.to_pandas(), pd.RangeIndex(4))
pd.testing.assert_index_equal(df2.chunks[0].columns_value.to_pandas(), pd.RangeIndex(4))
pd.testing.assert_series_equal(df2.chunks[0].dtypes, raw.dtypes[:4])
assert df2.chunks[2].shape == (4, 2)
pd.testing.assert_index_equal(df2.chunks[2].index_value.to_pandas(), pd.RangeIndex(4))
pd.testing.assert_index_equal(df2.chunks[2].columns_value.to_pandas(), pd.RangeIndex(8, 10))
pd.testing.assert_series_equal(df2.chunks[2].dtypes, raw.dtypes[-2:])
assert df2.chunks[-1].shape == (2, 2)
pd.testing.assert_index_equal(df2.chunks[-1].index_value.to_pandas(), pd.RangeIndex(8, 10))
pd.testing.assert_index_equal(df2.chunks[-1].columns_value.to_pandas(), pd.RangeIndex(8, 10))
pd.testing.assert_series_equal(df2.chunks[-1].dtypes, raw.dtypes[-2:])
for c in df2.chunks:
assert c.shape[1] == len(c.dtypes)
assert len(c.columns_value.to_pandas()) == len(c.dtypes)
columns = [np.random.bytes(10) for _ in range(10)]
index = np.random.randint(-100, 100, size=(4,))
raw = pd.DataFrame(np.random.rand(4, 10), index=index, columns=columns)
df = from_pandas_df(raw, chunk_size=3)
df2 = tile(df.rechunk(6))
assert df2.shape == (4, 10)
assert len(df2.chunks) == 2
assert df2.chunks[0].shape == (4, 6)
pd.testing.assert_index_equal(df2.chunks[0].index_value.to_pandas(), df.index_value.to_pandas())
pd.testing.assert_index_equal(df2.chunks[0].columns_value.to_pandas(), pd.Index(columns[:6]))
pd.testing.assert_series_equal(df2.chunks[0].dtypes, raw.dtypes[:6])
assert df2.chunks[1].shape == (4, 4)
pd.testing.assert_index_equal(df2.chunks[1].index_value.to_pandas(), df.index_value.to_pandas())
pd.testing.assert_index_equal(df2.chunks[1].columns_value.to_pandas(), pd.Index(columns[6:]))
pd.testing.assert_series_equal(df2.chunks[1].dtypes, raw.dtypes[-4:])
for c in df2.chunks:
assert c.shape[1] == len(c.dtypes)
assert len(c.columns_value.to_pandas()) == len(c.dtypes)
# test Series rechunk
series = from_pandas_series(pd.Series(np.random.rand(10,)), chunk_size=3)
series2 = tile(series.rechunk(4))
assert series2.shape == (10,)
assert len(series2.chunks) == 3
pd.testing.assert_index_equal(series2.index_value.to_pandas(), pd.RangeIndex(10))
assert series2.chunk_shape == (3,)
assert series2.nsplits == ((4, 4, 2), )
assert series2.chunks[0].shape == (4,)
pd.testing.assert_index_equal(series2.chunks[0].index_value.to_pandas(), pd.RangeIndex(4))
assert series2.chunks[1].shape == (4,)
pd.testing.assert_index_equal(series2.chunks[1].index_value.to_pandas(), pd.RangeIndex(4, 8))
assert series2.chunks[2].shape == (2,)
pd.testing.assert_index_equal(series2.chunks[2].index_value.to_pandas(), pd.RangeIndex(8, 10))
series2 = tile(series.rechunk(1))
assert series2.shape == (10,)
assert len(series2.chunks) == 10
pd.testing.assert_index_equal(series2.index_value.to_pandas(), pd.RangeIndex(10))
assert series2.chunk_shape == (10,)
assert series2.nsplits == ((1,) * 10, )
assert series2.chunks[0].shape == (1,)
pd.testing.assert_index_equal(series2.chunks[0].index_value.to_pandas(), pd.RangeIndex(1))
# no need to rechunk
series2 = tile(series.rechunk(3))
series = tile(series)
assert series2.chunk_shape == series.chunk_shape
assert series2.nsplits == series.nsplits
def test_data_frame_apply():
cols = [chr(ord('A') + i) for i in range(10)]
df_raw = pd.DataFrame(dict((c, [i ** 2 for i in range(20)]) for c in cols))
old_chunk_store_limit = options.chunk_store_limit
try:
options.chunk_store_limit = 20
df = from_pandas_df(df_raw, chunk_size=5)
def df_func_with_err(v):
assert len(v) > 2
return v.sort_values()
with pytest.raises(TypeError):
df.apply(df_func_with_err)
r = df.apply(df_func_with_err, output_type='dataframe',
dtypes=df_raw.dtypes)
assert r.shape == (np.nan, df.shape[-1])
assert r.op._op_type_ == opcodes.APPLY
assert r.op.output_types[0] == OutputType.dataframe
assert r.op.elementwise is False
r = df.apply('ffill')
assert r.op._op_type_ == opcodes.FILL_NA
r = tile(df.apply(np.sqrt))
assert all(v == np.dtype('float64') for v in r.dtypes) is True
assert r.shape == df.shape
assert r.op._op_type_ == opcodes.APPLY
assert r.op.output_types[0] == OutputType.dataframe
assert r.op.elementwise is True
r = tile(df.apply(lambda x: pd.Series([1, 2])))
assert all(v == np.dtype('int64') for v in r.dtypes) is True
assert r.shape == (np.nan, df.shape[1])
assert r.op.output_types[0] == OutputType.dataframe
assert r.chunks[0].shape == (np.nan, 1)
assert r.chunks[0].inputs[0].shape[0] == df_raw.shape[0]
assert r.chunks[0].inputs[0].op._op_type_ == opcodes.CONCATENATE
assert r.op.elementwise is False
r = tile(df.apply(np.sum, axis='index'))
assert np.dtype('int64') == r.dtype
assert r.shape == (df.shape[1],)
assert r.op.output_types[0] == OutputType.series
assert r.chunks[0].shape == (20 // df.shape[0],)
assert r.chunks[0].inputs[0].shape[0] == df_raw.shape[0]
assert r.chunks[0].inputs[0].op._op_type_ == opcodes.CONCATENATE
assert r.op.elementwise is False
r = tile(df.apply(np.sum, axis='columns'))
assert np.dtype('int64') == r.dtype
assert r.shape == (df.shape[0],)
assert r.op.output_types[0] == OutputType.series
assert r.chunks[0].shape == (20 // df.shape[1],)
assert r.chunks[0].inputs[0].shape[1] == df_raw.shape[1]
assert r.chunks[0].inputs[0].op._op_type_ == opcodes.CONCATENATE
assert r.op.elementwise is False
r = tile(df.apply(lambda x: pd.Series([1, 2], index=['foo', 'bar']), axis=1))
assert all(v == np.dtype('int64') for v in r.dtypes) is True
assert r.shape == (df.shape[0], np.nan)
assert r.op.output_types[0] == OutputType.dataframe
assert r.chunks[0].shape == (20 // df.shape[1], np.nan)
assert r.chunks[0].inputs[0].shape[1] == df_raw.shape[1]
assert r.chunks[0].inputs[0].op._op_type_ == opcodes.CONCATENATE
assert r.op.elementwise is False
r = tile(df.apply(lambda x: [1, 2], axis=1, result_type='expand'))
assert all(v == np.dtype('int64') for v in r.dtypes) is True
assert r.shape == (df.shape[0], np.nan)
assert r.op.output_types[0] == OutputType.dataframe
assert r.chunks[0].shape == (20 // df.shape[1], np.nan)
assert r.chunks[0].inputs[0].shape[1] == df_raw.shape[1]
assert r.chunks[0].inputs[0].op._op_type_ == opcodes.CONCATENATE
assert r.op.elementwise is False
r = tile(df.apply(lambda x: list(range(10)), axis=1, result_type='reduce'))
assert np.dtype('object') == r.dtype
assert r.shape == (df.shape[0],)
assert r.op.output_types[0] == OutputType.series
assert r.chunks[0].shape == (20 // df.shape[1],)
assert r.chunks[0].inputs[0].shape[1] == df_raw.shape[1]
assert r.chunks[0].inputs[0].op._op_type_ == opcodes.CONCATENATE
assert r.op.elementwise is False
r = tile(df.apply(lambda x: list(range(10)), axis=1, result_type='broadcast'))
assert all(v == np.dtype('int64') for v in r.dtypes) is True
assert r.shape == (df.shape[0], np.nan)
assert r.op.output_types[0] == OutputType.dataframe
assert r.chunks[0].shape == (20 // df.shape[1], np.nan)
assert r.chunks[0].inputs[0].shape[1] == df_raw.shape[1]
assert r.chunks[0].inputs[0].op._op_type_ == opcodes.CONCATENATE
assert r.op.elementwise is False
finally:
options.chunk_store_limit = old_chunk_store_limit
raw = pd.DataFrame({'a': [np.array([1, 2, 3]), np.array([4, 5, 6])]})
df = from_pandas_df(raw)
df2 = df.apply(lambda x: x['a'].astype(pd.Series), axis=1,
output_type='dataframe', dtypes=pd.Series([np.dtype(float)] * 3))
assert df2.ndim == 2
def test_series_apply():
idxes = [chr(ord('A') + i) for i in range(20)]
s_raw = pd.Series([i ** 2 for i in range(20)], index=idxes)
series = from_pandas_series(s_raw, chunk_size=5)
r = tile(series.apply('add', args=(1,)))
assert r.op._op_type_ == opcodes.ADD
r = tile(series.apply(np.sqrt))
assert np.dtype('float64') == r.dtype
assert r.shape == series.shape
assert r.op._op_type_ == opcodes.APPLY
assert r.op.output_types[0] == OutputType.series
assert r.chunks[0].shape == (5,)
assert r.chunks[0].inputs[0].shape == (5,)
r = tile(series.apply('sqrt'))
assert np.dtype('float64') == r.dtype
assert r.shape == series.shape
assert r.op._op_type_ == opcodes.APPLY
assert r.op.output_types[0] == OutputType.series
assert r.chunks[0].shape == (5,)
assert r.chunks[0].inputs[0].shape == (5,)
r = tile(series.apply(lambda x: [x, x + 1], convert_dtype=False))
assert np.dtype('object') == r.dtype
assert r.shape == series.shape
assert r.op._op_type_ == opcodes.APPLY
assert r.op.output_types[0] == OutputType.series
assert r.chunks[0].shape == (5,)
assert r.chunks[0].inputs[0].shape == (5,)
s_raw2 = pd.Series([np.array([1, 2, 3]), np.array([4, 5, 6])])
series = from_pandas_series(s_raw2)
r = series.apply(np.sum)
assert r.dtype == np.dtype(object)
r = series.apply(lambda x: pd.Series([1]), output_type='dataframe')
expected = s_raw2.apply(lambda x: pd.Series([1]))
pd.testing.assert_series_equal(r.dtypes, expected.dtypes)
dtypes = pd.Series([np.dtype(float)] * 3)
r = series.apply(pd.Series, output_type='dataframe',
dtypes=dtypes)
assert r.ndim == 2
pd.testing.assert_series_equal(r.dtypes, dtypes)
assert r.shape == (2, 3)
r = series.apply(pd.Series, output_type='dataframe',
dtypes=dtypes, index=pd.RangeIndex(2))
assert r.ndim == 2
pd.testing.assert_series_equal(r.dtypes, dtypes)
assert r.shape == (2, 3)
with pytest.raises(AttributeError, match='abc'):
series.apply('abc')
with pytest.raises(TypeError):
# dtypes not provided
series.apply(lambda x: x.tolist(), output_type='dataframe')
def test_transform():
cols = [chr(ord('A') + i) for i in range(10)]
df_raw = pd.DataFrame(dict((c, [i ** 2 for i in range(20)]) for c in cols))
df = from_pandas_df(df_raw, chunk_size=5)
idxes = [chr(ord('A') + i) for i in range(20)]
s_raw = pd.Series([i ** 2 for i in range(20)], index=idxes)
series = from_pandas_series(s_raw, chunk_size=5)
def rename_fn(f, new_name):
f.__name__ = new_name
return f
old_chunk_store_limit = options.chunk_store_limit
try:
options.chunk_store_limit = 20
# DATAFRAME CASES
# test transform with infer failure
def transform_df_with_err(v):
assert len(v) > 2
return v.sort_values()
with pytest.raises(TypeError):
df.transform(transform_df_with_err)
r = tile(df.transform(transform_df_with_err, dtypes=df_raw.dtypes))
assert r.shape == df.shape
assert r.op._op_type_ == opcodes.TRANSFORM
assert r.op.output_types[0] == OutputType.dataframe
assert r.chunks[0].shape == (df.shape[0], 20 // df.shape[0])
assert r.chunks[0].inputs[0].shape[0] == df_raw.shape[0]
assert r.chunks[0].inputs[0].op._op_type_ == opcodes.CONCATENATE
# test transform scenarios on data frames
r = tile(df.transform(lambda x: list(range(len(x)))))
assert all(v == np.dtype('int64') for v in r.dtypes) is True
assert r.shape == df.shape
assert r.op._op_type_ == opcodes.TRANSFORM
assert r.op.output_types[0] == OutputType.dataframe
assert r.chunks[0].shape == (df.shape[0], 20 // df.shape[0])
assert r.chunks[0].inputs[0].shape[0] == df_raw.shape[0]
assert r.chunks[0].inputs[0].op._op_type_ == opcodes.CONCATENATE
r = tile(df.transform(lambda x: list(range(len(x))), axis=1))
assert all(v == np.dtype('int64') for v in r.dtypes) is True
assert r.shape == df.shape
assert r.op._op_type_ == opcodes.TRANSFORM
assert r.op.output_types[0] == OutputType.dataframe
assert r.chunks[0].shape == (20 // df.shape[1], df.shape[1])
assert r.chunks[0].inputs[0].shape[1] == df_raw.shape[1]
assert r.chunks[0].inputs[0].op._op_type_ == opcodes.CONCATENATE
r = tile(df.transform(['cumsum', 'cummax', lambda x: x + 1]))
assert all(v == np.dtype('int64') for v in r.dtypes) is True
assert r.shape == (df.shape[0], df.shape[1] * 3)
assert r.op._op_type_ == opcodes.TRANSFORM
assert r.op.output_types[0] == OutputType.dataframe
assert r.chunks[0].shape == (df.shape[0], 20 // df.shape[0] * 3)
assert r.chunks[0].inputs[0].shape[0] == df_raw.shape[0]
assert r.chunks[0].inputs[0].op._op_type_ == opcodes.CONCATENATE
r = tile(df.transform({'A': 'cumsum', 'D': ['cumsum', 'cummax'], 'F': lambda x: x + 1}))
assert all(v == np.dtype('int64') for v in r.dtypes) is True
assert r.shape == (df.shape[0], 4)
assert r.op._op_type_ == opcodes.TRANSFORM
assert r.op.output_types[0] == OutputType.dataframe
assert r.chunks[0].shape == (df.shape[0], 1)
assert r.chunks[0].inputs[0].shape[0] == df_raw.shape[0]
assert r.chunks[0].inputs[0].op._op_type_ == opcodes.CONCATENATE
# test agg scenarios on series
r = tile(df.transform(lambda x: x.iloc[:-1], _call_agg=True))
assert all(v == np.dtype('int64') for v in r.dtypes) is True
assert r.shape == (np.nan, df.shape[1])
assert r.op._op_type_ == opcodes.TRANSFORM
assert r.op.output_types[0] == OutputType.dataframe
assert r.chunks[0].shape == (np.nan, 1)
assert r.chunks[0].inputs[0].shape[0] == df_raw.shape[0]
assert r.chunks[0].inputs[0].op._op_type_ == opcodes.CONCATENATE
r = tile(df.transform(lambda x: x.iloc[:-1], axis=1, _call_agg=True))
assert all(v == np.dtype('int64') for v in r.dtypes) is True
assert r.shape == (df.shape[0], np.nan)
assert r.op._op_type_ == opcodes.TRANSFORM
assert r.op.output_types[0] == OutputType.dataframe
assert r.chunks[0].shape == (2, np.nan)
assert r.chunks[0].inputs[0].shape[1] == df_raw.shape[1]
assert r.chunks[0].inputs[0].op._op_type_ == opcodes.CONCATENATE
fn_list = [rename_fn(lambda x: x.iloc[1:].reset_index(drop=True), 'f1'),
lambda x: x.iloc[:-1].reset_index(drop=True)]
r = tile(df.transform(fn_list, _call_agg=True))
assert all(v == np.dtype('int64') for v in r.dtypes) is True
assert r.shape == (np.nan, df.shape[1] * 2)
assert r.op._op_type_ == opcodes.TRANSFORM
assert r.op.output_types[0] == OutputType.dataframe
assert r.chunks[0].shape == (np.nan, 2)
assert r.chunks[0].inputs[0].shape[0] == df_raw.shape[0]
assert r.chunks[0].inputs[0].op._op_type_ == opcodes.CONCATENATE
r = tile(df.transform(lambda x: x.sum(), _call_agg=True))
assert r.dtype == np.dtype('int64')
assert r.shape == (df.shape[1],)
assert r.op._op_type_ == opcodes.TRANSFORM
assert r.op.output_types[0] == OutputType.series
assert r.chunks[0].shape == (20 // df.shape[0],)
assert r.chunks[0].inputs[0].shape[0] == df_raw.shape[0]
assert r.chunks[0].inputs[0].op._op_type_ == opcodes.CONCATENATE
fn_dict = {
'A': rename_fn(lambda x: x.iloc[1:].reset_index(drop=True), 'f1'),
'D': [rename_fn(lambda x: x.iloc[1:].reset_index(drop=True), 'f1'),
lambda x: x.iloc[:-1].reset_index(drop=True)],
'F': lambda x: x.iloc[:-1].reset_index(drop=True),
}
r = tile(df.transform(fn_dict, _call_agg=True))
assert all(v == np.dtype('int64') for v in r.dtypes) is True
assert r.shape == (np.nan, 4)
assert r.op._op_type_ == opcodes.TRANSFORM
assert r.op.output_types[0] == OutputType.dataframe
assert r.chunks[0].shape == (np.nan, 1)
assert r.chunks[0].inputs[0].shape[0] == df_raw.shape[0]
assert r.chunks[0].inputs[0].op._op_type_ == opcodes.CONCATENATE
# SERIES CASES
# test transform scenarios on series
r = tile(series.transform(lambda x: x + 1))
assert np.dtype('int64') == r.dtype
assert r.shape == series.shape
assert r.op._op_type_ == opcodes.TRANSFORM
assert r.op.output_types[0] == OutputType.series
assert r.chunks[0].shape == (5,)
assert r.chunks[0].inputs[0].shape == (5,)
finally:
options.chunk_store_limit = old_chunk_store_limit
def test_string_method():
s = pd.Series(['a', 'b', 'c'], name='s')
series = from_pandas_series(s, chunk_size=2)
with pytest.raises(AttributeError):
_ = series.str.non_exist
r = series.str.contains('c')
assert r.dtype == np.bool_
assert r.name == s.name
pd.testing.assert_index_equal(r.index_value.to_pandas(), s.index)
assert r.shape == s.shape
r = tile(r)
for i, c in enumerate(r.chunks):
assert c.index == (i,)
assert c.dtype == np.bool_
assert c.name == s.name
pd.testing.assert_index_equal(c.index_value.to_pandas(),
s.index[i * 2: (i + 1) * 2])
assert c.shape == (2,) if i == 0 else (1,)
r = series.str.split(',', expand=True, n=1)
assert r.op.output_types[0] == OutputType.dataframe
assert r.shape == (3, 2)
pd.testing.assert_index_equal(r.index_value.to_pandas(), s.index)
pd.testing.assert_index_equal(r.columns_value.to_pandas(), pd.RangeIndex(2))
r = tile(r)
for i, c in enumerate(r.chunks):
assert c.index == (i, 0)
pd.testing.assert_index_equal(c.index_value.to_pandas(),
s.index[i * 2: (i + 1) * 2])
pd.testing.assert_index_equal(c.columns_value.to_pandas(), pd.RangeIndex(2))
assert c.shape == (2, 2) if i == 0 else (1, 2)
with pytest.raises(TypeError):
_ = series.str.cat([['1', '2']])
with pytest.raises(ValueError):
_ = series.str.cat(['1', '2'])
with pytest.raises(ValueError):
_ = series.str.cat(',')
with pytest.raises(TypeError):
_ = series.str.cat({'1', '2', '3'})
r = series.str.cat(sep=',')
assert r.op.output_types[0] == OutputType.scalar
assert r.dtype == s.dtype
r = tile(r)
assert len(r.chunks) == 1
assert r.chunks[0].op.output_types[0] == OutputType.scalar
assert r.chunks[0].dtype == s.dtype
r = series.str.extract(r'[ab](\d)', expand=False)
assert r.op.output_types[0] == OutputType.series
assert r.dtype == s.dtype
r = tile(r)
for i, c in enumerate(r.chunks):
assert c.index == (i,)
assert c.dtype == s.dtype
assert c.name == s.name
pd.testing.assert_index_equal(c.index_value.to_pandas(),
s.index[i * 2: (i + 1) * 2])
assert c.shape == (2,) if i == 0 else (1,)
r = series.str.extract(r'[ab](\d)', expand=True)
assert r.op.output_types[0] == OutputType.dataframe
assert r.shape == (3, 1)
pd.testing.assert_index_equal(r.index_value.to_pandas(), s.index)
pd.testing.assert_index_equal(r.columns_value.to_pandas(), pd.RangeIndex(1))
r = tile(r)
for i, c in enumerate(r.chunks):
assert c.index == (i, 0)
pd.testing.assert_index_equal(c.index_value.to_pandas(),
s.index[i * 2: (i + 1) * 2])
pd.testing.assert_index_equal(c.columns_value.to_pandas(), pd.RangeIndex(1))
assert c.shape == (2, 1) if i == 0 else (1, 1)
assert 'lstrip' in dir(series.str)
def test_datetime_method():
s = pd.Series([pd.Timestamp('2020-1-1'),
pd.Timestamp('2020-2-1'),
pd.Timestamp('2020-3-1')],
name='ss')
series = from_pandas_series(s, chunk_size=2)
r = series.dt.year
assert r.dtype == s.dt.year.dtype
pd.testing.assert_index_equal(r.index_value.to_pandas(), s.index)
assert r.shape == s.shape
assert r.op.output_types[0] == OutputType.series
assert r.name == s.dt.year.name
r = tile(r)
for i, c in enumerate(r.chunks):
assert c.index == (i,)
assert c.dtype == s.dt.year.dtype
assert c.op.output_types[0] == OutputType.series
assert r.name == s.dt.year.name
pd.testing.assert_index_equal(c.index_value.to_pandas(),
s.index[i * 2: (i + 1) * 2])
assert c.shape == (2,) if i == 0 else (1,)
with pytest.raises(AttributeError):
_ = series.dt.non_exist
assert 'ceil' in dir(series.dt)
def test_series_isin():
# one chunk in multiple chunks
a = from_pandas_series(
|
pd.Series([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
|
pandas.Series
|
"""
Author: <NAME>.
Date: 02/11/2020.
File to create a the files for K-Fold validation.
The dataset is expected to be in a folder following the structure:
data/
cross_validation/ (The folder you're currently in)
dataset/
0/
1/
preprocessing/
You must change the logic to read your dataset in case it follows another structure.
The bottom section of this code expects a list with the absoulte path to the images
and a list with their labels.
"""
import glob
import pandas as pd
from sklearn.model_selection import KFold
#! /////////// Change code to read your dataset //////
SPLIT_CHAR = '/' # Change for \\ if you're using Windows
DATASET_FOLDER = '..' + SPLIT_CHAR + 'dataset' + SPLIT_CHAR # Change '..' for an absolute path
IMAGE_EXTENSION = '*.png' # Change for the extension of your images
print('Reading Dataset...')
# Get absolute paths to all images in dataset
images = glob.glob(DATASET_FOLDER + '*' + SPLIT_CHAR + IMAGE_EXTENSION)
# Get labels per image
labels = [int(img.split(SPLIT_CHAR)[-2]) for img in images]
print("Splitting dataset...")
# Split dataset
NUMBER_0F_FOLDS = 5
kfolds = KFold(n_splits=NUMBER_0F_FOLDS, shuffle=True)
for fold, (train_ids, test_ids) in enumerate(kfolds.split(images)):
train_x = [images[id] for id in train_ids]
test_x = [images[id] for id in test_ids]
train_y = [labels[id] for id in train_ids]
test_y = [labels[id] for id in test_ids]
print("Saving dataset "+str(fold)+"...")
# Save the splits on csv files
train_df =
|
pd.DataFrame({'ID_IMG':train_x, 'LABEL': train_y})
|
pandas.DataFrame
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
NAME:
Bayt Data Scrapper
AUTHOR:
showmethedata.wiki
DESCRIPTION:
Scrap Bayt data in regular interval and store in structured format
CONTENTS:
The following APIs are public:
- get_data()
NOTES:
This program can be run either as a Python module (importable) or as a shell script from terminal.
"""
import requests
from bs4 import BeautifulSoup
from collections import namedtuple
from datetime import datetime
import logging
from time import time
import time
import functools
from pandas import DataFrame
from typing import List, NamedTuple
import argparse
import sys
# create and configure logger
LOG_FORMAT = "%(levelname)s %(asctime)s - %(message)s"
logging.basicConfig(filename=f'../logs/logging_scrap_bayt.log',
level=logging.DEBUG, format=LOG_FORMAT, filemode='w')
logger = logging.getLogger()
class ScrapBayt:
COUNTRY_ISO_MAP = dict(zip(
["united-arab-emirate", "qatar", "saudi-arabia"], ["uae", "qatar", "saudi-arabia"]))
HEADERS = {
'authority': 'www.bayt.com',
'cache-control': 'max-age=0',
'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="96", "Google Chrome";v="96"',
'sec-ch-ua-mobile': '?0',
'sec-ch-ua-platform': '"Linux"',
'upgrade-insecure-requests': '1',
'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.93 Safari/537.36',
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
'sec-fetch-site': 'none',
'sec-fetch-mode': 'navigate',
'sec-fetch-user': '?1',
'sec-fetch-dest': 'document',
'accept-language': 'en-US,en;q=0.9,de;q=0.8'}
SLEEP = 10 # delay between requests by page
def __init__(self, job_title: str, location: str) -> None:
"""Scrap jobs from Indeed website.
Args:
job_title (str): Search term
location (str): Country of interest. Can be either [`united-arab-emirate`, `qatar`, `saudi-arabia`] for now, however it could be extended in future with API calls to ISO country codes.
debug (bool, optional): [Enable logging to a log file for quick debugging access]. Defaults to True.
"""
assert isinstance(job_title, str)
assert isinstance(location, str) and location in self.COUNTRY_ISO_MAP
self.job_title = job_title
self.location = location
self._session = requests.Session()
def __repr__(self) -> str:
return f"{ScrapBayt}"
def get_data(self, save: bool = False) -> DataFrame:
job_ids, soups = list(), list()
page = 1
# Get job ids from all pages #
while True:
url = self.__get_url(page)
time.sleep(self.SLEEP)
soup = self.__extract(url)
logger.info(f'Created a soup for page: {page}')
latest_job_ids = self.__get_jobs_id(soup)
logger.info(f'Found {len(latest_job_ids)} jobs for page => {page}')
if job_ids: # stop iteration after pagination is complete.
if job_ids[-1] == latest_job_ids:
break
job_ids.append(latest_job_ids)
page += 1
total_jobs = sum([len(jobs) for jobs in job_ids])
logger.info(f'Total jobs found: {total_jobs}')
logger.info(f'Total job ids: {job_ids}')
# Extract all jobs #
# Exit if no joubs were found
if not job_ids[0]:
logging.warning(f'No matching jobs were found!')
sys.exit(0)
cnt = 0
urls = list()
for page in range(0, len(job_ids)):
cnt += 1
page += 1
for job_id in job_ids[page]:
url = f"{self.__get_url(page)}&jobId={job_id}"
logger.info(f'Making API request for job url => {url}')
urls.append(url)
time.sleep(self.SLEEP)
soups.append(self.__extract(url))
logger.info(
f'Completed extraction of {cnt} out of {total_jobs} jobs')
print(f'Extracted job {cnt} out of {total_jobs}')
cnt += 1
# Transform #
data = self.__transform(soups, links=urls)
# Load #
return self.__load(data)
def __get_url(self, page: int, /) -> str:
# indeed specific for dealing with white space in job title
if len(self.job_title.split()) > 1:
self.job_title = self.job_title.split(
)[0] + "-" + self.job_title.split()[1]
return f"https://www.bayt.com/en/{self.COUNTRY_ISO_MAP[self.location]}/jobs/{self.job_title}-jobs/?page={page}"
@functools.lru_cache
def __extract(self, url: str) -> BeautifulSoup:
return BeautifulSoup(self._session.get(url, headers=self.HEADERS).text, 'html.parser')
def __get_jobs_id(self, soup: BeautifulSoup, /) -> List[int]:
return [element.get('data-job-id') for element in soup.find('div', {'id': 'results_inner_card', 'class': 'card-content'}).find_all('li', {"data-job-id": True})]
def __transform(self, data: List[BeautifulSoup], /, *, links: List[str]) -> List[NamedTuple]:
Parsed = namedtuple(
'Parsed', 'title company_name description post_date link')
jobs_parsed = list()
for i, job in enumerate(data):
try:
p = Parsed(title=job.h2.text, company_name=job.find('a', class_='is-black').text,
description=job.find(
class_="card-content t-small bt p20").text.strip(),
post_date='-'.join(
job.find('span', class_='p20l-d p10y-m u-block-m').text.strip().split()[-2:]),
link=links[i])
except:
logger.error(
f'Failed to transform and bypassed for job: {i+1}')
else:
jobs_parsed.append(p)
logger.info(
f'Transformation successfully done for job => {i+1}')
return jobs_parsed
def __load(self, data: List[NamedTuple], /, *, save: bool = True) -> DataFrame:
try:
data =
|
DataFrame.from_records(data, columns=data[0]._fields)
|
pandas.DataFrame.from_records
|
""" Module for sleep periods from accelerometer """
import datetime
import numpy as np
import pandas as pd
import LAMP
from ..feature_types import primary_feature, log
from ..raw.accelerometer import accelerometer
@primary_feature(
name="cortex.feature.sleep_periods",
dependencies=[accelerometer]
)
def sleep_periods(attach=True,
**kwargs):
"""
Generate sleep periods with given data
Args:
attach (boolean):
**kwargs:
id (string): The participant's LAMP id. Required.
start (int): The initial UNIX timestamp (in ms) of the window for which the feature
is being generated. Required.
end (int): The last UNIX timestamp (in ms) of the window for which the feature
is being generated. Required.
Returns:
"""
def _expected_sleep_period(accelerometer_data_reduced):
"""
Return the expected sleep period for a set of accelerometer data
:param accelerometer_data (list)
:return _sleep_period_expted (dict): list bed/wake timestamps and mean
accel. magnitude for expected bedtime
"""
df = pd.DataFrame.from_dict(accelerometer_data_reduced)
# If we have data, we filter to remove duplicates here
if 'timestamp' in df.columns:
df = df[df['timestamp'] != df['timestamp'].shift()]
# Creating possible times for expected sleep period, which will be checked
times = [(datetime.time(hour=h, minute=m), (datetime.datetime.combine(datetime.date.today(), datetime.time(hour=h, minute=m)) + datetime.timedelta(hours=8, minutes=0)).time()) for h in range(18, 24) for m in [0, 30] ] + [(datetime.time(hour=h, minute=m), (datetime.datetime.combine(datetime.date.today(), datetime.time(hour=h, minute=m)) + datetime.timedelta(hours=8, minutes=0)).time()) for h in range(0, 4) for m in [0, 30]]
mean_activity = float('inf')
for t0, t1 in times:
if datetime.time(hour=18, minute=0) <= t0 <= datetime.time(hour=23, minute=30):
selection = pd.concat([df.loc[t0 <= df.time, :], df.loc[df.time <= t1, :]])
else:
selection = df.loc[(t0 <= df.time) & (df.time <= t1), :]
if len(selection) == 0 or selection['count'].sum() == 0:
continue
nonnan_ind = np.where(np.logical_not(np.isnan(selection['magnitude'])))[0]
nonnan_sel = selection.iloc[nonnan_ind]
sel_act = np.average(nonnan_sel['magnitude'], weights=nonnan_sel['count'])
if sel_act < mean_activity:
mean_activity = sel_act
_sleep_period_expected = {'bed': t0, 'wake': t1, 'accelerometer_magnitude': sel_act}
if mean_activity == float('inf'):
_sleep_period_expected = {'bed': None, 'wake': None, 'accelerometer_magnitude': None}
return _sleep_period_expected
# Data reduction
try:
reduced_data = LAMP.Type.get_attachment(kwargs['id'],
'cortex.sleep_periods.reduced')['data']
for i, x in enumerate(reduced_data['data']):
reduced_data['data'][i]['time'] = datetime.time(x['time']['hour'],
x['time']['minute'])
log.info("Using saved reduced data...")
except Exception:
reduced_data = {'end':0, 'data':[]}
log.info("No saved reduced data found, starting new...")
reduced_data_end = reduced_data['end']
if reduced_data_end < kwargs['end']: # update reduced data
# Accel binning
_accelerometer = accelerometer(**{**kwargs, 'start': reduced_data_end})['data']
if len(_accelerometer) > 0:
reduce_df = pd.DataFrame.from_dict(_accelerometer)
reduce_df.loc[:, 'Time'] = pd.to_datetime(reduce_df['timestamp'], unit='ms')
reduce_df.loc[:, 'magnitude'] = reduce_df.apply(lambda row: np.linalg.norm([row['x'],
row['y'],
row['z']]),
axis=1)
# Get mean accel readings of 10min bins for participant
new_reduced_data = []
for s, t in reduce_df.groupby(pd.Grouper(key='Time', freq='10min')):
res_10min = {'time': s.time(), 'magnitude': t['magnitude'].abs().mean(),
'count': len(t)}
# Update new reduced data
found = False
for accel_bin in reduced_data['data']:
if accel_bin['time'] == res_10min['time']:
accel_bin['magnitude'] = np.mean([accel_bin['magnitude']]
* accel_bin['count'] +
[res_10min['magnitude']]
* res_10min['count'])
accel_bin['count'] = accel_bin['count'] + res_10min['count']
new_reduced_data.append(accel_bin)
found = True
break
if not found: # if time not found, initialize it
new_reduced_data.append(res_10min)
# convert to time dicts for saving
save_reduced_data = []
for x in new_reduced_data:
if x['magnitude'] and x['count']:
save_reduced_data.append({'time': {'hour': x['time'].hour,
'minute': x['time'].minute},
'magnitude': x['magnitude'],
'count': x['count']})
reduced_data = {'end': kwargs['end'], 'data': new_reduced_data}
# set attachment
LAMP.Type.set_attachment(kwargs['id'], 'me',
attachment_key='cortex.sleep_periods.reduced',
body={'end': int(kwargs['end']),
'data': save_reduced_data})
log.info("Saving reduced data...")
accelerometer_data = accelerometer(**kwargs)['data']
if len(accelerometer_data) == 0:
return {'data': [], 'has_raw_data': 0}
# Calculate sleep periods
_sleep_period_expected = _expected_sleep_period(reduced_data['data'])
if _sleep_period_expected['bed'] is None:
return {'data': [], 'has_raw_data': 1}
accel_df = pd.DataFrame.from_dict(accelerometer_data)
accel_df = accel_df[accel_df['timestamp'] != accel_df['timestamp'].shift()]
accel_df.loc[:, 'Time'] = pd.to_datetime(accel_df['timestamp'], unit='ms')
accel_df.loc[:, 'magnitude'] = accel_df.apply(lambda row: np.linalg.norm([row['x'],
row['y'],
row['z']]),
axis=1)
# Get mean accel readings of 10min bins for participant
df10min = pd.DataFrame.from_dict(reduced_data['data']).sort_values(by='time')
bed_time, wake_time = _sleep_period_expected['bed'], _sleep_period_expected['wake']
# Calculate sleep
sleep_start, sleep_start_flex = bed_time, (datetime.datetime.combine(datetime.date.today(),
bed_time) - datetime.timedelta(hours=2)).time()
sleep_end, sleep_end_flex = wake_time, (datetime.datetime.combine(datetime.date.today(),
wake_time) + datetime.timedelta(hours=2)).time()
# We need to shift times so that the day begins a midnight
# (and thus is on the same day) sleep start flex begins on
accel_df.loc[:, "Shifted Time"] = pd.to_datetime(accel_df['Time']) - \
(datetime.datetime.combine(datetime.date.min, sleep_end_flex) - datetime.datetime.min)
accel_df.loc[:, "Shifted Day"] =
|
pd.to_datetime(accel_df['Shifted Time'])
|
pandas.to_datetime
|
import os
from collections import Counter
from flask import Flask, request, redirect, url_for, send_from_directory,render_template
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import io
import base64
from pylab import rcParams
from sklearn.externals import joblib
from sklearn.preprocessing import LabelEncoder
UPLOAD_FOLDER = 'flask-upload-test'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif','csv'])
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
data_file = 'flask-upload-test/data.csv'
df = pd.read_csv(data_file)
enc_df = pd.read_csv(data_file)
label_encoder = LabelEncoder()
cat_columns = df.dtypes.pipe(lambda x: x[x == 'object']).index
for col in cat_columns:
df[col] = label_encoder.fit_transform(df[col])
loaded_model = joblib.load('pickle_model.pkl')
result = loaded_model.predict(df)
pred_series = pd.Series(result.tolist())
pred_series = pred_series.rename('Predicated Value')
final_df = enc_df.merge(pred_series.to_frame(), left_index=True, right_index=True)
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
@app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
# check if the post request has the file part
if 'file' not in request.files:
print ('no file')
return redirect(request.url)
file = request.files['file']
# if user does not select file, browser also
# submit a empty part without filename
if file.filename == '':
print ('no filename')
return redirect(request.url)
if file and allowed_file(file.filename):
filename = "data.csv" # secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return redirect(url_for('uploaded_file', filename=filename))
return render_template("index.html")
@app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'],
filename)
@app.route('/show', methods=['GET'])
def show_df():
data_file = 'flask-upload-test/data.csv'
df = pd.read_csv(data_file)
to_html = "<!doctype html><title>Show DF</title>"+df.to_html()
return to_html
@app.route('/html', methods=['GET'])
def html():
global my_list
return '''
<!doctype html>
<title>HTML</title>
<h1>CSS</h1>
<p>
dfsifgdsifds
</p>
'''
@app.route('/plot', methods=['GET'])
def plot():
data_file = 'flask-upload-test/data.csv'
df = pd.read_csv(data_file)
img = io.BytesIO()
a, x = plt.subplots(figsize=(16, 10))
sns.countplot(x="Topic", data=df, palette="muted")
plt.title('Correlation between different features', y=1.03, size=18)
plt.savefig(img, format='png')
img.seek(0)
plot_url_count = base64.b64encode(img.getvalue()).decode()
return render_template("plot.html",plot_url_count = plot_url_count)
@app.route('/abs', methods=['Get'])
def plot_count():
img = io.BytesIO()
sns.countplot(x='StudentAbsenceDays', data=final_df, hue='Predicated Value', palette='dark')
plt.savefig(img, format='png')
img.seek(0) # rewind to beginning of file
plot_url = base64.b64encode(img.getvalue()).decode()
return render_template("plot.html") #render_template("plot.html",plot_url = plot_url)
@app.route('/encode', methods=['GET'])
def encode():
data_file = 'flask-upload-test/data.csv'
df = pd.read_csv(data_file)
label_encoder = LabelEncoder()
cat_columns = df.dtypes.pipe(lambda x: x[x == 'object']).index
for col in cat_columns:
df[col] = label_encoder.fit_transform(df[col])
to_html_predict = "<!doctype html><title>Show Encoded DataFrame Values </title>" + df.to_html()
return to_html_predict
@app.route('/predict', methods=['GET'])
def predict():
data_file = 'flask-upload-test/data.csv'
df = pd.read_csv(data_file)
enc_df = pd.read_csv(data_file)
label_encoder = LabelEncoder()
cat_columns = df.dtypes.pipe(lambda x: x[x == 'object']).index
for col in cat_columns:
df[col] = label_encoder.fit_transform(df[col])
loaded_model = joblib.load('pickle_model.pkl')
result = loaded_model.predict(df)
pred_series = pd.Series(result.tolist())
pred_series = pred_series.rename('Predicated Value')
final_df = enc_df.merge(pred_series.to_frame(), left_index=True, right_index=True)
letter_counts = Counter(result)
df = pd.DataFrame.from_dict(letter_counts, orient='index')
ax = df.plot(kind='bar', color=tuple(["g", "b", "r"]), legend=False,figsize=(15,8))
patches, labels = ax.get_legend_handles_labels()
ax.legend(patches, labels, loc='best')
img = io.BytesIO()
plt.savefig(img, format='png')
img.seek(0)
plot_url = base64.b64encode(img.getvalue()).decode()
return '<h1> if you to see all the dataset with the predicted values press here </h1> <a href="/predictDF"> <input type="button" value="Predict"></a> <p> </p><img src="data:image/png;base64,{}">'.format(plot_url)
@app.route('/predictDF', methods=['GET'])
def predict_df():
data_file = 'flask-upload-test/data.csv'
df =
|
pd.read_csv(data_file)
|
pandas.read_csv
|
from datetime import datetime
from decimal import Decimal
from io import StringIO
import numpy as np
import pytest
from pandas.errors import PerformanceWarning
import pandas as pd
from pandas import DataFrame, Index, MultiIndex, Series, Timestamp, date_range, read_csv
import pandas._testing as tm
from pandas.core.base import SpecificationError
import pandas.core.common as com
def test_repr():
# GH18203
result = repr(pd.Grouper(key="A", level="B"))
expected = "Grouper(key='A', level='B', axis=0, sort=False)"
assert result == expected
@pytest.mark.parametrize("dtype", ["int64", "int32", "float64", "float32"])
def test_basic(dtype):
data = Series(np.arange(9) // 3, index=np.arange(9), dtype=dtype)
index = np.arange(9)
np.random.shuffle(index)
data = data.reindex(index)
grouped = data.groupby(lambda x: x // 3)
for k, v in grouped:
assert len(v) == 3
agged = grouped.aggregate(np.mean)
assert agged[1] == 1
tm.assert_series_equal(agged, grouped.agg(np.mean)) # shorthand
tm.assert_series_equal(agged, grouped.mean())
tm.assert_series_equal(grouped.agg(np.sum), grouped.sum())
expected = grouped.apply(lambda x: x * x.sum())
transformed = grouped.transform(lambda x: x * x.sum())
assert transformed[7] == 12
tm.assert_series_equal(transformed, expected)
value_grouped = data.groupby(data)
tm.assert_series_equal(
value_grouped.aggregate(np.mean), agged, check_index_type=False
)
# complex agg
agged = grouped.aggregate([np.mean, np.std])
msg = r"nested renamer is not supported"
with pytest.raises(SpecificationError, match=msg):
grouped.aggregate({"one": np.mean, "two": np.std})
group_constants = {0: 10, 1: 20, 2: 30}
agged = grouped.agg(lambda x: group_constants[x.name] + x.mean())
assert agged[1] == 21
# corner cases
msg = "Must produce aggregated value"
# exception raised is type Exception
with pytest.raises(Exception, match=msg):
grouped.aggregate(lambda x: x * 2)
def test_groupby_nonobject_dtype(mframe, df_mixed_floats):
key = mframe.index.codes[0]
grouped = mframe.groupby(key)
result = grouped.sum()
expected = mframe.groupby(key.astype("O")).sum()
tm.assert_frame_equal(result, expected)
# GH 3911, mixed frame non-conversion
df = df_mixed_floats.copy()
df["value"] = range(len(df))
def max_value(group):
return group.loc[group["value"].idxmax()]
applied = df.groupby("A").apply(max_value)
result = applied.dtypes
expected = Series(
[np.dtype("object")] * 2 + [np.dtype("float64")] * 2 + [np.dtype("int64")],
index=["A", "B", "C", "D", "value"],
)
tm.assert_series_equal(result, expected)
def test_groupby_return_type():
# GH2893, return a reduced type
df1 = DataFrame(
[
{"val1": 1, "val2": 20},
{"val1": 1, "val2": 19},
{"val1": 2, "val2": 27},
{"val1": 2, "val2": 12},
]
)
def func(dataf):
return dataf["val2"] - dataf["val2"].mean()
with tm.assert_produces_warning(FutureWarning):
result = df1.groupby("val1", squeeze=True).apply(func)
assert isinstance(result, Series)
df2 = DataFrame(
[
{"val1": 1, "val2": 20},
{"val1": 1, "val2": 19},
{"val1": 1, "val2": 27},
{"val1": 1, "val2": 12},
]
)
def func(dataf):
return dataf["val2"] - dataf["val2"].mean()
with tm.assert_produces_warning(FutureWarning):
result = df2.groupby("val1", squeeze=True).apply(func)
assert isinstance(result, Series)
# GH3596, return a consistent type (regression in 0.11 from 0.10.1)
df = DataFrame([[1, 1], [1, 1]], columns=["X", "Y"])
with tm.assert_produces_warning(FutureWarning):
result = df.groupby("X", squeeze=False).count()
assert isinstance(result, DataFrame)
def test_inconsistent_return_type():
# GH5592
# inconsistent return type
df = DataFrame(
dict(
A=["Tiger", "Tiger", "Tiger", "Lamb", "Lamb", "Pony", "Pony"],
B=Series(np.arange(7), dtype="int64"),
C=date_range("20130101", periods=7),
)
)
def f(grp):
return grp.iloc[0]
expected = df.groupby("A").first()[["B"]]
result = df.groupby("A").apply(f)[["B"]]
tm.assert_frame_equal(result, expected)
def f(grp):
if grp.name == "Tiger":
return None
return grp.iloc[0]
result = df.groupby("A").apply(f)[["B"]]
e = expected.copy()
e.loc["Tiger"] = np.nan
tm.assert_frame_equal(result, e)
def f(grp):
if grp.name == "Pony":
return None
return grp.iloc[0]
result = df.groupby("A").apply(f)[["B"]]
e = expected.copy()
e.loc["Pony"] = np.nan
tm.assert_frame_equal(result, e)
# 5592 revisited, with datetimes
def f(grp):
if grp.name == "Pony":
return None
return grp.iloc[0]
result = df.groupby("A").apply(f)[["C"]]
e = df.groupby("A").first()[["C"]]
e.loc["Pony"] = pd.NaT
tm.assert_frame_equal(result, e)
# scalar outputs
def f(grp):
if grp.name == "Pony":
return None
return grp.iloc[0].loc["C"]
result = df.groupby("A").apply(f)
e = df.groupby("A").first()["C"].copy()
e.loc["Pony"] = np.nan
e.name = None
tm.assert_series_equal(result, e)
def test_pass_args_kwargs(ts, tsframe):
def f(x, q=None, axis=0):
return np.percentile(x, q, axis=axis)
g = lambda x: np.percentile(x, 80, axis=0)
# Series
ts_grouped = ts.groupby(lambda x: x.month)
agg_result = ts_grouped.agg(np.percentile, 80, axis=0)
apply_result = ts_grouped.apply(np.percentile, 80, axis=0)
trans_result = ts_grouped.transform(np.percentile, 80, axis=0)
agg_expected = ts_grouped.quantile(0.8)
trans_expected = ts_grouped.transform(g)
tm.assert_series_equal(apply_result, agg_expected)
tm.assert_series_equal(agg_result, agg_expected)
tm.assert_series_equal(trans_result, trans_expected)
agg_result = ts_grouped.agg(f, q=80)
apply_result = ts_grouped.apply(f, q=80)
trans_result = ts_grouped.transform(f, q=80)
tm.assert_series_equal(agg_result, agg_expected)
tm.assert_series_equal(apply_result, agg_expected)
tm.assert_series_equal(trans_result, trans_expected)
# DataFrame
df_grouped = tsframe.groupby(lambda x: x.month)
agg_result = df_grouped.agg(np.percentile, 80, axis=0)
apply_result = df_grouped.apply(DataFrame.quantile, 0.8)
expected = df_grouped.quantile(0.8)
tm.assert_frame_equal(apply_result, expected, check_names=False)
tm.assert_frame_equal(agg_result, expected)
agg_result = df_grouped.agg(f, q=80)
apply_result = df_grouped.apply(DataFrame.quantile, q=0.8)
tm.assert_frame_equal(agg_result, expected)
tm.assert_frame_equal(apply_result, expected, check_names=False)
def test_len():
df = tm.makeTimeDataFrame()
grouped = df.groupby([lambda x: x.year, lambda x: x.month, lambda x: x.day])
assert len(grouped) == len(df)
grouped = df.groupby([lambda x: x.year, lambda x: x.month])
expected = len({(x.year, x.month) for x in df.index})
assert len(grouped) == expected
# issue 11016
df = pd.DataFrame(dict(a=[np.nan] * 3, b=[1, 2, 3]))
assert len(df.groupby(("a"))) == 0
assert len(df.groupby(("b"))) == 3
assert len(df.groupby(["a", "b"])) == 3
def test_basic_regression():
# regression
result = Series([1.0 * x for x in list(range(1, 10)) * 10])
data = np.random.random(1100) * 10.0
groupings = Series(data)
grouped = result.groupby(groupings)
grouped.mean()
@pytest.mark.parametrize(
"dtype", ["float64", "float32", "int64", "int32", "int16", "int8"]
)
def test_with_na_groups(dtype):
index = Index(np.arange(10))
values = Series(np.ones(10), index, dtype=dtype)
labels = Series(
[np.nan, "foo", "bar", "bar", np.nan, np.nan, "bar", "bar", np.nan, "foo"],
index=index,
)
# this SHOULD be an int
grouped = values.groupby(labels)
agged = grouped.agg(len)
expected = Series([4, 2], index=["bar", "foo"])
tm.assert_series_equal(agged, expected, check_dtype=False)
# assert issubclass(agged.dtype.type, np.integer)
# explicitly return a float from my function
def f(x):
return float(len(x))
agged = grouped.agg(f)
expected = Series([4, 2], index=["bar", "foo"])
tm.assert_series_equal(agged, expected, check_dtype=False)
assert issubclass(agged.dtype.type, np.dtype(dtype).type)
def test_indices_concatenation_order():
# GH 2808
def f1(x):
y = x[(x.b % 2) == 1] ** 2
if y.empty:
multiindex = MultiIndex(levels=[[]] * 2, codes=[[]] * 2, names=["b", "c"])
res = DataFrame(columns=["a"], index=multiindex)
return res
else:
y = y.set_index(["b", "c"])
return y
def f2(x):
y = x[(x.b % 2) == 1] ** 2
if y.empty:
return DataFrame()
else:
y = y.set_index(["b", "c"])
return y
def f3(x):
y = x[(x.b % 2) == 1] ** 2
if y.empty:
multiindex = MultiIndex(
levels=[[]] * 2, codes=[[]] * 2, names=["foo", "bar"]
)
res = DataFrame(columns=["a", "b"], index=multiindex)
return res
else:
return y
df = DataFrame({"a": [1, 2, 2, 2], "b": range(4), "c": range(5, 9)})
df2 = DataFrame({"a": [3, 2, 2, 2], "b": range(4), "c": range(5, 9)})
# correct result
result1 = df.groupby("a").apply(f1)
result2 = df2.groupby("a").apply(f1)
tm.assert_frame_equal(result1, result2)
# should fail (not the same number of levels)
msg = "Cannot concat indices that do not have the same number of levels"
with pytest.raises(AssertionError, match=msg):
df.groupby("a").apply(f2)
with pytest.raises(AssertionError, match=msg):
df2.groupby("a").apply(f2)
# should fail (incorrect shape)
with pytest.raises(AssertionError, match=msg):
df.groupby("a").apply(f3)
with pytest.raises(AssertionError, match=msg):
df2.groupby("a").apply(f3)
def test_attr_wrapper(ts):
grouped = ts.groupby(lambda x: x.weekday())
result = grouped.std()
expected = grouped.agg(lambda x: np.std(x, ddof=1))
tm.assert_series_equal(result, expected)
# this is pretty cool
result = grouped.describe()
expected = {name: gp.describe() for name, gp in grouped}
expected = DataFrame(expected).T
tm.assert_frame_equal(result, expected)
# get attribute
result = grouped.dtype
expected = grouped.agg(lambda x: x.dtype)
# make sure raises error
msg = "'SeriesGroupBy' object has no attribute 'foo'"
with pytest.raises(AttributeError, match=msg):
getattr(grouped, "foo")
def test_frame_groupby(tsframe):
grouped = tsframe.groupby(lambda x: x.weekday())
# aggregate
aggregated = grouped.aggregate(np.mean)
assert len(aggregated) == 5
assert len(aggregated.columns) == 4
# by string
tscopy = tsframe.copy()
tscopy["weekday"] = [x.weekday() for x in tscopy.index]
stragged = tscopy.groupby("weekday").aggregate(np.mean)
tm.assert_frame_equal(stragged, aggregated, check_names=False)
# transform
grouped = tsframe.head(30).groupby(lambda x: x.weekday())
transformed = grouped.transform(lambda x: x - x.mean())
assert len(transformed) == 30
assert len(transformed.columns) == 4
# transform propagate
transformed = grouped.transform(lambda x: x.mean())
for name, group in grouped:
mean = group.mean()
for idx in group.index:
tm.assert_series_equal(transformed.xs(idx), mean, check_names=False)
# iterate
for weekday, group in grouped:
assert group.index[0].weekday() == weekday
# groups / group_indices
groups = grouped.groups
indices = grouped.indices
for k, v in groups.items():
samething = tsframe.index.take(indices[k])
assert (samething == v).all()
def test_frame_groupby_columns(tsframe):
mapping = {"A": 0, "B": 0, "C": 1, "D": 1}
grouped = tsframe.groupby(mapping, axis=1)
# aggregate
aggregated = grouped.aggregate(np.mean)
assert len(aggregated) == len(tsframe)
assert len(aggregated.columns) == 2
# transform
tf = lambda x: x - x.mean()
groupedT = tsframe.T.groupby(mapping, axis=0)
tm.assert_frame_equal(groupedT.transform(tf).T, grouped.transform(tf))
# iterate
for k, v in grouped:
assert len(v.columns) == 2
def test_frame_set_name_single(df):
grouped = df.groupby("A")
result = grouped.mean()
assert result.index.name == "A"
result = df.groupby("A", as_index=False).mean()
assert result.index.name != "A"
result = grouped.agg(np.mean)
assert result.index.name == "A"
result = grouped.agg({"C": np.mean, "D": np.std})
assert result.index.name == "A"
result = grouped["C"].mean()
assert result.index.name == "A"
result = grouped["C"].agg(np.mean)
assert result.index.name == "A"
result = grouped["C"].agg([np.mean, np.std])
assert result.index.name == "A"
msg = r"nested renamer is not supported"
with pytest.raises(SpecificationError, match=msg):
grouped["C"].agg({"foo": np.mean, "bar": np.std})
def test_multi_func(df):
col1 = df["A"]
col2 = df["B"]
grouped = df.groupby([col1.get, col2.get])
agged = grouped.mean()
expected = df.groupby(["A", "B"]).mean()
# TODO groupby get drops names
tm.assert_frame_equal(
agged.loc[:, ["C", "D"]], expected.loc[:, ["C", "D"]], check_names=False
)
# some "groups" with no data
df = DataFrame(
{
"v1": np.random.randn(6),
"v2": np.random.randn(6),
"k1": np.array(["b", "b", "b", "a", "a", "a"]),
"k2": np.array(["1", "1", "1", "2", "2", "2"]),
},
index=["one", "two", "three", "four", "five", "six"],
)
# only verify that it works for now
grouped = df.groupby(["k1", "k2"])
grouped.agg(np.sum)
def test_multi_key_multiple_functions(df):
grouped = df.groupby(["A", "B"])["C"]
agged = grouped.agg([np.mean, np.std])
expected = DataFrame({"mean": grouped.agg(np.mean), "std": grouped.agg(np.std)})
tm.assert_frame_equal(agged, expected)
def test_frame_multi_key_function_list():
data = DataFrame(
{
"A": [
"foo",
"foo",
"foo",
"foo",
"bar",
"bar",
"bar",
"bar",
"foo",
"foo",
"foo",
],
"B": [
"one",
"one",
"one",
"two",
"one",
"one",
"one",
"two",
"two",
"two",
"one",
],
"C": [
"dull",
"dull",
"shiny",
"dull",
"dull",
"shiny",
"shiny",
"dull",
"shiny",
"shiny",
"shiny",
],
"D": np.random.randn(11),
"E": np.random.randn(11),
"F": np.random.randn(11),
}
)
grouped = data.groupby(["A", "B"])
funcs = [np.mean, np.std]
agged = grouped.agg(funcs)
expected = pd.concat(
[grouped["D"].agg(funcs), grouped["E"].agg(funcs), grouped["F"].agg(funcs)],
keys=["D", "E", "F"],
axis=1,
)
assert isinstance(agged.index, MultiIndex)
assert isinstance(expected.index, MultiIndex)
tm.assert_frame_equal(agged, expected)
@pytest.mark.parametrize("op", [lambda x: x.sum(), lambda x: x.mean()])
def test_groupby_multiple_columns(df, op):
data = df
grouped = data.groupby(["A", "B"])
result1 = op(grouped)
keys = []
values = []
for n1, gp1 in data.groupby("A"):
for n2, gp2 in gp1.groupby("B"):
keys.append((n1, n2))
values.append(op(gp2.loc[:, ["C", "D"]]))
mi = MultiIndex.from_tuples(keys, names=["A", "B"])
expected = pd.concat(values, axis=1).T
expected.index = mi
# a little bit crude
for col in ["C", "D"]:
result_col = op(grouped[col])
pivoted = result1[col]
exp = expected[col]
tm.assert_series_equal(result_col, exp)
tm.assert_series_equal(pivoted, exp)
# test single series works the same
result = data["C"].groupby([data["A"], data["B"]]).mean()
expected = data.groupby(["A", "B"]).mean()["C"]
tm.assert_series_equal(result, expected)
def test_as_index_select_column():
# GH 5764
df = pd.DataFrame([[1, 2], [1, 4], [5, 6]], columns=["A", "B"])
result = df.groupby("A", as_index=False)["B"].get_group(1)
expected = pd.Series([2, 4], name="B")
tm.assert_series_equal(result, expected)
result = df.groupby("A", as_index=False)["B"].apply(lambda x: x.cumsum())
expected = pd.Series(
[2, 6, 6], name="B", index=pd.MultiIndex.from_tuples([(0, 0), (0, 1), (1, 2)])
)
tm.assert_series_equal(result, expected)
def test_groupby_as_index_select_column_sum_empty_df():
# GH 35246
df = DataFrame(columns=["A", "B", "C"])
left = df.groupby(by="A", as_index=False)["B"].sum()
assert type(left) is DataFrame
assert left.to_dict() == {"A": {}, "B": {}}
def test_groupby_as_index_agg(df):
grouped = df.groupby("A", as_index=False)
# single-key
result = grouped.agg(np.mean)
expected = grouped.mean()
tm.assert_frame_equal(result, expected)
result2 = grouped.agg({"C": np.mean, "D": np.sum})
expected2 = grouped.mean()
expected2["D"] = grouped.sum()["D"]
tm.assert_frame_equal(result2, expected2)
grouped = df.groupby("A", as_index=True)
msg = r"nested renamer is not supported"
with pytest.raises(SpecificationError, match=msg):
grouped["C"].agg({"Q": np.sum})
# multi-key
grouped = df.groupby(["A", "B"], as_index=False)
result = grouped.agg(np.mean)
expected = grouped.mean()
tm.assert_frame_equal(result, expected)
result2 = grouped.agg({"C": np.mean, "D": np.sum})
expected2 = grouped.mean()
expected2["D"] = grouped.sum()["D"]
tm.assert_frame_equal(result2, expected2)
expected3 = grouped["C"].sum()
expected3 = DataFrame(expected3).rename(columns={"C": "Q"})
result3 = grouped["C"].agg({"Q": np.sum})
tm.assert_frame_equal(result3, expected3)
# GH7115 & GH8112 & GH8582
df = DataFrame(np.random.randint(0, 100, (50, 3)), columns=["jim", "joe", "jolie"])
ts = Series(np.random.randint(5, 10, 50), name="jim")
gr = df.groupby(ts)
gr.nth(0) # invokes set_selection_from_grouper internally
tm.assert_frame_equal(gr.apply(sum), df.groupby(ts).apply(sum))
for attr in ["mean", "max", "count", "idxmax", "cumsum", "all"]:
gr = df.groupby(ts, as_index=False)
left = getattr(gr, attr)()
gr = df.groupby(ts.values, as_index=True)
right = getattr(gr, attr)().reset_index(drop=True)
tm.assert_frame_equal(left, right)
def test_ops_not_as_index(reduction_func):
# GH 10355, 21090
# Using as_index=False should not modify grouped column
if reduction_func in ("corrwith",):
pytest.skip("Test not applicable")
if reduction_func in ("nth", "ngroup",):
pytest.skip("Skip until behavior is determined (GH #5755)")
df = DataFrame(np.random.randint(0, 5, size=(100, 2)), columns=["a", "b"])
expected = getattr(df.groupby("a"), reduction_func)()
if reduction_func == "size":
expected = expected.rename("size")
expected = expected.reset_index()
g = df.groupby("a", as_index=False)
result = getattr(g, reduction_func)()
tm.assert_frame_equal(result, expected)
result = g.agg(reduction_func)
tm.assert_frame_equal(result, expected)
result = getattr(g["b"], reduction_func)()
tm.assert_frame_equal(result, expected)
result = g["b"].agg(reduction_func)
tm.assert_frame_equal(result, expected)
def test_as_index_series_return_frame(df):
grouped = df.groupby("A", as_index=False)
grouped2 = df.groupby(["A", "B"], as_index=False)
result = grouped["C"].agg(np.sum)
expected = grouped.agg(np.sum).loc[:, ["A", "C"]]
assert isinstance(result, DataFrame)
tm.assert_frame_equal(result, expected)
result2 = grouped2["C"].agg(np.sum)
expected2 = grouped2.agg(np.sum).loc[:, ["A", "B", "C"]]
assert isinstance(result2, DataFrame)
tm.assert_frame_equal(result2, expected2)
result = grouped["C"].sum()
expected = grouped.sum().loc[:, ["A", "C"]]
assert isinstance(result, DataFrame)
tm.assert_frame_equal(result, expected)
result2 = grouped2["C"].sum()
expected2 = grouped2.sum().loc[:, ["A", "B", "C"]]
assert isinstance(result2, DataFrame)
tm.assert_frame_equal(result2, expected2)
def test_as_index_series_column_slice_raises(df):
# GH15072
grouped = df.groupby("A", as_index=False)
msg = r"Column\(s\) C already selected"
with pytest.raises(IndexError, match=msg):
grouped["C"].__getitem__("D")
def test_groupby_as_index_cython(df):
data = df
# single-key
grouped = data.groupby("A", as_index=False)
result = grouped.mean()
expected = data.groupby(["A"]).mean()
expected.insert(0, "A", expected.index)
expected.index = np.arange(len(expected))
tm.assert_frame_equal(result, expected)
# multi-key
grouped = data.groupby(["A", "B"], as_index=False)
result = grouped.mean()
expected = data.groupby(["A", "B"]).mean()
arrays = list(zip(*expected.index.values))
expected.insert(0, "A", arrays[0])
expected.insert(1, "B", arrays[1])
expected.index = np.arange(len(expected))
tm.assert_frame_equal(result, expected)
def test_groupby_as_index_series_scalar(df):
grouped = df.groupby(["A", "B"], as_index=False)
# GH #421
result = grouped["C"].agg(len)
expected = grouped.agg(len).loc[:, ["A", "B", "C"]]
tm.assert_frame_equal(result, expected)
def test_groupby_as_index_corner(df, ts):
msg = "as_index=False only valid with DataFrame"
with pytest.raises(TypeError, match=msg):
ts.groupby(lambda x: x.weekday(), as_index=False)
msg = "as_index=False only valid for axis=0"
with pytest.raises(ValueError, match=msg):
df.groupby(lambda x: x.lower(), as_index=False, axis=1)
def test_groupby_multiple_key(df):
df = tm.makeTimeDataFrame()
grouped = df.groupby([lambda x: x.year, lambda x: x.month, lambda x: x.day])
agged = grouped.sum()
tm.assert_almost_equal(df.values, agged.values)
grouped = df.T.groupby(
[lambda x: x.year, lambda x: x.month, lambda x: x.day], axis=1
)
agged = grouped.agg(lambda x: x.sum())
tm.assert_index_equal(agged.index, df.columns)
tm.assert_almost_equal(df.T.values, agged.values)
agged = grouped.agg(lambda x: x.sum())
tm.assert_almost_equal(df.T.values, agged.values)
def test_groupby_multi_corner(df):
# test that having an all-NA column doesn't mess you up
df = df.copy()
df["bad"] = np.nan
agged = df.groupby(["A", "B"]).mean()
expected = df.groupby(["A", "B"]).mean()
expected["bad"] = np.nan
tm.assert_frame_equal(agged, expected)
def test_omit_nuisance(df):
grouped = df.groupby("A")
result = grouped.mean()
expected = df.loc[:, ["A", "C", "D"]].groupby("A").mean()
tm.assert_frame_equal(result, expected)
agged = grouped.agg(np.mean)
exp = grouped.mean()
tm.assert_frame_equal(agged, exp)
df = df.loc[:, ["A", "C", "D"]]
df["E"] = datetime.now()
grouped = df.groupby("A")
result = grouped.agg(np.sum)
expected = grouped.sum()
tm.assert_frame_equal(result, expected)
# won't work with axis = 1
grouped = df.groupby({"A": 0, "C": 0, "D": 1, "E": 1}, axis=1)
msg = "reduction operation 'sum' not allowed for this dtype"
with pytest.raises(TypeError, match=msg):
grouped.agg(lambda x: x.sum(0, numeric_only=False))
def test_omit_nuisance_python_multiple(three_group):
grouped = three_group.groupby(["A", "B"])
agged = grouped.agg(np.mean)
exp = grouped.mean()
tm.assert_frame_equal(agged, exp)
def test_empty_groups_corner(mframe):
# handle empty groups
df = DataFrame(
{
"k1": np.array(["b", "b", "b", "a", "a", "a"]),
"k2": np.array(["1", "1", "1", "2", "2", "2"]),
"k3": ["foo", "bar"] * 3,
"v1": np.random.randn(6),
"v2": np.random.randn(6),
}
)
grouped = df.groupby(["k1", "k2"])
result = grouped.agg(np.mean)
expected = grouped.mean()
tm.assert_frame_equal(result, expected)
grouped = mframe[3:5].groupby(level=0)
agged = grouped.apply(lambda x: x.mean())
agged_A = grouped["A"].apply(np.mean)
tm.assert_series_equal(agged["A"], agged_A)
assert agged.index.name == "first"
def test_nonsense_func():
df = DataFrame([0])
msg = r"unsupported operand type\(s\) for \+: 'int' and 'str'"
with pytest.raises(TypeError, match=msg):
df.groupby(lambda x: x + "foo")
def test_wrap_aggregated_output_multindex(mframe):
df = mframe.T
df["baz", "two"] = "peekaboo"
keys = [np.array([0, 0, 1]), np.array([0, 0, 1])]
agged = df.groupby(keys).agg(np.mean)
assert isinstance(agged.columns, MultiIndex)
def aggfun(ser):
if ser.name == ("foo", "one"):
raise TypeError
else:
return ser.sum()
agged2 = df.groupby(keys).aggregate(aggfun)
assert len(agged2.columns) + 1 == len(df.columns)
def test_groupby_level_apply(mframe):
result = mframe.groupby(level=0).count()
assert result.index.name == "first"
result = mframe.groupby(level=1).count()
assert result.index.name == "second"
result = mframe["A"].groupby(level=0).count()
assert result.index.name == "first"
def test_groupby_level_mapper(mframe):
deleveled = mframe.reset_index()
mapper0 = {"foo": 0, "bar": 0, "baz": 1, "qux": 1}
mapper1 = {"one": 0, "two": 0, "three": 1}
result0 = mframe.groupby(mapper0, level=0).sum()
result1 = mframe.groupby(mapper1, level=1).sum()
mapped_level0 = np.array([mapper0.get(x) for x in deleveled["first"]])
mapped_level1 = np.array([mapper1.get(x) for x in deleveled["second"]])
expected0 = mframe.groupby(mapped_level0).sum()
expected1 = mframe.groupby(mapped_level1).sum()
expected0.index.name, expected1.index.name = "first", "second"
tm.assert_frame_equal(result0, expected0)
tm.assert_frame_equal(result1, expected1)
def test_groupby_level_nonmulti():
# GH 1313, GH 13901
s = Series([1, 2, 3, 10, 4, 5, 20, 6], Index([1, 2, 3, 1, 4, 5, 2, 6], name="foo"))
expected = Series([11, 22, 3, 4, 5, 6], Index(range(1, 7), name="foo"))
result = s.groupby(level=0).sum()
tm.assert_series_equal(result, expected)
result = s.groupby(level=[0]).sum()
tm.assert_series_equal(result, expected)
result = s.groupby(level=-1).sum()
tm.assert_series_equal(result, expected)
result = s.groupby(level=[-1]).sum()
tm.assert_series_equal(result, expected)
msg = "level > 0 or level < -1 only valid with MultiIndex"
with pytest.raises(ValueError, match=msg):
s.groupby(level=1)
with pytest.raises(ValueError, match=msg):
s.groupby(level=-2)
msg = "No group keys passed!"
with pytest.raises(ValueError, match=msg):
s.groupby(level=[])
msg = "multiple levels only valid with MultiIndex"
with pytest.raises(ValueError, match=msg):
s.groupby(level=[0, 0])
with pytest.raises(ValueError, match=msg):
s.groupby(level=[0, 1])
msg = "level > 0 or level < -1 only valid with MultiIndex"
with pytest.raises(ValueError, match=msg):
s.groupby(level=[1])
def test_groupby_complex():
# GH 12902
a = Series(data=np.arange(4) * (1 + 2j), index=[0, 0, 1, 1])
expected = Series((1 + 2j, 5 + 10j))
result = a.groupby(level=0).sum()
tm.assert_series_equal(result, expected)
result = a.sum(level=0)
tm.assert_series_equal(result, expected)
def test_groupby_series_indexed_differently():
s1 = Series(
[5.0, -9.0, 4.0, 100.0, -5.0, 55.0, 6.7],
index=Index(["a", "b", "c", "d", "e", "f", "g"]),
)
s2 = Series(
[1.0, 1.0, 4.0, 5.0, 5.0, 7.0], index=Index(["a", "b", "d", "f", "g", "h"])
)
grouped = s1.groupby(s2)
agged = grouped.mean()
exp = s1.groupby(s2.reindex(s1.index).get).mean()
tm.assert_series_equal(agged, exp)
def test_groupby_with_hier_columns():
tuples = list(
zip(
*[
["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"],
["one", "two", "one", "two", "one", "two", "one", "two"],
]
)
)
index = MultiIndex.from_tuples(tuples)
columns = MultiIndex.from_tuples(
[("A", "cat"), ("B", "dog"), ("B", "cat"), ("A", "dog")]
)
df = DataFrame(np.random.randn(8, 4), index=index, columns=columns)
result = df.groupby(level=0).mean()
tm.assert_index_equal(result.columns, columns)
result = df.groupby(level=0, axis=1).mean()
tm.assert_index_equal(result.index, df.index)
result = df.groupby(level=0).agg(np.mean)
tm.assert_index_equal(result.columns, columns)
result = df.groupby(level=0).apply(lambda x: x.mean())
tm.assert_index_equal(result.columns, columns)
result = df.groupby(level=0, axis=1).agg(lambda x: x.mean(1))
tm.assert_index_equal(result.columns, Index(["A", "B"]))
tm.assert_index_equal(result.index, df.index)
# add a nuisance column
sorted_columns, _ = columns.sortlevel(0)
df["A", "foo"] = "bar"
result = df.groupby(level=0).mean()
tm.assert_index_equal(result.columns, df.columns[:-1])
def test_grouping_ndarray(df):
grouped = df.groupby(df["A"].values)
result = grouped.sum()
expected = df.groupby("A").sum()
tm.assert_frame_equal(
result, expected, check_names=False
) # Note: no names when grouping by value
def test_groupby_wrong_multi_labels():
data = """index,foo,bar,baz,spam,data
0,foo1,bar1,baz1,spam2,20
1,foo1,bar2,baz1,spam3,30
2,foo2,bar2,baz1,spam2,40
3,foo1,bar1,baz2,spam1,50
4,foo3,bar1,baz2,spam1,60"""
data = read_csv(StringIO(data), index_col=0)
grouped = data.groupby(["foo", "bar", "baz", "spam"])
result = grouped.agg(np.mean)
expected = grouped.mean()
tm.assert_frame_equal(result, expected)
def test_groupby_series_with_name(df):
result = df.groupby(df["A"]).mean()
result2 = df.groupby(df["A"], as_index=False).mean()
assert result.index.name == "A"
assert "A" in result2
result = df.groupby([df["A"], df["B"]]).mean()
result2 = df.groupby([df["A"], df["B"]], as_index=False).mean()
assert result.index.names == ("A", "B")
assert "A" in result2
assert "B" in result2
def test_seriesgroupby_name_attr(df):
# GH 6265
result = df.groupby("A")["C"]
assert result.count().name == "C"
assert result.mean().name == "C"
testFunc = lambda x: np.sum(x) * 2
assert result.agg(testFunc).name == "C"
def test_consistency_name():
# GH 12363
df = DataFrame(
{
"A": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "foo"],
"B": ["one", "one", "two", "two", "two", "two", "one", "two"],
"C": np.random.randn(8) + 1.0,
"D": np.arange(8),
}
)
expected = df.groupby(["A"]).B.count()
result = df.B.groupby(df.A).count()
tm.assert_series_equal(result, expected)
def test_groupby_name_propagation(df):
# GH 6124
def summarize(df, name=None):
return Series({"count": 1, "mean": 2, "omissions": 3}, name=name)
def summarize_random_name(df):
# Provide a different name for each Series. In this case, groupby
# should not attempt to propagate the Series name since they are
# inconsistent.
return Series({"count": 1, "mean": 2, "omissions": 3}, name=df.iloc[0]["A"])
metrics = df.groupby("A").apply(summarize)
assert metrics.columns.name is None
metrics = df.groupby("A").apply(summarize, "metrics")
assert metrics.columns.name == "metrics"
metrics = df.groupby("A").apply(summarize_random_name)
assert metrics.columns.name is None
def test_groupby_nonstring_columns():
df = DataFrame([np.arange(10) for x in range(10)])
grouped = df.groupby(0)
result = grouped.mean()
expected = df.groupby(df[0]).mean()
tm.assert_frame_equal(result, expected)
def test_groupby_mixed_type_columns():
# GH 13432, unorderable types in py3
df = DataFrame([[0, 1, 2]], columns=["A", "B", 0])
expected = DataFrame([[1, 2]], columns=["B", 0], index=Index([0], name="A"))
result = df.groupby("A").first()
tm.assert_frame_equal(result, expected)
result = df.groupby("A").sum()
tm.assert_frame_equal(result, expected)
# TODO: Ensure warning isn't emitted in the first place
@pytest.mark.filterwarnings("ignore:Mean of:RuntimeWarning")
def test_cython_grouper_series_bug_noncontig():
arr = np.empty((100, 100))
arr.fill(np.nan)
obj = Series(arr[:, 0])
inds = np.tile(range(10), 10)
result = obj.groupby(inds).agg(Series.median)
assert result.isna().all()
def test_series_grouper_noncontig_index():
index = Index(tm.rands_array(10, 100))
values = Series(np.random.randn(50), index=index[::2])
labels = np.random.randint(0, 5, 50)
# it works!
grouped = values.groupby(labels)
# accessing the index elements causes segfault
f = lambda x: len(set(map(id, x.index)))
grouped.agg(f)
def test_convert_objects_leave_decimal_alone():
s = Series(range(5))
labels = np.array(["a", "b", "c", "d", "e"], dtype="O")
def convert_fast(x):
return Decimal(str(x.mean()))
def convert_force_pure(x):
# base will be length 0
assert len(x.values.base) > 0
return Decimal(str(x.mean()))
grouped = s.groupby(labels)
result = grouped.agg(convert_fast)
assert result.dtype == np.object_
assert isinstance(result[0], Decimal)
result = grouped.agg(convert_force_pure)
assert result.dtype == np.object_
assert isinstance(result[0], Decimal)
def test_groupby_dtype_inference_empty():
# GH 6733
df = DataFrame({"x": [], "range": np.arange(0, dtype="int64")})
assert df["x"].dtype == np.float64
result = df.groupby("x").first()
exp_index = Index([], name="x", dtype=np.float64)
expected = DataFrame({"range": Series([], index=exp_index, dtype="int64")})
tm.assert_frame_equal(result, expected, by_blocks=True)
def test_groupby_list_infer_array_like(df):
result = df.groupby(list(df["A"])).mean()
expected = df.groupby(df["A"]).mean()
tm.assert_frame_equal(result, expected, check_names=False)
with pytest.raises(KeyError, match=r"^'foo'$"):
df.groupby(list(df["A"][:-1]))
# pathological case of ambiguity
df = DataFrame({"foo": [0, 1], "bar": [3, 4], "val": np.random.randn(2)})
result = df.groupby(["foo", "bar"]).mean()
expected = df.groupby([df["foo"], df["bar"]]).mean()[["val"]]
def test_groupby_keys_same_size_as_index():
# GH 11185
freq = "s"
index = pd.date_range(
start=pd.Timestamp("2015-09-29T11:34:44-0700"), periods=2, freq=freq
)
df = pd.DataFrame([["A", 10], ["B", 15]], columns=["metric", "values"], index=index)
result = df.groupby([pd.Grouper(level=0, freq=freq), "metric"]).mean()
expected = df.set_index([df.index, "metric"])
tm.assert_frame_equal(result, expected)
def test_groupby_one_row():
# GH 11741
msg = r"^'Z'$"
df1 = pd.DataFrame(np.random.randn(1, 4), columns=list("ABCD"))
with pytest.raises(KeyError, match=msg):
df1.groupby("Z")
df2 = pd.DataFrame(np.random.randn(2, 4), columns=list("ABCD"))
with pytest.raises(KeyError, match=msg):
df2.groupby("Z")
def test_groupby_nat_exclude():
# GH 6992
df = pd.DataFrame(
{
"values": np.random.randn(8),
"dt": [
np.nan,
pd.Timestamp("2013-01-01"),
np.nan,
pd.Timestamp("2013-02-01"),
np.nan,
pd.Timestamp("2013-02-01"),
np.nan,
pd.Timestamp("2013-01-01"),
],
"str": [np.nan, "a", np.nan, "a", np.nan, "a", np.nan, "b"],
}
)
grouped = df.groupby("dt")
expected = [pd.Index([1, 7]), pd.Index([3, 5])]
keys = sorted(grouped.groups.keys())
assert len(keys) == 2
for k, e in zip(keys, expected):
# grouped.groups keys are np.datetime64 with system tz
# not to be affected by tz, only compare values
tm.assert_index_equal(grouped.groups[k], e)
# confirm obj is not filtered
tm.assert_frame_equal(grouped.grouper.groupings[0].obj, df)
assert grouped.ngroups == 2
expected = {
Timestamp("2013-01-01 00:00:00"): np.array([1, 7], dtype=np.intp),
Timestamp("2013-02-01 00:00:00"): np.array([3, 5], dtype=np.intp),
}
for k in grouped.indices:
tm.assert_numpy_array_equal(grouped.indices[k], expected[k])
tm.assert_frame_equal(grouped.get_group(Timestamp("2013-01-01")), df.iloc[[1, 7]])
tm.assert_frame_equal(grouped.get_group(Timestamp("2013-02-01")), df.iloc[[3, 5]])
with pytest.raises(KeyError, match=r"^NaT$"):
grouped.get_group(pd.NaT)
nan_df = DataFrame(
{"nan": [np.nan, np.nan, np.nan], "nat": [pd.NaT, pd.NaT, pd.NaT]}
)
assert nan_df["nan"].dtype == "float64"
assert nan_df["nat"].dtype == "datetime64[ns]"
for key in ["nan", "nat"]:
grouped = nan_df.groupby(key)
assert grouped.groups == {}
assert grouped.ngroups == 0
assert grouped.indices == {}
with pytest.raises(KeyError, match=r"^nan$"):
grouped.get_group(np.nan)
with pytest.raises(KeyError, match=r"^NaT$"):
grouped.get_group(pd.NaT)
def test_groupby_2d_malformed():
d = DataFrame(index=range(2))
d["group"] = ["g1", "g2"]
d["zeros"] = [0, 0]
d["ones"] = [1, 1]
d["label"] = ["l1", "l2"]
tmp = d.groupby(["group"]).mean()
res_values = np.array([[0, 1], [0, 1]], dtype=np.int64)
tm.assert_index_equal(tmp.columns, Index(["zeros", "ones"]))
tm.assert_numpy_array_equal(tmp.values, res_values)
def test_int32_overflow():
B = np.concatenate((np.arange(10000), np.arange(10000), np.arange(5000)))
A = np.arange(25000)
df = DataFrame({"A": A, "B": B, "C": A, "D": B, "E": np.random.randn(25000)})
left = df.groupby(["A", "B", "C", "D"]).sum()
right = df.groupby(["D", "C", "B", "A"]).sum()
assert len(left) == len(right)
def test_groupby_sort_multi():
df = DataFrame(
{
"a": ["foo", "bar", "baz"],
"b": [3, 2, 1],
"c": [0, 1, 2],
"d": np.random.randn(3),
}
)
tups = [tuple(row) for row in df[["a", "b", "c"]].values]
tups = com.asarray_tuplesafe(tups)
result = df.groupby(["a", "b", "c"], sort=True).sum()
tm.assert_numpy_array_equal(result.index.values, tups[[1, 2, 0]])
tups = [tuple(row) for row in df[["c", "a", "b"]].values]
tups = com.asarray_tuplesafe(tups)
result = df.groupby(["c", "a", "b"], sort=True).sum()
tm.assert_numpy_array_equal(result.index.values, tups)
tups = [tuple(x) for x in df[["b", "c", "a"]].values]
tups = com.asarray_tuplesafe(tups)
result = df.groupby(["b", "c", "a"], sort=True).sum()
tm.assert_numpy_array_equal(result.index.values, tups[[2, 1, 0]])
df = DataFrame(
{"a": [0, 1, 2, 0, 1, 2], "b": [0, 0, 0, 1, 1, 1], "d": np.random.randn(6)}
)
grouped = df.groupby(["a", "b"])["d"]
result = grouped.sum()
def _check_groupby(df, result, keys, field, f=lambda x: x.sum()):
tups = [tuple(row) for row in df[keys].values]
tups = com.asarray_tuplesafe(tups)
expected = f(df.groupby(tups)[field])
for k, v in expected.items():
assert result[k] == v
_check_groupby(df, result, ["a", "b"], "d")
def test_dont_clobber_name_column():
df = DataFrame(
{"key": ["a", "a", "a", "b", "b", "b"], "name": ["foo", "bar", "baz"] * 2}
)
result = df.groupby("key").apply(lambda x: x)
tm.assert_frame_equal(result, df)
def test_skip_group_keys():
tsf = tm.makeTimeDataFrame()
grouped = tsf.groupby(lambda x: x.month, group_keys=False)
result = grouped.apply(lambda x: x.sort_values(by="A")[:3])
pieces = [group.sort_values(by="A")[:3] for key, group in grouped]
expected = pd.concat(pieces)
tm.assert_frame_equal(result, expected)
grouped = tsf["A"].groupby(lambda x: x.month, group_keys=False)
result = grouped.apply(lambda x: x.sort_values()[:3])
pieces = [group.sort_values()[:3] for key, group in grouped]
expected = pd.concat(pieces)
tm.assert_series_equal(result, expected)
def test_no_nonsense_name(float_frame):
# GH #995
s = float_frame["C"].copy()
s.name = None
result = s.groupby(float_frame["A"]).agg(np.sum)
assert result.name is None
def test_multifunc_sum_bug():
# GH #1065
x = DataFrame(np.arange(9).reshape(3, 3))
x["test"] = 0
x["fl"] = [1.3, 1.5, 1.6]
grouped = x.groupby("test")
result = grouped.agg({"fl": "sum", 2: "size"})
assert result["fl"].dtype == np.float64
def test_handle_dict_return_value(df):
def f(group):
return {"max": group.max(), "min": group.min()}
def g(group):
return Series({"max": group.max(), "min": group.min()})
result = df.groupby("A")["C"].apply(f)
expected = df.groupby("A")["C"].apply(g)
assert isinstance(result, Series)
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("grouper", ["A", ["A", "B"]])
def test_set_group_name(df, grouper):
def f(group):
assert group.name is not None
return group
def freduce(group):
assert group.name is not None
return group.sum()
def foo(x):
return freduce(x)
grouped = df.groupby(grouper)
# make sure all these work
grouped.apply(f)
grouped.aggregate(freduce)
grouped.aggregate({"C": freduce, "D": freduce})
grouped.transform(f)
grouped["C"].apply(f)
grouped["C"].aggregate(freduce)
grouped["C"].aggregate([freduce, foo])
grouped["C"].transform(f)
def test_group_name_available_in_inference_pass():
# gh-15062
df = pd.DataFrame({"a": [0, 0, 1, 1, 2, 2], "b": np.arange(6)})
names = []
def f(group):
names.append(group.name)
return group.copy()
df.groupby("a", sort=False, group_keys=False).apply(f)
expected_names = [0, 1, 2]
assert names == expected_names
def test_no_dummy_key_names(df):
# see gh-1291
result = df.groupby(df["A"].values).sum()
assert result.index.name is None
result = df.groupby([df["A"].values, df["B"].values]).sum()
assert result.index.names == (None, None)
def test_groupby_sort_multiindex_series():
# series multiindex groupby sort argument was not being passed through
# _compress_group_index
# GH 9444
index = MultiIndex(
levels=[[1, 2], [1, 2]],
codes=[[0, 0, 0, 0, 1, 1], [1, 1, 0, 0, 0, 0]],
names=["a", "b"],
)
mseries = Series([0, 1, 2, 3, 4, 5], index=index)
index = MultiIndex(
levels=[[1, 2], [1, 2]], codes=[[0, 0, 1], [1, 0, 0]], names=["a", "b"]
)
mseries_result = Series([0, 2, 4], index=index)
result = mseries.groupby(level=["a", "b"], sort=False).first()
tm.assert_series_equal(result, mseries_result)
result = mseries.groupby(level=["a", "b"], sort=True).first()
tm.assert_series_equal(result, mseries_result.sort_index())
def test_groupby_reindex_inside_function():
periods = 1000
ind = date_range(start="2012/1/1", freq="5min", periods=periods)
df = DataFrame({"high": np.arange(periods), "low": np.arange(periods)}, index=ind)
def agg_before(hour, func, fix=False):
"""
Run an aggregate func on the subset of data.
"""
def _func(data):
d = data.loc[data.index.map(lambda x: x.hour < 11)].dropna()
if fix:
data[data.index[0]]
if len(d) == 0:
return None
return func(d)
return _func
def afunc(data):
d = data.select(lambda x: x.hour < 11).dropna()
return np.max(d)
grouped = df.groupby(lambda x: datetime(x.year, x.month, x.day))
closure_bad = grouped.agg({"high": agg_before(11, np.max)})
closure_good = grouped.agg({"high": agg_before(11, np.max, True)})
tm.assert_frame_equal(closure_bad, closure_good)
def test_groupby_multiindex_missing_pair():
# GH9049
df = DataFrame(
{
"group1": ["a", "a", "a", "b"],
"group2": ["c", "c", "d", "c"],
"value": [1, 1, 1, 5],
}
)
df = df.set_index(["group1", "group2"])
df_grouped = df.groupby(level=["group1", "group2"], sort=True)
res = df_grouped.agg("sum")
idx = MultiIndex.from_tuples(
[("a", "c"), ("a", "d"), ("b", "c")], names=["group1", "group2"]
)
exp = DataFrame([[2], [1], [5]], index=idx, columns=["value"])
tm.assert_frame_equal(res, exp)
def test_groupby_multiindex_not_lexsorted():
# GH 11640
# define the lexsorted version
lexsorted_mi = MultiIndex.from_tuples(
[("a", ""), ("b1", "c1"), ("b2", "c2")], names=["b", "c"]
)
lexsorted_df = DataFrame([[1, 3, 4]], columns=lexsorted_mi)
assert lexsorted_df.columns.is_lexsorted()
# define the non-lexsorted version
not_lexsorted_df = DataFrame(
columns=["a", "b", "c", "d"], data=[[1, "b1", "c1", 3], [1, "b2", "c2", 4]]
)
not_lexsorted_df = not_lexsorted_df.pivot_table(
index="a", columns=["b", "c"], values="d"
)
not_lexsorted_df = not_lexsorted_df.reset_index()
assert not not_lexsorted_df.columns.is_lexsorted()
# compare the results
tm.assert_frame_equal(lexsorted_df, not_lexsorted_df)
expected = lexsorted_df.groupby("a").mean()
with tm.assert_produces_warning(PerformanceWarning):
result = not_lexsorted_df.groupby("a").mean()
tm.assert_frame_equal(expected, result)
# a transforming function should work regardless of sort
# GH 14776
df = DataFrame(
{"x": ["a", "a", "b", "a"], "y": [1, 1, 2, 2], "z": [1, 2, 3, 4]}
).set_index(["x", "y"])
assert not df.index.is_lexsorted()
for level in [0, 1, [0, 1]]:
for sort in [False, True]:
result = df.groupby(level=level, sort=sort).apply(DataFrame.drop_duplicates)
expected = df
tm.assert_frame_equal(expected, result)
result = (
df.sort_index()
.groupby(level=level, sort=sort)
.apply(DataFrame.drop_duplicates)
)
expected = df.sort_index()
tm.assert_frame_equal(expected, result)
def test_index_label_overlaps_location():
# checking we don't have any label/location confusion in the
# the wake of GH5375
df = DataFrame(list("ABCDE"), index=[2, 0, 2, 1, 1])
g = df.groupby(list("ababb"))
actual = g.filter(lambda x: len(x) > 2)
expected = df.iloc[[1, 3, 4]]
tm.assert_frame_equal(actual, expected)
ser = df[0]
g = ser.groupby(list("ababb"))
actual = g.filter(lambda x: len(x) > 2)
expected = ser.take([1, 3, 4])
tm.assert_series_equal(actual, expected)
# ... and again, with a generic Index of floats
df.index = df.index.astype(float)
g = df.groupby(list("ababb"))
actual = g.filter(lambda x: len(x) > 2)
expected = df.iloc[[1, 3, 4]]
tm.assert_frame_equal(actual, expected)
ser = df[0]
g = ser.groupby(list("ababb"))
actual = g.filter(lambda x: len(x) > 2)
expected = ser.take([1, 3, 4])
tm.assert_series_equal(actual, expected)
def test_transform_doesnt_clobber_ints():
# GH 7972
n = 6
x = np.arange(n)
df = DataFrame({"a": x // 2, "b": 2.0 * x, "c": 3.0 * x})
df2 = DataFrame({"a": x // 2 * 1.0, "b": 2.0 * x, "c": 3.0 * x})
gb = df.groupby("a")
result = gb.transform("mean")
gb2 = df2.groupby("a")
expected = gb2.transform("mean")
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize(
"sort_column",
["ints", "floats", "strings", ["ints", "floats"], ["ints", "strings"]],
)
@pytest.mark.parametrize(
"group_column", ["int_groups", "string_groups", ["int_groups", "string_groups"]]
)
def test_groupby_preserves_sort(sort_column, group_column):
# Test to ensure that groupby always preserves sort order of original
# object. Issue #8588 and #9651
df = DataFrame(
{
"int_groups": [3, 1, 0, 1, 0, 3, 3, 3],
"string_groups": ["z", "a", "z", "a", "a", "g", "g", "g"],
"ints": [8, 7, 4, 5, 2, 9, 1, 1],
"floats": [2.3, 5.3, 6.2, -2.4, 2.2, 1.1, 1.1, 5],
"strings": ["z", "d", "a", "e", "word", "word2", "42", "47"],
}
)
# Try sorting on different types and with different group types
df = df.sort_values(by=sort_column)
g = df.groupby(group_column)
def test_sort(x):
tm.assert_frame_equal(x, x.sort_values(by=sort_column))
g.apply(test_sort)
def test_group_shift_with_null_key():
# This test is designed to replicate the segfault in issue #13813.
n_rows = 1200
# Generate a moderately large dataframe with occasional missing
# values in column `B`, and then group by [`A`, `B`]. This should
# force `-1` in `labels` array of `g.grouper.group_info` exactly
# at those places, where the group-by key is partially missing.
df = DataFrame(
[(i % 12, i % 3 if i % 3 else np.nan, i) for i in range(n_rows)],
dtype=float,
columns=["A", "B", "Z"],
index=None,
)
g = df.groupby(["A", "B"])
expected = DataFrame(
[(i + 12 if i % 3 and i < n_rows - 12 else np.nan) for i in range(n_rows)],
dtype=float,
columns=["Z"],
index=None,
)
result = g.shift(-1)
tm.assert_frame_equal(result, expected)
def test_group_shift_with_fill_value():
# GH #24128
n_rows = 24
df = DataFrame(
[(i % 12, i % 3, i) for i in range(n_rows)],
dtype=float,
columns=["A", "B", "Z"],
index=None,
)
g = df.groupby(["A", "B"])
expected = DataFrame(
[(i + 12 if i < n_rows - 12 else 0) for i in range(n_rows)],
dtype=float,
columns=["Z"],
index=None,
)
result = g.shift(-1, fill_value=0)[["Z"]]
tm.assert_frame_equal(result, expected)
def test_group_shift_lose_timezone():
# GH 30134
now_dt = pd.Timestamp.utcnow()
df = DataFrame({"a": [1, 1], "date": now_dt})
result = df.groupby("a").shift(0).iloc[0]
expected = Series({"date": now_dt}, name=result.name)
tm.assert_series_equal(result, expected)
def test_pivot_table_values_key_error():
# This test is designed to replicate the error in issue #14938
df = pd.DataFrame(
{
"eventDate": pd.date_range(datetime.today(), periods=20, freq="M").tolist(),
"thename": range(0, 20),
}
)
df["year"] = df.set_index("eventDate").index.year
df["month"] = df.set_index("eventDate").index.month
with pytest.raises(KeyError, match="'badname'"):
df.reset_index().pivot_table(
index="year", columns="month", values="badname", aggfunc="count"
)
def test_empty_dataframe_groupby():
# GH8093
df = DataFrame(columns=["A", "B", "C"])
result = df.groupby("A").sum()
expected = DataFrame(columns=["B", "C"], dtype=np.float64)
expected.index.name = "A"
tm.assert_frame_equal(result, expected)
def test_tuple_as_grouping():
# https://github.com/pandas-dev/pandas/issues/18314
df = pd.DataFrame(
{
("a", "b"): [1, 1, 1, 1],
"a": [2, 2, 2, 2],
"b": [2, 2, 2, 2],
"c": [1, 1, 1, 1],
}
)
with pytest.raises(KeyError, match=r"('a', 'b')"):
df[["a", "b", "c"]].groupby(("a", "b"))
result = df.groupby(("a", "b"))["c"].sum()
expected = pd.Series([4], name="c", index=pd.Index([1], name=("a", "b")))
tm.assert_series_equal(result, expected)
def test_tuple_correct_keyerror():
# https://github.com/pandas-dev/pandas/issues/18798
df = pd.DataFrame(
1, index=range(3), columns=pd.MultiIndex.from_product([[1, 2], [3, 4]])
)
with pytest.raises(KeyError, match=r"^\(7, 8\)$"):
df.groupby((7, 8)).mean()
def test_groupby_agg_ohlc_non_first():
# GH 21716
df = pd.DataFrame(
[[1], [1]],
columns=["foo"],
index=pd.date_range("2018-01-01", periods=2, freq="D"),
)
expected = pd.DataFrame(
[[1, 1, 1, 1, 1], [1, 1, 1, 1, 1]],
columns=pd.MultiIndex.from_tuples(
(
("foo", "sum", "foo"),
("foo", "ohlc", "open"),
("foo", "ohlc", "high"),
("foo", "ohlc", "low"),
("foo", "ohlc", "close"),
)
),
index=pd.date_range("2018-01-01", periods=2, freq="D"),
)
result = df.groupby(pd.Grouper(freq="D")).agg(["sum", "ohlc"])
tm.assert_frame_equal(result, expected)
def test_groupby_multiindex_nat():
# GH 9236
values = [
(pd.NaT, "a"),
(datetime(2012, 1, 2), "a"),
(datetime(2012, 1, 2), "b"),
(datetime(2012, 1, 3), "a"),
]
mi = pd.MultiIndex.from_tuples(values, names=["date", None])
ser = pd.Series([3, 2, 2.5, 4], index=mi)
result = ser.groupby(level=1).mean()
expected = pd.Series([3.0, 2.5], index=["a", "b"])
tm.assert_series_equal(result, expected)
def test_groupby_empty_list_raises():
# GH 5289
values = zip(range(10), range(10))
df = DataFrame(values, columns=["apple", "b"])
msg = "Grouper and axis must be same length"
with pytest.raises(ValueError, match=msg):
df.groupby([[]])
def test_groupby_multiindex_series_keys_len_equal_group_axis():
# GH 25704
index_array = [["x", "x"], ["a", "b"], ["k", "k"]]
index_names = ["first", "second", "third"]
ri = pd.MultiIndex.from_arrays(index_array, names=index_names)
s = pd.Series(data=[1, 2], index=ri)
result = s.groupby(["first", "third"]).sum()
index_array = [["x"], ["k"]]
index_names = ["first", "third"]
ei = pd.MultiIndex.from_arrays(index_array, names=index_names)
expected = pd.Series([3], index=ei)
tm.assert_series_equal(result, expected)
def test_groupby_groups_in_BaseGrouper():
# GH 26326
# Test if DataFrame grouped with a pandas.Grouper has correct groups
mi = pd.MultiIndex.from_product([["A", "B"], ["C", "D"]], names=["alpha", "beta"])
df = pd.DataFrame({"foo": [1, 2, 1, 2], "bar": [1, 2, 3, 4]}, index=mi)
result = df.groupby([pd.Grouper(level="alpha"), "beta"])
expected = df.groupby(["alpha", "beta"])
assert result.groups == expected.groups
result = df.groupby(["beta", pd.Grouper(level="alpha")])
expected = df.groupby(["beta", "alpha"])
assert result.groups == expected.groups
@pytest.mark.parametrize("group_name", ["x", ["x"]])
def test_groupby_axis_1(group_name):
# GH 27614
df = pd.DataFrame(
np.arange(12).reshape(3, 4), index=[0, 1, 0], columns=[10, 20, 10, 20]
)
df.index.name = "y"
df.columns.name = "x"
results = df.groupby(group_name, axis=1).sum()
expected = df.T.groupby(group_name).sum().T
tm.assert_frame_equal(results, expected)
# test on MI column
iterables = [["bar", "baz", "foo"], ["one", "two"]]
mi = pd.MultiIndex.from_product(iterables=iterables, names=["x", "x1"])
df = pd.DataFrame(np.arange(18).reshape(3, 6), index=[0, 1, 0], columns=mi)
results = df.groupby(group_name, axis=1).sum()
expected = df.T.groupby(group_name).sum().T
tm.assert_frame_equal(results, expected)
@pytest.mark.parametrize(
"op, expected",
[
(
"shift",
{
"time": [
None,
None,
Timestamp("2019-01-01 12:00:00"),
Timestamp("2019-01-01 12:30:00"),
None,
None,
]
},
),
(
"bfill",
{
"time": [
Timestamp("2019-01-01 12:00:00"),
Timestamp("2019-01-01 12:30:00"),
Timestamp("2019-01-01 14:00:00"),
Timestamp("2019-01-01 14:30:00"),
Timestamp("2019-01-01 14:00:00"),
Timestamp("2019-01-01 14:30:00"),
]
},
),
(
"ffill",
{
"time": [
|
Timestamp("2019-01-01 12:00:00")
|
pandas.Timestamp
|
from pyetltools import get_default_logger
from pyetltools.core.env_manager import get_env_manager
from pyetltools.tools.misc import RetryDecorator
from pyetltools.core.cache import CachedDecorator
import pandas as pd
import re
env = get_env_manager()
def get_databases_cached(db_con, force_reload_from_source=False, days_in_cache=999999):
cache_key = ("DB_DATABASES_CACHE_" + db_con.key + "_" + db_con.data_source)
@RetryDecorator(manual_retry=False, fail_on_error=False)
@CachedDecorator(cache_key=cache_key, force_reload_from_source=force_reload_from_source, days_in_cache=days_in_cache)
def get_databases(db_con):
df=db_con.get_databases()
return df
return get_databases(db_con)
def get_objects(db_con):
df=db_con.get_objects()
if df is None:
raise Exception("No objects found")
return df
@RetryDecorator(manual_retry=False, auto_retry=0, fail_on_error=False)
@CachedDecorator()
def get_objects_cached(db_con, **kwargs):
return get_objects(db_con)
def get_objects_for_multiple_dbs_cached(db_con, db_name_regex=".*", **kwargs):
ret=[]
dbs=[db for db in get_databases_cached(db_con, **kwargs) if re.match(db_name_regex, db)]
if len(dbs)==0:
get_default_logger().warn("No databases found.")
return None
for db in dbs:
df = get_objects_cached(db_con.with_data_source(db), **kwargs)
if df is None:
get_default_logger().warn("No objects found in "+db)
else:
df["DATABASE_NAME"]=db
ret.append(df)
if len(ret)==0:
get_default_logger().warn("No objects found")
return None
else:
return pd.concat(ret)
def get_objects_by_name_cached(db_con, object_name_regex=".*", db_name_regex=".*", **kwargs):
if db_name_regex:
df = get_objects_for_multiple_dbs_cached(db_con, db_name_regex, **kwargs)
else:
df= get_objects_cached(db_con, **kwargs)
if df is not None:
return df.query(f"NAME.str.upper()==('{object_name_regex.upper()}')")
def get_objects_by_name_regex_cached(db_con, object_name_regex, db_name_regex=".*", **kwargs):
df = get_objects_for_multiple_dbs_cached(db_con, db_name_regex, **kwargs)
if df is not None:
return df.query(f"NAME.str.upper().str.match('{object_name_regex.upper()}')")
# def get_objects(db_con, db_regex, force_reload_from_source=False):
# cache_key = ("DB_OBJECT_CACHE_"+db_con.key+"_"+db_con.data_source + "_" + db_regex)
# def get_objects():
# df=db_con.get_objects_for_databases([db for db in db_con.get_databases() if re.match(db_regex, db)])
# if df is None:
# print("No databases found for regex: "+db_regex)
# return df
#
# return get_cache().get_from_cache(cache_key, retriever=get_objects, force_reload_from_source= force_reload_from_source)
def get_columns(db_con):
df = db_con.get_columns_all_objects()
if df is None:
print("No columns found")
else:
df.columns = map(str.upper, df.columns)
return df
@RetryDecorator(manual_retry=False, fail_on_error=False)
@CachedDecorator()
def get_columns_cached(db_con, **kwargs):
return get_columns(db_con)
def get_columns_for_multiple_dbs_cached(db_con, db_name_regex=".*", **kwargs):
ret=[]
dbs=[db for db in get_databases_cached(db_con, **kwargs) if re.match(db_name_regex, db)]
if len(dbs)==0:
get_default_logger().warn("No databases found.")
return None
for db in dbs:
df = get_columns_cached(db_con.with_data_source(db), **kwargs)
if df is None:
get_default_logger().warn("No columns found in "+db)
else:
df["DATABASE_NAME"]=db
ret.append(df)
if len(ret)==0:
get_default_logger().warn("No columns found.")
return None
else:
return pd.concat(ret)
@CachedDecorator()
def get_columns_by_object_name_cached_multiple_dbs(db_con, object_name, db_name_regex=".*", **kwargs):
df= get_columns_for_multiple_dbs_cached(db_con, db_name_regex, **kwargs)
return df.query(f"TABLE_NAME.str.upper()== '{object_name.upper()}'").sort_values("ORDINAL_POSITION")
@CachedDecorator()
def get_columns_by_object_name_cached(db_con, object_name, **kwargs):
df= get_columns_cached(db_con, **kwargs)
return df.query(f"TABLE_NAME.str.upper()== '{object_name.upper()}'").sort_values("ORDINAL_POSITION")
def get_columns_by_object_name_regex_cached(db_con, object_name_regex, db_name_regex=".*", **kwargs):
df= get_columns_for_multiple_dbs_cached(db_con, db_name_regex, **kwargs)
return df.query(f"TABLE_NAME.str.upper().str.match('{object_name_regex.upper()}')").sort_values("ORDINAL_POSITION")
def get_tables_metadata(db_con, tables, input_columns=["TABLE_NAME_REGEX","DB_NAME_REGEX"], output_columns=["NAME","SCHEMA","DATABASE_NAME"]):
"""
Searches for metadata for tables, input tables data frame should contains fields: table_name_regex and DB_NAME_REGEX
Result of the search will be added to the input dataframe in columns: NAME, SCHEMA, DATABASE_NAME
"""
if any(col in tables.columns for col in output_columns):
raise Exception("Output column name already in data frame")
if len(output_columns)!=3:
raise Exception("output_columns parameters should contain 3 values: for name, schema and database name")
def add_db_meta(db_con):
def get_db_meta(df):
r=df.iloc[0]
db = r[df.columns.get_loc(input_columns[1])]
table_name = r[df.columns.get_loc(input_columns[0])]
get_default_logger().info("Getting table meta for: "+table_name + " db:" + db)
meta = db_con.get_objects_by_name_regex_cached(f"{table_name}", db)
if meta is None or len(meta) == 0:
print("Not found")
r[output_columns[0]] = None
r[output_columns[1]] = None
r[output_columns[2]] = None
return pd.DataFrame([r])
else:
if len(meta)>1:
print("Find multiple matches")
res=[]
for m in meta.itertuples():
r_cp=r.copy()
r_cp[output_columns[0]] = m.NAME
r_cp[output_columns[1]] = m.SCHEMA
r_cp[output_columns[2]] = m.DATABASE_NAME
res.append(r_cp)
return pd.DataFrame(res)
return get_db_meta
return tables.groupby(tables.columns.tolist(), group_keys=False).apply(add_db_meta(db_con))
def get_table_counts(db_con, tables, agg_queries=True):
# Parameters:
# db_con(DBConnector): database connector
# tables(list): list of tuples
# tuple fields:
# db schema table_name table_type condition group_by_fields
def escape_sql(s):
if s:
return s.replace("'", "''")
else:
return ""
sqls = []
ret=[]
if len(tables)==0:
ret= pd.DataFrame(columns=["DATABASE_NAME","SCHEMA","NAME","WHERE_COND","CNT"])
for r in tables.itertuples():
cond=None
if "CONDITION" in tables:
cond = r.CONDITION
group_by=None
if "GROUP_BY" in tables:
group_by=r.GROUP_BY
sql=f"""SELECT '{r.DATABASE_NAME}' DATABASE_NAME,
'{r.SCHEMA}' "SCHEMA",
'{r.NAME}' NAME,
'{escape_sql(cond)}' WHERE_COND
{(","+group_by) if group_by else ''},
count(*) CNT FROM {r.DATABASE_NAME}.{r.SCHEMA}.{r.NAME}
WHERE {cond if cond else '1=1'}
{(" GROUP BY "+group_by) if group_by else ''}"""
if not agg_queries:
ret.append(db_con.query_pandas(sql))
else:
sqls.append(sql)
if agg_queries:
sql = " UNION ALL \n".join(sqls)
ret=[db_con.query_pandas(sql)]
return
|
pd.concat(ret)
|
pandas.concat
|
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import pmagpy.pmag as pmag
import pmagpy.ipmag as ipmag
import pmagpy.pmagplotlib as pmagplotlib
def make_plot(arch_df,edited_df,sect_depths,hole,\
gad_inc,depth_min,depth_max,labels,spec_df=[], fignum=1,
agemin=0,agemax=0):
"""
Makes a downhole plot of IODP data.
Parameters
___________
arch_df : Pandas DataFrame
dataframe of SRM archive measurements
edited_df : Panas DataFrame
dataframe of edited SRM archive measurements
sect_depths : NumPy array
array containing section depths of sections for plotting
hole : str
name of hole
gad_inc : float
inclination expected at the site from a GAD field
depth_min : float
minimum depth for plot
depth_max : float
maximum depth for plot
labels : Pandas Series
series containing section names (e.g., 1H-2)
spec_df : Pandas DataFrame
dataframe of specimen data for plotting
agemin : float
if desired, minimum age for time scale plot
agemax : float
if non-zero an time scale plot will be generated
"""
arch_df=arch_df[arch_df['core_depth']>depth_min]
arch_df=arch_df[arch_df['core_depth']<=depth_max]
edited_df=edited_df[edited_df['core_depth']>depth_min]
edited_df=edited_df[edited_df['core_depth']<=depth_max]
if len(spec_df)>0:
spec_df=spec_df[spec_df['core_depth']>depth_min]
spec_df=spec_df[spec_df['core_depth']<=depth_max]
plot_spec=True
else: plot_spec=False
max_depth=arch_df.core_depth.max()
min_depth=arch_df.core_depth.min()
plot=1
if agemax:
col=5
fig=plt.figure(fignum,(14,16))
else:
col=3
fig=plt.figure(fignum,(8,20))
ax=plt.subplot(1,col,plot)
for d in sect_depths:
if d<max_depth and d>min_depth:
plt.axhline(d,color='black',linestyle='dashed',linewidth=.75)
plot+=1
plt.plot(np.log10(edited_df['magn_volume']*1e3),edited_df['core_depth'],\
'co',markeredgecolor='grey')
plt.plot(np.log10(arch_df['magn_volume']*1e3),arch_df['core_depth'],'k.',markersize=1)
plt.ylabel('Depth (mbsf)')
plt.xlabel('Log Intensity (mA/m)')
plt.ylim(depth_max,depth_min)
ax=plt.subplot(1,col,plot)
for d in sect_depths:
if d<max_depth and d>min_depth:
plt.axhline(d,color='black',linestyle='dashed',linewidth=.75)
plot+=1
plt.plot(edited_df['dir_dec'],edited_df['core_depth'],'co',markeredgecolor='grey')
plt.plot(arch_df['dir_dec'],arch_df['core_depth'],'k.',markersize=1)
if plot_spec:
plt.plot(spec_df['dir_dec'],spec_df['core_depth'],'r*',markersize=10)
plt.axvline(180,color='red')
plt.xlabel('Declination')
plt.ylim(depth_max,depth_min)
plt.ylim(depth_max,depth_min)
plt.title(hole)
ax=plt.subplot(1,col,plot)
for d in sect_depths:
if d<max_depth and d>min_depth:
plt.axhline(d,color='black',linestyle='dashed',linewidth=.75)
plot+=1
plt.plot(edited_df['dir_inc'],edited_df['core_depth'],'co',markeredgecolor='grey')
plt.plot(arch_df['dir_inc'],arch_df['core_depth'],'k.',markersize=1)
if plot_spec:
plt.plot(spec_df['dir_inc'],spec_df['core_depth'],'r*',markersize=10)
plt.xlabel('Inclination')
plt.axvline(gad_inc,color='blue',linestyle='dotted')
plt.axvline(-gad_inc,color='blue',linestyle='dotted')
plt.axvline(0,color='red')
plt.xlim(-90,90)
for k in range(len(labels.values)):
if sect_depths[k]<max_depth and sect_depths[k]>=min_depth:
plt.text(100,sect_depths[k],labels.values[k],verticalalignment='top')
plt.ylim(depth_max,depth_min);
if agemax:
ax=plt.subplot(1,col,plot)
ax.axis('off')
ax=plt.subplot(1,col,plot+1)
pmagplotlib.plot_ts(ax,agemin,agemax)
plt.savefig('Figures/'+hole+'_'+str(fignum)+'.pdf')
print ('Plot saved in', 'Figures/'+hole+'_'+str(fignum)+'.pdf')
def inc_hist(df,inc_key='dir_inc'):
"""
Makes a histogram of inclination data from a data frame with 'dir_inc' as the inclination key
Parameters
__________
df : Pandas DataFrame
dataframe with inclination data in "inc_key" column
"""
plt.figure(figsize=(12,5))
plt.subplot(121)
plt.ylabel('Number of inclinations')
sns.distplot(df[inc_key],kde=False,bins=24)
plt.xlabel('Inclination')
plt.xlim(-90,90)
plt.subplot(122)
plt.ylabel('Fraction of inclinations')
sns.distplot(df[inc_key],bins=24)
plt.xlabel('Inclination')
plt.xlim(-90,90)
def demag_step(magic_dir,hole,demag_step,meas_file='srm_arch_measurements.txt',
site_file='srm_arch_sites.txt',depth_key='core_depth',verbose=True):
"""
Selects the desired demagnetization step, and puts the core/section/offset information
into the returned data frame
Parameters
___________
magic_dir : str
directory of the MagIC formatted files
hole : str
IODP Hole
demag_step : float
desired demagnetization step in tesla
meas_file : str
input measurement.txt format file for IODP measurements
site_file : str
input sites.txt format file for sites.
verbose : boolean
if True, announce return of dataframe
Returns
___________
DataFrame with selected step and additional metadata
"""
arch_data=pd.read_csv(magic_dir+'/'+meas_file,sep='\t',header=1)
depth_data=pd.read_csv(magic_dir+'/'+site_file,sep='\t',header=1)
depth_data['specimen']=depth_data['site']
depth_data=depth_data[['specimen',depth_key]]
depth_data.sort_values(by='specimen')
arch_data=pd.merge(arch_data,depth_data,on='specimen')
arch_demag_step=arch_data[arch_data['treat_ac_field']==demag_step]
pieces=arch_demag_step.specimen.str.split('-',expand=True)
pieces.columns=['exp','hole','core','sect','A/W','offset']
arch_demag_step['core_sects']=pieces['core'].astype('str')+'-'+pieces['sect'].astype('str')
arch_demag_step['offset']=pieces['offset'].astype('float')
arch_demag_step['core']=pieces['core']
arch_demag_step['section']=pieces['sect']
arch_demag_step['hole']=hole
arch_demag_step.drop_duplicates(inplace=True)
arch_demag_step.to_csv(hole+'/'+hole+'_arch_demag_step.csv',index=False)
if verbose: print ("Here's your demagnetization step DataFrame")
return arch_demag_step
def remove_ends(arch_demag_step,hole,core_top=80,section_ends=10):
"""
takes an archive measurement DataFrame and peels off the section ends and core tops
Parameters
__________
arch_demag_step : Pandas DataFrame
data frame filtered by iodp_funcs.demag_step
hole : str
IODP hole
core_top : float
cm to remove from the core top
section_ends : float
cm to remove from the section ends
Returns
_______
noends : DataFrame
filtered data frame
"""
noends=pd.DataFrame(columns=arch_demag_step.columns)
core_sects=arch_demag_step.core_sects.unique()
for core_sect in core_sects:
cs_df=arch_demag_step[arch_demag_step['core_sects'].str.contains(core_sect)]
if '-1' in core_sect:
cs_df=cs_df[cs_df.offset>cs_df['offset'].min()+core_top] # top 80cm
else:
cs_df=cs_df[cs_df.offset>cs_df['offset'].min()+section_ends] # top 10 cm
cs_df=cs_df[cs_df.offset<cs_df['offset'].max()-10]
noends=pd.concat([noends,cs_df])
noends.drop_duplicates(inplace=True)
noends.fillna("",inplace=True)
noends.to_csv(hole+'/'+hole+'_noends.csv',index=False)
print ("Here's your no end DataFrame")
return noends
def remove_disturbance(noends,hole):
"""
takes an archive measurement DataFrame and removes disturbed intervals using DescLogic files
Parameters
__________
noends : Pandas DataFrame
data frame filtered by iodp_funcs.remove_ends
hole : str
IODP hole
Returns
_______
nodist : DataFrame
filtered data frame
"""
disturbance_file=hole+'/'+hole+'_disturbances.xlsx'
disturbance_df=pd.read_excel(disturbance_file)
disturbance_df.dropna(subset=['Drilling disturbance intensity'],inplace=True)
disturbance_df=disturbance_df[disturbance_df['Drilling disturbance intensity'].str.contains('high')]
disturbance_df=disturbance_df[['Top Depth [m]','Bottom Depth [m]']]
disturbance_df.reset_index(inplace=True)
nodist=noends.copy(deep=True)
for k in disturbance_df.index.tolist():
top=disturbance_df.loc[k]['Top Depth [m]']
bottom=disturbance_df.loc[k]['Bottom Depth [m]']
nodist=nodist[(nodist['core_depth']<top) | (nodist['core_depth']>bottom)]
nodist.sort_values(by='core_depth',inplace=True)
nodist.drop_duplicates(inplace=True)
nodist.fillna("",inplace=True)
# save for later
nodist.to_csv(hole+'/'+hole+'_nodisturbance.csv',index=False)
print ("Here's your no DescLogic disturbance DataFrame")
return nodist
def no_xray_disturbance(nodist,hole):
"""
takes an archive measurement DataFrame and removes disturbed intervals using XRAY disturbance files
Parameters
__________
nodist : Pandas DataFrame
data frame filtered by iodp_funcs.remove_disturbance
hole : str
IODP hole
Returns
_______
no_xray_df : DataFrame
filtered data frame
"""
disturbance_file=hole+'/'+hole+'_disturbances.xlsx'
disturbance_df=pd.read_excel(disturbance_file)
disturbance_df.dropna(subset=['Drilling disturbance intensity'],inplace=True)
disturbance_df=disturbance_df[disturbance_df['Drilling disturbance intensity'].str.contains('high')]
xray_file=hole+'/'+hole+'_xray_disturbance.xlsx'
xray_df=pd.read_excel(xray_file,header=2)
no_xray_df=pd.DataFrame(columns=nodist.columns)
xray_df=xray_df[['Core','Section','interval (offset cm)']]
xray_df.dropna(inplace=True)
if type(xray_df.Section)!='str':
xray_df.Section=xray_df.Section.astype('int64')
xray_df.reset_index(inplace=True)
xray_df['core_sect']=xray_df['Core']+'-'+xray_df['Section'].astype('str')
xr_core_sects=xray_df['core_sect'].tolist()
nd_core_sects=nodist['core_sects'].tolist()
used=[]
# put in undisturbed cores
for coresect in nd_core_sects:
if coresect not in used and coresect not in xr_core_sects:
core_df=nodist[nodist['core_sects'].str.match(coresect)]
no_xray_df=pd.concat([no_xray_df,core_df])
used.append(coresect)
# take out disturbed bits
for coresect in xr_core_sects:
core_df=nodist[(nodist['core_sects'].str.match(coresect))]
x_core_df=xray_df[xray_df['core_sect']==coresect]
core_sect_intervals=x_core_df['interval (offset cm)'].tolist()
for core_sect_interval in core_sect_intervals:
interval=core_sect_interval.split('-')
top=int(interval[0])
bottom=int(interval[1])
# remove disturbed bit
core_df=core_df[(core_df['offset']<top) | (core_df['offset']>bottom)]
# add undisturbed bit to no_xray_df
no_xray_df=pd.concat([no_xray_df,core_df])
no_xray_df.sort_values(by='core_depth',inplace=True)
# save for later
no_xray_df.drop_duplicates(inplace=True)
no_xray_df.fillna("",inplace=True)
no_xray_df.to_csv(hole+'/'+hole+'_noXraydisturbance.csv',index=False)
#meas_dicts = no_xray_df.to_dict('records')
#pmag.magic_write(magic_dir+'/no_xray_measurements.txt', meas_dicts, 'measurements')
print ('Here is your DataFrame with no Xray identified disturbances')
return no_xray_df
def adj_dec(df,hole):
"""
takes an archive measurement DataFrame and adjusts the average declination by hole to 90 for "normal"
Parameters
__________
df : Pandas DataFrame
data frame of archive measurement data
hole : str
IODP hole
Returns
_______
adj_dec_df : DataFrame
adjusted declination data frame
core_dec_adj : dict
dictionary of cores and the average declination
"""
cores=df.core.unique()
adj_dec_df=pd.DataFrame(columns=df.columns)
core_dec_adj={}
for core in cores:
core_df=df[df['core']==core]
di_block=core_df[['dir_dec','dir_inc']].values
ppars=pmag.doprinc(di_block)
if ppars['inc']>0: # take the antipode
ppars['dec']=ppars['dec']-180
core_dec_adj[core]=ppars['dec']
core_df['adj_dec']=(core_df['dir_dec']-ppars['dec'])%360
core_df['dir_dec']=(core_df['adj_dec']+90)%360 # set mean normal to 90 for plottingh
adj_dec_df=
|
pd.concat([adj_dec_df,core_df])
|
pandas.concat
|
import copy
import re
from textwrap import dedent
import numpy as np
import pytest
import pandas as pd
from pandas import (
DataFrame,
MultiIndex,
)
import pandas._testing as tm
jinja2 = pytest.importorskip("jinja2")
from pandas.io.formats.style import ( # isort:skip
Styler,
)
from pandas.io.formats.style_render import (
_get_level_lengths,
_get_trimming_maximums,
maybe_convert_css_to_tuples,
non_reducing_slice,
)
@pytest.fixture
def mi_df():
return DataFrame(
[[1, 2], [3, 4]],
index=MultiIndex.from_product([["i0"], ["i1_a", "i1_b"]]),
columns=MultiIndex.from_product([["c0"], ["c1_a", "c1_b"]]),
dtype=int,
)
@pytest.fixture
def mi_styler(mi_df):
return Styler(mi_df, uuid_len=0)
@pytest.fixture
def mi_styler_comp(mi_styler):
# comprehensively add features to mi_styler
mi_styler = mi_styler._copy(deepcopy=True)
mi_styler.css = {**mi_styler.css, **{"row": "ROW", "col": "COL"}}
mi_styler.uuid_len = 5
mi_styler.uuid = "abcde"
mi_styler.set_caption("capt")
mi_styler.set_table_styles([{"selector": "a", "props": "a:v;"}])
mi_styler.hide(axis="columns")
mi_styler.hide([("c0", "c1_a")], axis="columns", names=True)
mi_styler.hide(axis="index")
mi_styler.hide([("i0", "i1_a")], axis="index", names=True)
mi_styler.set_table_attributes('class="box"')
mi_styler.format(na_rep="MISSING", precision=3)
mi_styler.format_index(precision=2, axis=0)
mi_styler.format_index(precision=4, axis=1)
mi_styler.highlight_max(axis=None)
mi_styler.applymap_index(lambda x: "color: white;", axis=0)
mi_styler.applymap_index(lambda x: "color: black;", axis=1)
mi_styler.set_td_classes(
DataFrame(
[["a", "b"], ["a", "c"]], index=mi_styler.index, columns=mi_styler.columns
)
)
mi_styler.set_tooltips(
DataFrame(
[["a2", "b2"], ["a2", "c2"]],
index=mi_styler.index,
columns=mi_styler.columns,
)
)
return mi_styler
@pytest.mark.parametrize(
"sparse_columns, exp_cols",
[
(
True,
[
{"is_visible": True, "attributes": 'colspan="2"', "value": "c0"},
{"is_visible": False, "attributes": "", "value": "c0"},
],
),
(
False,
[
{"is_visible": True, "attributes": "", "value": "c0"},
{"is_visible": True, "attributes": "", "value": "c0"},
],
),
],
)
def test_mi_styler_sparsify_columns(mi_styler, sparse_columns, exp_cols):
exp_l1_c0 = {"is_visible": True, "attributes": "", "display_value": "c1_a"}
exp_l1_c1 = {"is_visible": True, "attributes": "", "display_value": "c1_b"}
ctx = mi_styler._translate(True, sparse_columns)
assert exp_cols[0].items() <= ctx["head"][0][2].items()
assert exp_cols[1].items() <= ctx["head"][0][3].items()
assert exp_l1_c0.items() <= ctx["head"][1][2].items()
assert exp_l1_c1.items() <= ctx["head"][1][3].items()
@pytest.mark.parametrize(
"sparse_index, exp_rows",
[
(
True,
[
{"is_visible": True, "attributes": 'rowspan="2"', "value": "i0"},
{"is_visible": False, "attributes": "", "value": "i0"},
],
),
(
False,
[
{"is_visible": True, "attributes": "", "value": "i0"},
{"is_visible": True, "attributes": "", "value": "i0"},
],
),
],
)
def test_mi_styler_sparsify_index(mi_styler, sparse_index, exp_rows):
exp_l1_r0 = {"is_visible": True, "attributes": "", "display_value": "i1_a"}
exp_l1_r1 = {"is_visible": True, "attributes": "", "display_value": "i1_b"}
ctx = mi_styler._translate(sparse_index, True)
assert exp_rows[0].items() <= ctx["body"][0][0].items()
assert exp_rows[1].items() <= ctx["body"][1][0].items()
assert exp_l1_r0.items() <= ctx["body"][0][1].items()
assert exp_l1_r1.items() <= ctx["body"][1][1].items()
def test_mi_styler_sparsify_options(mi_styler):
with pd.option_context("styler.sparse.index", False):
html1 = mi_styler.to_html()
with pd.option_context("styler.sparse.index", True):
html2 = mi_styler.to_html()
assert html1 != html2
with pd.option_context("styler.sparse.columns", False):
html1 = mi_styler.to_html()
with pd.option_context("styler.sparse.columns", True):
html2 = mi_styler.to_html()
assert html1 != html2
@pytest.mark.parametrize(
"rn, cn, max_els, max_rows, max_cols, exp_rn, exp_cn",
[
(100, 100, 100, None, None, 12, 6), # reduce to (12, 6) < 100 elements
(1000, 3, 750, None, None, 250, 3), # dynamically reduce rows to 250, keep cols
(4, 1000, 500, None, None, 4, 125), # dynamically reduce cols to 125, keep rows
(1000, 3, 750, 10, None, 10, 3), # overwrite above dynamics with max_row
(4, 1000, 500, None, 5, 4, 5), # overwrite above dynamics with max_col
(100, 100, 700, 50, 50, 25, 25), # rows cols below given maxes so < 700 elmts
],
)
def test_trimming_maximum(rn, cn, max_els, max_rows, max_cols, exp_rn, exp_cn):
rn, cn = _get_trimming_maximums(
rn, cn, max_els, max_rows, max_cols, scaling_factor=0.5
)
assert (rn, cn) == (exp_rn, exp_cn)
@pytest.mark.parametrize(
"option, val",
[
("styler.render.max_elements", 6),
("styler.render.max_rows", 3),
],
)
def test_render_trimming_rows(option, val):
# test auto and specific trimming of rows
df = DataFrame(np.arange(120).reshape(60, 2))
with pd.option_context(option, val):
ctx = df.style._translate(True, True)
assert len(ctx["head"][0]) == 3 # index + 2 data cols
assert len(ctx["body"]) == 4 # 3 data rows + trimming row
assert len(ctx["body"][0]) == 3 # index + 2 data cols
@pytest.mark.parametrize(
"option, val",
[
("styler.render.max_elements", 6),
("styler.render.max_columns", 2),
],
)
def test_render_trimming_cols(option, val):
# test auto and specific trimming of cols
df = DataFrame(np.arange(30).reshape(3, 10))
with pd.option_context(option, val):
ctx = df.style._translate(True, True)
assert len(ctx["head"][0]) == 4 # index + 2 data cols + trimming col
assert len(ctx["body"]) == 3 # 3 data rows
assert len(ctx["body"][0]) == 4 # index + 2 data cols + trimming col
def test_render_trimming_mi():
midx = MultiIndex.from_product([[1, 2], [1, 2, 3]])
df = DataFrame(np.arange(36).reshape(6, 6), columns=midx, index=midx)
with pd.option_context("styler.render.max_elements", 4):
ctx = df.style._translate(True, True)
assert len(ctx["body"][0]) == 5 # 2 indexes + 2 data cols + trimming row
assert {"attributes": 'rowspan="2"'}.items() <= ctx["body"][0][0].items()
assert {"class": "data row0 col_trim"}.items() <= ctx["body"][0][4].items()
assert {"class": "data row_trim col_trim"}.items() <= ctx["body"][2][4].items()
assert len(ctx["body"]) == 3 # 2 data rows + trimming row
assert len(ctx["head"][0]) == 5 # 2 indexes + 2 column headers + trimming col
assert {"attributes": 'colspan="2"'}.items() <= ctx["head"][0][2].items()
def test_render_empty_mi():
# GH 43305
df = DataFrame(index=MultiIndex.from_product([["A"], [0, 1]], names=[None, "one"]))
expected = dedent(
"""\
>
<thead>
<tr>
<th class="index_name level0" > </th>
<th class="index_name level1" >one</th>
</tr>
</thead>
"""
)
assert expected in df.style.to_html()
@pytest.mark.parametrize("comprehensive", [True, False])
@pytest.mark.parametrize("render", [True, False])
@pytest.mark.parametrize("deepcopy", [True, False])
def test_copy(comprehensive, render, deepcopy, mi_styler, mi_styler_comp):
styler = mi_styler_comp if comprehensive else mi_styler
styler.uuid_len = 5
s2 = copy.deepcopy(styler) if deepcopy else copy.copy(styler) # make copy and check
assert s2 is not styler
if render:
styler.to_html()
excl = [
"na_rep", # deprecated
"precision", # deprecated
"cellstyle_map", # render time vars..
"cellstyle_map_columns",
"cellstyle_map_index",
"template_latex", # render templates are class level
"template_html",
"template_html_style",
"template_html_table",
]
if not deepcopy: # check memory locations are equal for all included attributes
for attr in [a for a in styler.__dict__ if (not callable(a) and a not in excl)]:
assert id(getattr(s2, attr)) == id(getattr(styler, attr))
else: # check memory locations are different for nested or mutable vars
shallow = [
"data",
"columns",
"index",
"uuid_len",
"uuid",
"caption",
"cell_ids",
"hide_index_",
"hide_columns_",
"hide_index_names",
"hide_column_names",
"table_attributes",
]
for attr in shallow:
assert id(getattr(s2, attr)) == id(getattr(styler, attr))
for attr in [
a
for a in styler.__dict__
if (not callable(a) and a not in excl and a not in shallow)
]:
if getattr(s2, attr) is None:
assert id(getattr(s2, attr)) == id(getattr(styler, attr))
else:
assert id(getattr(s2, attr)) != id(getattr(styler, attr))
def test_clear(mi_styler_comp):
# NOTE: if this test fails for new features then 'mi_styler_comp' should be updated
# to ensure proper testing of the 'copy', 'clear', 'export' methods with new feature
# GH 40675
styler = mi_styler_comp
styler._compute() # execute applied methods
clean_copy = Styler(styler.data, uuid=styler.uuid)
excl = [
"data",
"index",
"columns",
"uuid",
"uuid_len", # uuid is set to be the same on styler and clean_copy
"cell_ids",
"cellstyle_map", # execution time only
"cellstyle_map_columns", # execution time only
"cellstyle_map_index", # execution time only
"precision", # deprecated
"na_rep", # deprecated
"template_latex", # render templates are class level
"template_html",
"template_html_style",
"template_html_table",
]
# tests vars are not same vals on obj and clean copy before clear (except for excl)
for attr in [a for a in styler.__dict__ if not (callable(a) or a in excl)]:
res = getattr(styler, attr) == getattr(clean_copy, attr)
assert not (all(res) if (hasattr(res, "__iter__") and len(res) > 0) else res)
# test vars have same vales on obj and clean copy after clearing
styler.clear()
for attr in [a for a in styler.__dict__ if not (callable(a))]:
res = getattr(styler, attr) == getattr(clean_copy, attr)
assert all(res) if hasattr(res, "__iter__") else res
def test_export(mi_styler_comp, mi_styler):
exp_attrs = [
"_todo",
"hide_index_",
"hide_index_names",
"hide_columns_",
"hide_column_names",
"table_attributes",
"table_styles",
"css",
]
for attr in exp_attrs:
check = getattr(mi_styler, attr) == getattr(mi_styler_comp, attr)
assert not (
all(check) if (hasattr(check, "__iter__") and len(check) > 0) else check
)
export = mi_styler_comp.export()
used = mi_styler.use(export)
for attr in exp_attrs:
check = getattr(used, attr) == getattr(mi_styler_comp, attr)
assert all(check) if (hasattr(check, "__iter__") and len(check) > 0) else check
used.to_html()
def test_hide_raises(mi_styler):
msg = "`subset` and `level` cannot be passed simultaneously"
with pytest.raises(ValueError, match=msg):
mi_styler.hide(axis="index", subset="something", level="something else")
msg = "`level` must be of type `int`, `str` or list of such"
with pytest.raises(ValueError, match=msg):
mi_styler.hide(axis="index", level={"bad": 1, "type": 2})
@pytest.mark.parametrize("level", [1, "one", [1], ["one"]])
def test_hide_index_level(mi_styler, level):
mi_styler.index.names, mi_styler.columns.names = ["zero", "one"], ["zero", "one"]
ctx = mi_styler.hide(axis="index", level=level)._translate(False, True)
assert len(ctx["head"][0]) == 3
assert len(ctx["head"][1]) == 3
assert len(ctx["head"][2]) == 4
assert ctx["head"][2][0]["is_visible"]
assert not ctx["head"][2][1]["is_visible"]
assert ctx["body"][0][0]["is_visible"]
assert not ctx["body"][0][1]["is_visible"]
assert ctx["body"][1][0]["is_visible"]
assert not ctx["body"][1][1]["is_visible"]
@pytest.mark.parametrize("level", [1, "one", [1], ["one"]])
@pytest.mark.parametrize("names", [True, False])
def test_hide_columns_level(mi_styler, level, names):
mi_styler.columns.names = ["zero", "one"]
if names:
mi_styler.index.names = ["zero", "one"]
ctx = mi_styler.hide(axis="columns", level=level)._translate(True, False)
assert len(ctx["head"]) == (2 if names else 1)
@pytest.mark.parametrize("method", ["applymap", "apply"])
@pytest.mark.parametrize("axis", ["index", "columns"])
def test_apply_map_header(method, axis):
# GH 41893
df = DataFrame({"A": [0, 0], "B": [1, 1]}, index=["C", "D"])
func = {
"apply": lambda s: ["attr: val" if ("A" in v or "C" in v) else "" for v in s],
"applymap": lambda v: "attr: val" if ("A" in v or "C" in v) else "",
}
# test execution added to todo
result = getattr(df.style, f"{method}_index")(func[method], axis=axis)
assert len(result._todo) == 1
assert len(getattr(result, f"ctx_{axis}")) == 0
# test ctx object on compute
result._compute()
expected = {
(0, 0): [("attr", "val")],
}
assert getattr(result, f"ctx_{axis}") == expected
@pytest.mark.parametrize("method", ["apply", "applymap"])
@pytest.mark.parametrize("axis", ["index", "columns"])
def test_apply_map_header_mi(mi_styler, method, axis):
# GH 41893
func = {
"apply": lambda s: ["attr: val;" if "b" in v else "" for v in s],
"applymap": lambda v: "attr: val" if "b" in v else "",
}
result = getattr(mi_styler, f"{method}_index")(func[method], axis=axis)._compute()
expected = {(1, 1): [("attr", "val")]}
assert getattr(result, f"ctx_{axis}") == expected
def test_apply_map_header_raises(mi_styler):
# GH 41893
with pytest.raises(ValueError, match="No axis named bad for object type DataFrame"):
mi_styler.applymap_index(lambda v: "attr: val;", axis="bad")._compute()
class TestStyler:
def setup_method(self, method):
np.random.seed(24)
self.s = DataFrame({"A": np.random.permutation(range(6))})
self.df = DataFrame({"A": [0, 1], "B": np.random.randn(2)})
self.f = lambda x: x
self.g = lambda x: x
def h(x, foo="bar"):
return pd.Series(f"color: {foo}", index=x.index, name=x.name)
self.h = h
self.styler = Styler(self.df)
self.attrs = DataFrame({"A": ["color: red", "color: blue"]})
self.dataframes = [
self.df,
DataFrame(
{"f": [1.0, 2.0], "o": ["a", "b"], "c": pd.Categorical(["a", "b"])}
),
]
self.blank_value = " "
def test_init_non_pandas(self):
msg = "``data`` must be a Series or DataFrame"
with pytest.raises(TypeError, match=msg):
Styler([1, 2, 3])
def test_init_series(self):
result = Styler(pd.Series([1, 2]))
assert result.data.ndim == 2
def test_repr_html_ok(self):
self.styler._repr_html_()
def test_repr_html_mathjax(self):
# gh-19824 / 41395
assert "tex2jax_ignore" not in self.styler._repr_html_()
with pd.option_context("styler.html.mathjax", False):
assert "tex2jax_ignore" in self.styler._repr_html_()
def test_update_ctx(self):
self.styler._update_ctx(self.attrs)
expected = {(0, 0): [("color", "red")], (1, 0): [("color", "blue")]}
assert self.styler.ctx == expected
def test_update_ctx_flatten_multi_and_trailing_semi(self):
attrs = DataFrame({"A": ["color: red; foo: bar", "color:blue ; foo: baz;"]})
self.styler._update_ctx(attrs)
expected = {
(0, 0): [("color", "red"), ("foo", "bar")],
(1, 0): [("color", "blue"), ("foo", "baz")],
}
assert self.styler.ctx == expected
def test_render(self):
df = DataFrame({"A": [0, 1]})
style = lambda x: pd.Series(["color: red", "color: blue"], name=x.name)
s = Styler(df, uuid="AB").apply(style)
s.to_html()
# it worked?
def test_multiple_render(self):
# GH 39396
s = Styler(self.df, uuid_len=0).applymap(lambda x: "color: red;", subset=["A"])
s.to_html() # do 2 renders to ensure css styles not duplicated
assert (
'<style type="text/css">\n#T__row0_col0, #T__row1_col0 {\n'
" color: red;\n}\n</style>" in s.to_html()
)
def test_render_empty_dfs(self):
empty_df = DataFrame()
es = Styler(empty_df)
es.to_html()
# An index but no columns
DataFrame(columns=["a"]).style.to_html()
# A column but no index
DataFrame(index=["a"]).style.to_html()
# No IndexError raised?
def test_render_double(self):
df = DataFrame({"A": [0, 1]})
style = lambda x: pd.Series(
["color: red; border: 1px", "color: blue; border: 2px"], name=x.name
)
s = Styler(df, uuid="AB").apply(style)
s.to_html()
# it worked?
def test_set_properties(self):
df = DataFrame({"A": [0, 1]})
result = df.style.set_properties(color="white", size="10px")._compute().ctx
# order is deterministic
v = [("color", "white"), ("size", "10px")]
expected = {(0, 0): v, (1, 0): v}
assert result.keys() == expected.keys()
for v1, v2 in zip(result.values(), expected.values()):
assert sorted(v1) == sorted(v2)
def test_set_properties_subset(self):
df = DataFrame({"A": [0, 1]})
result = (
df.style.set_properties(subset=pd.IndexSlice[0, "A"], color="white")
._compute()
.ctx
)
expected = {(0, 0): [("color", "white")]}
assert result == expected
def test_empty_index_name_doesnt_display(self):
# https://github.com/pandas-dev/pandas/pull/12090#issuecomment-180695902
df = DataFrame({"A": [1, 2], "B": [3, 4], "C": [5, 6]})
result = df.style._translate(True, True)
assert len(result["head"]) == 1
expected = {
"class": "blank level0",
"type": "th",
"value": self.blank_value,
"is_visible": True,
"display_value": self.blank_value,
}
assert expected.items() <= result["head"][0][0].items()
def test_index_name(self):
# https://github.com/pandas-dev/pandas/issues/11655
df = DataFrame({"A": [1, 2], "B": [3, 4], "C": [5, 6]})
result = df.set_index("A").style._translate(True, True)
expected = {
"class": "index_name level0",
"type": "th",
"value": "A",
"is_visible": True,
"display_value": "A",
}
assert expected.items() <= result["head"][1][0].items()
def test_multiindex_name(self):
# https://github.com/pandas-dev/pandas/issues/11655
df = DataFrame({"A": [1, 2], "B": [3, 4], "C": [5, 6]})
result = df.set_index(["A", "B"]).style._translate(True, True)
expected = [
{
"class": "index_name level0",
"type": "th",
"value": "A",
"is_visible": True,
"display_value": "A",
},
{
"class": "index_name level1",
"type": "th",
"value": "B",
"is_visible": True,
"display_value": "B",
},
{
"class": "blank col0",
"type": "th",
"value": self.blank_value,
"is_visible": True,
"display_value": self.blank_value,
},
]
assert result["head"][1] == expected
def test_numeric_columns(self):
# https://github.com/pandas-dev/pandas/issues/12125
# smoke test for _translate
df = DataFrame({0: [1, 2, 3]})
df.style._translate(True, True)
def test_apply_axis(self):
df = DataFrame({"A": [0, 0], "B": [1, 1]})
f = lambda x: [f"val: {x.max()}" for v in x]
result = df.style.apply(f, axis=1)
assert len(result._todo) == 1
assert len(result.ctx) == 0
result._compute()
expected = {
(0, 0): [("val", "1")],
(0, 1): [("val", "1")],
(1, 0): [("val", "1")],
(1, 1): [("val", "1")],
}
assert result.ctx == expected
result = df.style.apply(f, axis=0)
expected = {
(0, 0): [("val", "0")],
(0, 1): [("val", "1")],
(1, 0): [("val", "0")],
(1, 1): [("val", "1")],
}
result._compute()
assert result.ctx == expected
result = df.style.apply(f) # default
result._compute()
assert result.ctx == expected
@pytest.mark.parametrize("axis", [0, 1])
def test_apply_series_return(self, axis):
# GH 42014
df = DataFrame([[1, 2], [3, 4]], index=["X", "Y"], columns=["X", "Y"])
# test Series return where len(Series) < df.index or df.columns but labels OK
func = lambda s: pd.Series(["color: red;"], index=["Y"])
result = df.style.apply(func, axis=axis)._compute().ctx
assert result[(1, 1)] == [("color", "red")]
assert result[(1 - axis, axis)] == [("color", "red")]
# test Series return where labels align but different order
func = lambda s: pd.Series(["color: red;", "color: blue;"], index=["Y", "X"])
result = df.style.apply(func, axis=axis)._compute().ctx
assert result[(0, 0)] == [("color", "blue")]
assert result[(1, 1)] == [("color", "red")]
assert result[(1 - axis, axis)] == [("color", "red")]
assert result[(axis, 1 - axis)] == [("color", "blue")]
@pytest.mark.parametrize("index", [False, True])
@pytest.mark.parametrize("columns", [False, True])
def test_apply_dataframe_return(self, index, columns):
# GH 42014
df = DataFrame([[1, 2], [3, 4]], index=["X", "Y"], columns=["X", "Y"])
idxs = ["X", "Y"] if index else ["Y"]
cols = ["X", "Y"] if columns else ["Y"]
df_styles = DataFrame("color: red;", index=idxs, columns=cols)
result = df.style.apply(lambda x: df_styles, axis=None)._compute().ctx
assert result[(1, 1)] == [("color", "red")] # (Y,Y) styles always present
assert (result[(0, 1)] == [("color", "red")]) is index # (X,Y) only if index
assert (result[(1, 0)] == [("color", "red")]) is columns # (Y,X) only if cols
assert (result[(0, 0)] == [("color", "red")]) is (index and columns) # (X,X)
@pytest.mark.parametrize(
"slice_",
[
pd.IndexSlice[:],
pd.IndexSlice[:, ["A"]],
pd.IndexSlice[[1], :],
pd.IndexSlice[[1], ["A"]],
pd.IndexSlice[:2, ["A", "B"]],
],
)
@pytest.mark.parametrize("axis", [0, 1])
def test_apply_subset(self, slice_, axis):
result = (
self.df.style.apply(self.h, axis=axis, subset=slice_, foo="baz")
._compute()
.ctx
)
expected = {
(r, c): [("color", "baz")]
for r, row in enumerate(self.df.index)
for c, col in enumerate(self.df.columns)
if row in self.df.loc[slice_].index and col in self.df.loc[slice_].columns
}
assert result == expected
@pytest.mark.parametrize(
"slice_",
[
pd.IndexSlice[:],
pd.IndexSlice[:, ["A"]],
pd.IndexSlice[[1], :],
pd.IndexSlice[[1], ["A"]],
pd.IndexSlice[:2, ["A", "B"]],
],
)
def test_applymap_subset(self, slice_):
result = (
self.df.style.applymap(lambda x: "color:baz;", subset=slice_)._compute().ctx
)
expected = {
(r, c): [("color", "baz")]
for r, row in enumerate(self.df.index)
for c, col in enumerate(self.df.columns)
if row in self.df.loc[slice_].index and col in self.df.loc[slice_].columns
}
assert result == expected
@pytest.mark.parametrize(
"slice_",
[
pd.IndexSlice[:, pd.IndexSlice["x", "A"]],
pd.IndexSlice[:, pd.IndexSlice[:, "A"]],
pd.IndexSlice[:, pd.IndexSlice[:, ["A", "C"]]], # missing col element
pd.IndexSlice[pd.IndexSlice["a", 1], :],
pd.IndexSlice[pd.IndexSlice[:, 1], :],
pd.IndexSlice[pd.IndexSlice[:, [1, 3]], :], # missing row element
pd.IndexSlice[:, ("x", "A")],
pd.IndexSlice[("a", 1), :],
],
)
def test_applymap_subset_multiindex(self, slice_):
# GH 19861
# edited for GH 33562
warn = None
msg = "indexing on a MultiIndex with a nested sequence of labels"
if (
isinstance(slice_[-1], tuple)
and isinstance(slice_[-1][-1], list)
and "C" in slice_[-1][-1]
):
warn = FutureWarning
elif (
isinstance(slice_[0], tuple)
and isinstance(slice_[0][1], list)
and 3 in slice_[0][1]
):
warn = FutureWarning
idx = MultiIndex.from_product([["a", "b"], [1, 2]])
col = MultiIndex.from_product([["x", "y"], ["A", "B"]])
df = DataFrame(np.random.rand(4, 4), columns=col, index=idx)
with tm.assert_produces_warning(warn, match=msg, check_stacklevel=False):
df.style.applymap(lambda x: "color: red;", subset=slice_).to_html()
def test_applymap_subset_multiindex_code(self):
# https://github.com/pandas-dev/pandas/issues/25858
# Checks styler.applymap works with multindex when codes are provided
codes = np.array([[0, 0, 1, 1], [0, 1, 0, 1]])
columns = MultiIndex(
levels=[["a", "b"], ["%", "#"]], codes=codes, names=["", ""]
)
df = DataFrame(
[[1, -1, 1, 1], [-1, 1, 1, 1]], index=["hello", "world"], columns=columns
)
pct_subset = pd.IndexSlice[:, pd.IndexSlice[:, "%":"%"]]
def color_negative_red(val):
color = "red" if val < 0 else "black"
return f"color: {color}"
df.loc[pct_subset]
df.style.applymap(color_negative_red, subset=pct_subset)
def test_empty(self):
df = DataFrame({"A": [1, 0]})
s = df.style
s.ctx = {(0, 0): [("color", "red")], (1, 0): [("", "")]}
result = s._translate(True, True)["cellstyle"]
expected = [
{"props": [("color", "red")], "selectors": ["row0_col0"]},
{"props": [("", "")], "selectors": ["row1_col0"]},
]
assert result == expected
def test_duplicate(self):
df = DataFrame({"A": [1, 0]})
s = df.style
s.ctx = {(0, 0): [("color", "red")], (1, 0): [("color", "red")]}
result = s._translate(True, True)["cellstyle"]
expected = [
{"props": [("color", "red")], "selectors": ["row0_col0", "row1_col0"]}
]
assert result == expected
def test_init_with_na_rep(self):
# GH 21527 28358
df = DataFrame([[None, None], [1.1, 1.2]], columns=["A", "B"])
ctx = Styler(df, na_rep="NA")._translate(True, True)
assert ctx["body"][0][1]["display_value"] == "NA"
assert ctx["body"][0][2]["display_value"] == "NA"
def test_caption(self):
styler = Styler(self.df, caption="foo")
result = styler.to_html()
assert all(["caption" in result, "foo" in result])
styler = self.df.style
result = styler.set_caption("baz")
assert styler is result
assert styler.caption == "baz"
def test_uuid(self):
styler = Styler(self.df, uuid="abc123")
result = styler.to_html()
assert "abc123" in result
styler = self.df.style
result = styler.set_uuid("aaa")
assert result is styler
assert result.uuid == "aaa"
def test_unique_id(self):
# See https://github.com/pandas-dev/pandas/issues/16780
df = DataFrame({"a": [1, 3, 5, 6], "b": [2, 4, 12, 21]})
result = df.style.to_html(uuid="test")
assert "test" in result
ids = re.findall('id="(.*?)"', result)
assert np.unique(ids).size == len(ids)
def test_table_styles(self):
style = [{"selector": "th", "props": [("foo", "bar")]}] # default format
styler = Styler(self.df, table_styles=style)
result = " ".join(styler.to_html().split())
assert "th { foo: bar; }" in result
styler = self.df.style
result = styler.set_table_styles(style)
assert styler is result
assert styler.table_styles == style
# GH 39563
style = [{"selector": "th", "props": "foo:bar;"}] # css string format
styler = self.df.style.set_table_styles(style)
result = " ".join(styler.to_html().split())
assert "th { foo: bar; }" in result
def test_table_styles_multiple(self):
ctx = self.df.style.set_table_styles(
[
{"selector": "th,td", "props": "color:red;"},
{"selector": "tr", "props": "color:green;"},
]
)._translate(True, True)["table_styles"]
assert ctx == [
{"selector": "th", "props": [("color", "red")]},
{"selector": "td", "props": [("color", "red")]},
{"selector": "tr", "props": [("color", "green")]},
]
def test_table_styles_dict_multiple_selectors(self):
# GH 44011
result = self.df.style.set_table_styles(
[{"selector": "th,td", "props": [("border-left", "2px solid black")]}]
)._translate(True, True)["table_styles"]
expected = [
{"selector": "th", "props": [("border-left", "2px solid black")]},
{"selector": "td", "props": [("border-left", "2px solid black")]},
]
assert result == expected
def test_maybe_convert_css_to_tuples(self):
expected = [("a", "b"), ("c", "d e")]
assert maybe_convert_css_to_tuples("a:b;c:d e;") == expected
assert maybe_convert_css_to_tuples("a: b ;c: d e ") == expected
expected = []
assert maybe_convert_css_to_tuples("") == expected
def test_maybe_convert_css_to_tuples_err(self):
msg = "Styles supplied as string must follow CSS rule formats"
with pytest.raises(ValueError, match=msg):
maybe_convert_css_to_tuples("err")
def test_table_attributes(self):
attributes = 'class="foo" data-bar'
styler = Styler(self.df, table_attributes=attributes)
result = styler.to_html()
assert 'class="foo" data-bar' in result
result = self.df.style.set_table_attributes(attributes).to_html()
assert 'class="foo" data-bar' in result
def test_apply_none(self):
def f(x):
return DataFrame(
np.where(x == x.max(), "color: red", ""),
index=x.index,
columns=x.columns,
)
result = DataFrame([[1, 2], [3, 4]]).style.apply(f, axis=None)._compute().ctx
assert result[(1, 1)] == [("color", "red")]
def test_trim(self):
result = self.df.style.to_html() # trim=True
assert result.count("#") == 0
result = self.df.style.highlight_max().to_html()
assert result.count("#") == len(self.df.columns)
def test_export(self):
f = lambda x: "color: red" if x > 0 else "color: blue"
g = lambda x, z: f"color: {z}" if x > 0 else f"color: {z}"
style1 = self.styler
style1.applymap(f).applymap(g, z="b").highlight_max()._compute() # = render
result = style1.export()
style2 = self.df.style
style2.use(result)
assert style1._todo == style2._todo
style2.to_html()
def test_bad_apply_shape(self):
df = DataFrame([[1, 2], [3, 4]], index=["A", "B"], columns=["X", "Y"])
msg = "resulted in the apply method collapsing to a Series."
with pytest.raises(ValueError, match=msg):
df.style._apply(lambda x: "x")
msg = "created invalid {} labels"
with pytest.raises(ValueError, match=msg.format("index")):
df.style._apply(lambda x: [""])
with pytest.raises(ValueError, match=msg.format("index")):
df.style._apply(lambda x: ["", "", "", ""])
with pytest.raises(ValueError, match=msg.format("index")):
df.style._apply(lambda x: pd.Series(["a:v;", ""], index=["A", "C"]), axis=0)
with pytest.raises(ValueError, match=msg.format("columns")):
df.style._apply(lambda x: ["", "", ""], axis=1)
with pytest.raises(ValueError, match=msg.format("columns")):
df.style._apply(lambda x: pd.Series(["a:v;", ""], index=["X", "Z"]), axis=1)
msg = "returned ndarray with wrong shape"
with pytest.raises(ValueError, match=msg):
df.style._apply(lambda x: np.array([[""], [""]]), axis=None)
def test_apply_bad_return(self):
def f(x):
return ""
df = DataFrame([[1, 2], [3, 4]])
msg = (
"must return a DataFrame or ndarray when passed to `Styler.apply` "
"with axis=None"
)
with pytest.raises(TypeError, match=msg):
df.style._apply(f, axis=None)
@pytest.mark.parametrize("axis", ["index", "columns"])
def test_apply_bad_labels(self, axis):
def f(x):
return DataFrame(**{axis: ["bad", "labels"]})
df = DataFrame([[1, 2], [3, 4]])
msg = f"created invalid {axis} labels."
with pytest.raises(ValueError, match=msg):
df.style._apply(f, axis=None)
def test_get_level_lengths(self):
index = MultiIndex.from_product([["a", "b"], [0, 1, 2]])
expected = {
(0, 0): 3,
(0, 3): 3,
(1, 0): 1,
(1, 1): 1,
(1, 2): 1,
(1, 3): 1,
(1, 4): 1,
(1, 5): 1,
}
result = _get_level_lengths(index, sparsify=True, max_index=100)
tm.assert_dict_equal(result, expected)
expected = {
(0, 0): 1,
(0, 1): 1,
(0, 2): 1,
(0, 3): 1,
(0, 4): 1,
(0, 5): 1,
(1, 0): 1,
(1, 1): 1,
(1, 2): 1,
(1, 3): 1,
(1, 4): 1,
(1, 5): 1,
}
result = _get_level_lengths(index, sparsify=False, max_index=100)
|
tm.assert_dict_equal(result, expected)
|
pandas._testing.assert_dict_equal
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.