-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathace_extensions.py
More file actions
219 lines (155 loc) · 5.77 KB
/
ace_extensions.py
File metadata and controls
219 lines (155 loc) · 5.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
import os
import pickle
import time
from functools import partial
from multiprocessing.pool import ThreadPool
import pandas as pd
import tqdm
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
import ace_lib as ace
def get_stored_session(duration=1800):
brain_session = ace.SingleSession()
retry_strategy = Retry(
total=5,
backoff_factor=1,
status_forcelist=[429, 500, 502, 503, 504],
allowed_methods=["HEAD", "GET", "OPTIONS", "POST"],
)
adapter = HTTPAdapter(max_retries=retry_strategy)
brain_session.mount("https://", adapter)
brain_session.mount("http://", adapter)
if os.path.exists("session.pkl"):
try:
with open("session.pkl", "rb") as f:
session_data = pickle.load(f)
brain_session.cookies.update(session_data["cookies"])
brain_session.headers.update(session_data["headers"])
print("Loaded stored session from disk.")
except Exception as e:
print(f"Failed to load session: {e}")
time_to_live = ace.check_session_timeout(brain_session)
if time_to_live >= duration:
print(f"Session is valid. Expires in {time_to_live} seconds.")
return brain_session
print("Session expired or missing. Logging in...")
brain_session = ace.start_session()
with open("session.pkl", "wb") as f:
pickle.dump(
{"cookies": brain_session.cookies, "headers": brain_session.headers}, f
)
print("New session saved to disk.")
return brain_session
def disable_progress_bar():
class _DummyTqdm:
def __init__(self, *args, **kwargs):
self.total = kwargs.get("total", None)
def __enter__(self):
return self
def __exit__(self, *exc):
return False
def update(self, n=1):
pass
def set_description(self, *a, **kw):
pass
def close(self):
pass
def __iter__(self):
return iter(())
def __len__(self):
return 0
ace.tqdm.tqdm = _DummyTqdm
def get_power_pool_corr(s: ace.SingleSession, alpha_id: str) -> pd.DataFrame:
"""
Retrieve the power pool correlation data for a specific alpha.
Args:
s (SingleSession): An authenticated session object.
alpha_id (str): The ID of the alpha.
Returns:
pandas.DataFrame: A DataFrame containing the power pool correlation data.
Raises:
requests.exceptions.RequestException: If there's an error in the API request.
"""
while True:
result = s.get(
ace.brain_api_url + "/alphas/" + alpha_id + "/correlations/power-pool"
)
if "retry-after" in result.headers:
time.sleep(float(result.headers["Retry-After"]))
else:
break
if result.json().get("records", 0) == 0:
ace.logger.warning(
f"Failed to get power pool correlation for alpha_id {alpha_id}. {result.json()}"
)
return pd.DataFrame()
columns = [dct["name"] for dct in result.json()["schema"]["properties"]]
power_pool_corr_df = pd.DataFrame(result.json()["records"], columns=columns).assign(
alpha_id=alpha_id
)
power_pool_corr_df["alpha_max_power_pool_corr"] = result.json()["max"]
power_pool_corr_df["alpha_min_power_pool_corr"] = result.json()["min"]
return power_pool_corr_df
def create_tag_list(s: ace.SingleSession, name: str, alpha_ids: list[str]) -> dict:
response = s.post(
ace.brain_api_url + "/tags",
json={"type": "LIST", "name": name, "alphas": alpha_ids},
)
if response.status_code not in (200, 201):
ace.logger.warning(
f"Failed to create tag list '{name}'. "
f"Status code: {response.status_code}, Response: {response.text}"
)
return {}
return response.json()
def get_datafield(s: ace.SingleSession, datafield: str):
"""
Retrieve Data Field.
Args:
s (SingleSession): An authenticated session object.
data_field (str): Name of Data Field
Returns:
JSON: A JSON Object containing information about the Data Field.
"""
resp = s.get(ace.brain_api_url + "/data-fields/" + datafield)
resp_json = resp.json()
return resp_json
def simulate_single_alpha(
brain_session: ace.SingleSession,
alpha: dict,
) -> dict:
brain_session = ace.check_session_and_relogin(brain_session)
simulation_response = ace.start_simulation(brain_session, alpha)
simulation_result = ace.simulation_progress(brain_session, simulation_response)
if not simulation_result["completed"]:
return ""
return simulation_result["result"]
def simulate_alpha_list(
brain_session: ace.SingleSession,
alpha_list: list,
limit_of_concurrent_simulations: int = 5,
) -> list:
if (limit_of_concurrent_simulations < 1) or (limit_of_concurrent_simulations > 8):
limit_of_concurrent_simulations = 5
result_list = []
with ThreadPool(limit_of_concurrent_simulations) as pool:
with tqdm.tqdm(total=len(alpha_list)) as pbar:
for result in pool.imap_unordered(
partial(simulate_single_alpha, brain_session), alpha_list
):
result_list.append(result)
pbar.update()
return result_list
def get_alpha_recordset(
brain_session: ace.SingleSession, alpha_id: str, recordset_type: str
):
while True:
result = brain_session.get(
ace.brain_api_url + "/alphas/" + alpha_id + f"/recordsets/{recordset_type}"
)
if "retry-after" in result.headers:
time.sleep(float(result.headers["Retry-After"]))
else:
break
recordset = result.json()
return recordset["records"]