Skip to content

Commit

Permalink
pep8
Browse files Browse the repository at this point in the history
  • Loading branch information
kiedanski committed Jul 11, 2019
1 parent 343c584 commit cf3dced
Show file tree
Hide file tree
Showing 22 changed files with 285 additions and 254 deletions.
39 changes: 19 additions & 20 deletions pymarket/bids/bids.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
class BidManager(object):
"""A class used to store and manipulate a collection
of all the bids in the market.
Attributes
-----------
col_names : :obj:`list` of :obj:`str`
Expand All @@ -19,27 +19,27 @@ class BidManager(object):
"""

col_names = [
'quantity',
'price',
'user',
'buying',
'time',
'divisible',
]
'quantity',
'price',
'user',
'buying',
'time',
'divisible',
]

def __init__(self):
self.n_bids = 0
self.bids = []

def add_bid(
self,
quantity: float,
price: float,
user: int,
buying: bool=True,
time: float = 0,
divisible: bool =True
) -> int:
self,
quantity: float,
price: float,
user: int,
buying: bool=True,
time: float = 0,
divisible: bool =True
) -> int:
"""Appends a bid to the bid list
Parameters
Expand All @@ -61,7 +61,7 @@ def add_bid(
divisible
`True` is the user accepts a fraction of the asked quantity as
a result and `False` otherwise.
Returns
-------
int
Expand All @@ -76,9 +76,8 @@ def add_bid(
new_bid = (quantity, price, user, buying, time, divisible)
self.bids.append(new_bid)
self.n_bids += 1

return self.n_bids - 1

return self.n_bids - 1

def get_df(self) -> pd.DataFrame:
"""Creates a dataframe with the bids
Expand All @@ -88,7 +87,7 @@ def get_df(self) -> pd.DataFrame:
Returns
-------
pd.DataFrame
pd.DataFrame
Dataframe with each row a different bid
and each column each of the different attributes.
Expand Down
45 changes: 23 additions & 22 deletions pymarket/bids/demand_curves.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
from pymarket.bids import BidManager


def demand_curve_from_bids(bids: pd.DataFrame) -> Tuple[np.ndarray, np.ndarray]:
def demand_curve_from_bids(
bids: pd.DataFrame) -> Tuple[np.ndarray, np.ndarray]:
"""
Creates a demand curve from a set of buying bids.
It is the inverse cumulative distribution of quantity
Expand All @@ -25,7 +26,7 @@ def demand_curve_from_bids(bids: pd.DataFrame) -> Tuple[np.ndarray, np.ndarray]:
and the second column is the y-coordinate.
An extra point is a))dded with x coordinate at infinity and
price at 0 to represent the end of the curve.
index : np.ndarray
The order of the identifier of each bid in the demand
curve.
Expand Down Expand Up @@ -68,15 +69,17 @@ def demand_curve_from_bids(bids: pd.DataFrame) -> Tuple[np.ndarray, np.ndarray]:
array([0, 2, 3])
"""
buying = bids[bids.buying == True]
buying = bids[bids.buying]
buying = buying.sort_values('price', ascending=False)
buying['acum'] = buying.quantity.cumsum()
demand_curve = buying[['acum', 'price']].values
demand_curve = np.vstack([demand_curve, [np.inf, 0]])
index = buying.index.values
return demand_curve, index

def supply_curve_from_bids(bids : pd.DataFrame) -> Tuple[np.ndarray, np.ndarray]:


def supply_curve_from_bids(
bids: pd.DataFrame) -> Tuple[np.ndarray, np.ndarray]:
"""
Creates a supply curve from a set of selling bids.
It is the cumulative distribution of quantity
Expand All @@ -97,7 +100,7 @@ def supply_curve_from_bids(bids : pd.DataFrame) -> Tuple[np.ndarray, np.ndarray]
and the second column is the y-coordinate.
An extra point is added with x coordinate at infinity and
price at infinity to represent the end of the curve.
index : np.ndarray
The order of the identifier of each bid in the supply
curve.
Expand Down Expand Up @@ -150,7 +153,7 @@ def supply_curve_from_bids(bids : pd.DataFrame) -> Tuple[np.ndarray, np.ndarray]
return supply_curve, index


def get_value_stepwise(x : float, f : np.ndarray) -> Union[float, None]:
def get_value_stepwise(x: float, f: np.ndarray) -> Union[float, None]:
"""
Returns the value of a stepwise constant
function defined by the right extrems
Expand Down Expand Up @@ -193,18 +196,18 @@ def get_value_stepwise(x : float, f : np.ndarray) -> Union[float, None]:

for step in f:
if x <= step[0]:
return step[1]
return step[1]


def intersect_stepwise(
f : np.ndarray,
g : np.ndarray,
k:float=0.5
f: np.ndarray,
g: np.ndarray,
k: float=0.5
) -> Tuple[
Union[float, None],
Union[int, None],
Union[int, None],
float]:
Union[float, None],
Union[int, None],
Union[int, None],
float]:
"""
Finds the intersection of
two stepwise constants functions
Expand Down Expand Up @@ -266,7 +269,7 @@ def intersect_stepwise(
>>> g = np.array([[2,2]])
>>> pm.intersect_stepwise(f, g)
(1, 0, 0, 2)
Empty intersection, returning the middle value
>>> f = np.array([[1,3], [2, 2.5]])
Expand All @@ -275,26 +278,24 @@ def intersect_stepwise(
(None, None, None, 2.25)
"""
x_max = np.min([f.max(axis=0)[0], g.max(axis=0)[0]])
xs = sorted([x for x in set(g[:, 0]).union(set(f[:, 0])) if x <= x_max])
xs = sorted([x for x in set(g[:, 0]).union(set(f[:, 0])) if x <= x_max])
fext = [get_value_stepwise(x, f) for x in xs]
gext = [get_value_stepwise(x, g) for x in xs]
x_ast = None
for i in range(len(xs) - 1):
if (fext[i] > gext[i]) and (fext[i + 1] < gext[i + 1]):
x_ast = xs[i]

f_ast = np.argmax(f[:, 0] >= x_ast) if x_ast is not None else None
g_ast = np.argmax(g[:, 0] >= x_ast) if x_ast is not None else None

g_val = g[g_ast, 1] if g_ast is not None else get_value_stepwise(xs[-1], g)
f_val = f[f_ast, 1] if f_ast is not None else get_value_stepwise(xs[-1], f)

intersect_domain_both = x_ast in f[:, 0] and x_ast in g[:, 0]
if not (intersect_domain_both) and (x_ast is not None):
v = g_val if x_ast in f[:, 0] else f_val
else:
v = g_val * k + (1 - k) * f_val

return x_ast, f_ast, g_ast, v


return x_ast, f_ast, g_ast, v
72 changes: 36 additions & 36 deletions pymarket/bids/processing.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@
from pymarket.bids import BidManager


def new_player_id(index : int) -> Callable[[List[int]], int]:
def new_player_id(index: int) -> Callable[[List[int]], int]:
"""Helper function for merge_same_price.
Creates a function that returns consecutive integers.
Parameters
-----------
index
Expand All @@ -30,7 +30,7 @@ def new_player_id(index : int) -> Callable[[List[int]], int]:
>>> id_gen([3])
3
>>> id_gen([5])
5
5
>>> id_gen([0, 1])
6
>>> id_gen([2, 4])
Expand All @@ -43,9 +43,9 @@ def new_id(users: List[int]) -> int:
Generates a unique identifier for a
list of users. If the list has
only one user, then the id is mantained
else, a new user id is created for the
else, a new user id is created for the
whole list.
Parameters
----------
users
Expand Down Expand Up @@ -74,7 +74,7 @@ def new_id(users: List[int]) -> int:
return new_id


def merge_same_price(df : pd.DataFrame, prec: float=5) -> pd.DataFrame:
def merge_same_price(df: pd.DataFrame, prec: float=5) -> pd.DataFrame:
"""
Process a collection of bids by merging in each
side (buying or selling) all players with the same
Expand All @@ -95,7 +95,7 @@ def merge_same_price(df : pd.DataFrame, prec: float=5) -> pd.DataFrame:
The new collection of bids where
players with the same price have
been merged into one.
final_maping : dict
Maping from new bids index to the
old bids index.
Expand Down Expand Up @@ -128,63 +128,63 @@ def merge_same_price(df : pd.DataFrame, prec: float=5) -> pd.DataFrame:
2 4.0 2.44445 6 False 0 True
>>> index
{0: [0, 1], 1: [2], 2: [3, 4]}
>>> mar = pm.Market()
>>> mar.accept_bid(250, 200, 0, True) # CleanRetail
>>> mar.accept_bid(250, 200, 0, True) # CleanRetail
0
>>> mar.accept_bid(300, 110, 1, True) # El4You
>>> mar.accept_bid(300, 110, 1, True) # El4You
1
>>> mar.accept_bid(120, 100, 2, True) # EVcharge
>>> mar.accept_bid(120, 100, 2, True) # EVcharge
2
>>> mar.accept_bid( 80, 90, 3, True) # QualiWatt
>>> mar.accept_bid( 80, 90, 3, True) # QualiWatt
3
>>> mar.accept_bid( 40, 85, 4, True) # IntelliWatt
>>> mar.accept_bid( 40, 85, 4, True) # IntelliWatt
4
>>> mar.accept_bid( 70, 75, 1, True) # El4You
>>> mar.accept_bid( 70, 75, 1, True) # El4You
5
>>> mar.accept_bid( 60, 65, 0, True) # CleanRetail
>>> mar.accept_bid( 60, 65, 0, True) # CleanRetail
6
>>> mar.accept_bid( 45, 40, 4, True) # IntelliWatt
>>> mar.accept_bid( 45, 40, 4, True) # IntelliWatt
7
>>> mar.accept_bid( 30, 38, 3, True) # QualiWatt
>>> mar.accept_bid( 30, 38, 3, True) # QualiWatt
8
>>> mar.accept_bid( 35, 31, 4, True) # IntelliWatt
>>> mar.accept_bid( 35, 31, 4, True) # IntelliWatt
9
>>> mar.accept_bid( 25, 24, 0, True) # CleanRetail
>>> mar.accept_bid( 25, 24, 0, True) # CleanRetail
10
>>> mar.accept_bid( 10, 21, 1, True) # El4You
>>> mar.accept_bid( 10, 21, 1, True) # El4You
11
>>> mar.accept_bid(120, 0, 5, False) # RT
>>> mar.accept_bid(120, 0, 5, False) # RT
12
>>> mar.accept_bid(50, 0, 6, False) # WeTrustInWind
>>> mar.accept_bid(50, 0, 6, False) # WeTrustInWind
13
>>> mar.accept_bid(200, 15, 7, False) # BlueHydro
>>> mar.accept_bid(200, 15, 7, False) # BlueHydro
14
>>> mar.accept_bid(400, 30, 5, False) # RT
>>> mar.accept_bid(400, 30, 5, False) # RT
15
>>> mar.accept_bid(60, 32.5, 8, False) # KøbenhavnCHP
>>> mar.accept_bid(60, 32.5, 8, False) # KøbenhavnCHP
16
>>> mar.accept_bid(50, 34, 8, False) # KøbenhavnCHP
>>> mar.accept_bid(50, 34, 8, False) # KøbenhavnCHP
17
>>> mar.accept_bid(60, 36, 8, False) # KøbenhavnCHP
>>> mar.accept_bid(60, 36, 8, False) # KøbenhavnCHP
18
>>> mar.accept_bid(100,37.5, 9, False) # DirtyPower
>>> mar.accept_bid(100,37.5, 9, False) # DirtyPower
19
>>> mar.accept_bid(70, 39, 9, False) # DirtyPower
>>> mar.accept_bid(70, 39, 9, False) # DirtyPower
20
>>> mar.accept_bid(50, 40, 9, False) # DirtyPower
>>> mar.accept_bid(50, 40, 9, False) # DirtyPower
21
>>> mar.accept_bid(70, 60, 5, False) # RT
>>> mar.accept_bid(70, 60, 5, False) # RT
22
>>> mar.accept_bid(45, 70, 5, False) # RT
>>> mar.accept_bid(45, 70, 5, False) # RT
23
>>> mar.accept_bid(50, 100, 10, False) # SafePeak
>>> mar.accept_bid(50, 100, 10, False) # SafePeak
24
>>> mar.accept_bid(60, 150, 10, False) # SafePeak
>>> mar.accept_bid(60, 150, 10, False) # SafePeak
25
>>> mar.accept_bid(50, 200, 10, False) # SafePeak
>>> mar.accept_bid(50, 200, 10, False) # SafePeak
26
>>> bids, index = pm.merge_same_price(mar.bm.get_df())
>>> mar.bm.get_df()
Expand Down Expand Up @@ -248,7 +248,7 @@ def merge_same_price(df : pd.DataFrame, prec: float=5) -> pd.DataFrame:
# print(df_new)
df_new.user = df_new.user.apply(id_gen)
#maping = df_new.set_index('user').bid.to_dict()
#for k, v in maping.items():
# for k, v in maping.items():
# user_to_bid[k] = v

dataframe_new.append(df_new)
Expand Down
19 changes: 11 additions & 8 deletions pymarket/datasets/uniform_bidders.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
import numpy as np

def generate(cant_buyers: int, cant_sellers: int, offset_sellers: float=0,
offset_buyers: float=0, r:np.random.RandomState = None, eps:float=1e-4):

def generate(
cant_buyers: int,
cant_sellers: int,
offset_sellers: float=0,
offset_buyers: float=0,
r: np.random.RandomState = None,
eps: float=1e-4):
"""
Generates random bids. All the volumes and reservation
prices are sampled independently from a uniform distribution.
Expand Down Expand Up @@ -42,21 +48,18 @@ def generate(cant_buyers: int, cant_sellers: int, offset_sellers: float=0,

if r is None:
r = np.random.RandomState()

offset = [offset_buyers, offset_sellers]
quantities = [cant_buyers, cant_sellers]
bids = []

user = 0
for i, (o_, q_) in enumerate(zip(offset, quantities)):
range_ = np.arange(0, 1, eps)
qs = r.choice(range_, q_, replace=False)
vs = r.choice(range_+ o_, q_, replace=False)
qs = r.choice(range_, q_, replace=False)
vs = r.choice(range_ + o_, q_, replace=False)
for j in range(q_):
bid = (qs[j], vs[j], user, bool(i), 0, True)
bids.append(bid)
user += 1
return bids



0 comments on commit cf3dced

Please sign in to comment.