INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
After optimising calculate ( and optionally print ) the performance of the optimal portfolio. Currently calculates expected return volatility and the Sharpe ratio. | def portfolio_performance(self, verbose=False, risk_free_rate=0.02):
"""
After optimising, calculate (and optionally print) the performance of the optimal
portfolio. Currently calculates expected return, volatility, and the Sharpe ratio.
:param verbose: whether performance should be pri... |
After optimising calculate ( and optionally print ) the performance of the optimal portfolio. Currently calculates expected return volatility and the Sharpe ratio. | def portfolio_performance(
expected_returns, cov_matrix, weights, verbose=False, risk_free_rate=0.02
):
"""
After optimising, calculate (and optionally print) the performance of the optimal
portfolio. Currently calculates expected return, volatility, and the Sharpe ratio.
:param expected_returns: e... |
Helper method to clean the raw weights setting any weights whose absolute values are below the cutoff to zero and rounding the rest. | def clean_weights(self, cutoff=1e-4, rounding=5):
"""
Helper method to clean the raw weights, setting any weights whose absolute
values are below the cutoff to zero, and rounding the rest.
:param cutoff: the lower bound, defaults to 1e-4
:type cutoff: float, optional
:pa... |
Private method: process input bounds into a form acceptable by scipy. optimize and check the validity of said bounds. | def _make_valid_bounds(self, test_bounds):
"""
Private method: process input bounds into a form acceptable by scipy.optimize,
and check the validity of said bounds.
:param test_bounds: minimum and maximum weight of an asset
:type test_bounds: tuple
:raises ValueError: if... |
For a long only portfolio convert the continuous weights to a discrete allocation in a greedy iterative approach. This can be thought of as a clever way to round the continuous weights to an integer number of shares | def portfolio(weights, latest_prices, min_allocation=0.01, total_portfolio_value=10000):
"""
For a long only portfolio, convert the continuous weights to a discrete allocation
in a greedy iterative approach. This can be thought of as a clever way to round
the continuous weights to an integer number of s... |
For a long only portfolio convert the continuous weights to a discrete allocation using Mixed Integer Linear Programming. This can be thought of as a clever way to round the continuous weights to an integer number of shares | def portfolio_lp(
weights, latest_prices, min_allocation=0.01, total_portfolio_value=10000
):
"""
For a long only portfolio, convert the continuous weights to a discrete allocation
using Mixed Integer Linear Programming. This can be thought of as a clever way to round
the continuous weights to an in... |
For a long only portfolio convert the continuous weights to a discrete allocation using Mixed Integer Linear Programming. This function assumes that we buy some asset based on value instead of shares and there is a limit of minimum value and increasing step. | def portfolio_byvalue(
weights, steps, min_values, max_values=1e9, total_portfolio_value=10000
):
"""
For a long only portfolio, convert the continuous weights to a discrete
allocation using Mixed Integer Linear Programming. This function assumes
that we buy some asset based on value instead of shar... |
Find the portfolio weights that minimises the CVaR via Monte Carlo sampling from the return distribution. | def min_cvar(self, s=10000, beta=0.95, random_state=None):
"""
Find the portfolio weights that minimises the CVaR, via
Monte Carlo sampling from the return distribution.
:param s: number of bootstrap draws, defaults to 10000
:type s: int, optional
:param beta: "significa... |
Calculate the annualised sample covariance matrix of ( daily ) asset returns. | def sample_cov(prices, frequency=252):
"""
Calculate the annualised sample covariance matrix of (daily) asset returns.
:param prices: adjusted closing prices of the asset, each row is a date
and each column is a ticker/id.
:type prices: pd.DataFrame
:param frequency: number of ti... |
Estimate the semicovariance matrix i. e the covariance given that the returns are less than the benchmark. | def semicovariance(prices, benchmark=0, frequency=252):
"""
Estimate the semicovariance matrix, i.e the covariance given that
the returns are less than the benchmark.
.. semicov = E([min(r_i - B, 0)] . [min(r_j - B, 0)])
:param prices: adjusted closing prices of the asset, each row is a date
... |
Calculate the exponential covariance between two timeseries of returns. | def _pair_exp_cov(X, Y, span=180):
"""
Calculate the exponential covariance between two timeseries of returns.
:param X: first time series of returns
:type X: pd.Series
:param Y: second time series of returns
:type Y: pd.Series
:param span: the span of the exponential weighting function, de... |
Estimate the exponentially - weighted covariance matrix which gives greater weight to more recent data. | def exp_cov(prices, span=180, frequency=252):
"""
Estimate the exponentially-weighted covariance matrix, which gives
greater weight to more recent data.
:param prices: adjusted closing prices of the asset, each row is a date
and each column is a ticker/id.
:type prices: pd.DataFr... |
Calculate the minimum covariance determinant an estimator of the covariance matrix that is more robust to noise. | def min_cov_determinant(prices, frequency=252, random_state=None):
"""
Calculate the minimum covariance determinant, an estimator of the covariance matrix
that is more robust to noise.
:param prices: adjusted closing prices of the asset, each row is a date
and each column is a ticker... |
Helper method which annualises the output of shrinkage calculations and formats the result into a dataframe | def format_and_annualise(self, raw_cov_array):
"""
Helper method which annualises the output of shrinkage calculations,
and formats the result into a dataframe
:param raw_cov_array: raw covariance matrix of daily returns
:type raw_cov_array: np.ndarray
:return: annualise... |
Shrink a sample covariance matrix to the identity matrix ( scaled by the average sample variance ). This method does not estimate an optimal shrinkage parameter it requires manual input. | def shrunk_covariance(self, delta=0.2):
"""
Shrink a sample covariance matrix to the identity matrix (scaled by the average
sample variance). This method does not estimate an optimal shrinkage parameter,
it requires manual input.
:param delta: shrinkage parameter, defaults to 0.... |
Calculate the Ledoit - Wolf shrinkage estimate. | def ledoit_wolf(self):
"""
Calculate the Ledoit-Wolf shrinkage estimate.
:return: shrunk sample covariance matrix
:rtype: np.ndarray
"""
X = np.nan_to_num(self.X.values)
shrunk_cov, self.delta = covariance.ledoit_wolf(X)
return self.format_and_annualise(s... |
Calculate the Oracle Approximating Shrinkage estimate | def oracle_approximating(self):
"""
Calculate the Oracle Approximating Shrinkage estimate
:return: shrunk sample covariance matrix
:rtype: np.ndarray
"""
X = np.nan_to_num(self.X.values)
shrunk_cov, self.delta = covariance.oas(X)
return self.format_and_an... |
Calculate the Constant - Correlation covariance matrix. | def shrink(self):
"""
Calculate the Constant-Correlation covariance matrix.
:return: shrunk sample covariance matrix
:rtype: np.ndarray
"""
x = np.nan_to_num(self.X.values)
# de-mean returns
t, n = np.shape(x)
meanx = x.mean(axis=0)
x = x... |
Calculate the Constant - Correlation covariance matrix. | def shrink(self):
"""
Calculate the Constant-Correlation covariance matrix.
:return: shrunk sample covariance matrix
:rtype: np.ndarray
"""
x = np.nan_to_num(self.X.values)
# de-mean returns
t, n = np.shape(x)
meanx = x.mean(axis=0)
x = x... |
Get the minimum variance solution | def min_volatility(self):
"""Get the minimum variance solution"""
if not self.w:
self.solve()
var = []
for w in self.w:
a = np.dot(np.dot(w.T, self.cov_matrix), w)
var.append(a)
# return min(var)**.5, self.w[var.index(min(var))]
self.we... |
Get the max Sharpe ratio portfolio | def max_sharpe(self):
"""Get the max Sharpe ratio portfolio"""
if not self.w:
self.solve()
# 1) Compute the local max SR portfolio between any two neighbor turning points
w_sr, sr = [], []
for i in range(len(self.w) - 1):
w0 = np.copy(self.w[i])
... |
Get the efficient frontier | def efficient_frontier(self, points):
"""Get the efficient frontier"""
mu, sigma, weights = [], [], []
# remove the 1, to avoid duplications
a = np.linspace(0, 1, points / len(self.w))[:-1]
b = list(range(len(self.w) - 1))
for i in b:
w0, w1 = self.w[i], self.... |
Emit a SocketIO event. | def emit(event, *args, **kwargs):
"""Emit a SocketIO event.
This function emits a SocketIO event to one or more connected clients. A
JSON blob can be attached to the event as payload. This is a function that
can only be called from a SocketIO event handler, as in obtains some
information from the c... |
Send a SocketIO message. | def send(message, **kwargs):
"""Send a SocketIO message.
This function sends a simple SocketIO message to one or more connected
clients. The message can be a string or a JSON blob. This is a simpler
version of ``emit()``, which should be preferred. This is a function that
can only be called from a ... |
Join a room. | def join_room(room, sid=None, namespace=None):
"""Join a room.
This function puts the user in a room, under the current namespace. The
user and the namespace are obtained from the event context. This is a
function that can only be called from a SocketIO event handler. Example::
@socketio.on('j... |
Leave a room. | def leave_room(room, sid=None, namespace=None):
"""Leave a room.
This function removes the user from a room, under the current namespace.
The user and the namespace are obtained from the event context. Example::
@socketio.on('leave')
def on_leave(data):
username = session['user... |
Close a room. | def close_room(room, namespace=None):
"""Close a room.
This function removes any users that are in the given room and then deletes
the room from the server.
:param room: The name of the room to close.
:param namespace: The namespace for the room. If not provided, the
namespac... |
Return a list of the rooms the client is in. | def rooms(sid=None, namespace=None):
"""Return a list of the rooms the client is in.
This function returns all the rooms the client has entered, including its
own room, assigned by the Socket.IO server.
:param sid: The session id of the client. If not provided, the client is
obtained f... |
Disconnect the client. | def disconnect(sid=None, namespace=None, silent=False):
"""Disconnect the client.
This function terminates the connection with the client. As a result of
this call the client will receive a disconnect event. Example::
@socketio.on('message')
def receive_message(msg):
if is_bann... |
Decorator to register a SocketIO event handler. | def on(self, message, namespace=None):
"""Decorator to register a SocketIO event handler.
This decorator must be applied to SocketIO event handlers. Example::
@socketio.on('my event', namespace='/chat')
def handle_my_custom_event(json):
print('received json: ' +... |
Decorator to define a custom error handler for SocketIO events. | def on_error(self, namespace=None):
"""Decorator to define a custom error handler for SocketIO events.
This decorator can be applied to a function that acts as an error
handler for a namespace. This handler will be invoked when a SocketIO
event handler raises an exception. The handler f... |
Decorator to define a default error handler for SocketIO events. | def on_error_default(self, exception_handler):
"""Decorator to define a default error handler for SocketIO events.
This decorator can be applied to a function that acts as a default
error handler for any namespaces that do not have a specific handler.
Example::
@socketio.on... |
Register a SocketIO event handler. | def on_event(self, message, handler, namespace=None):
"""Register a SocketIO event handler.
``on_event`` is the non-decorator version of ``'on'``.
Example::
def on_foo_event(json):
print('received json: ' + str(json))
socketio.on_event('my event', on_f... |
Emit a server generated SocketIO event. | def emit(self, event, *args, **kwargs):
"""Emit a server generated SocketIO event.
This function emits a SocketIO event to one or more connected clients.
A JSON blob can be attached to the event as payload. This function can
be used outside of a SocketIO event context, so it is appropri... |
Send a server - generated SocketIO message. | def send(self, data, json=False, namespace=None, room=None,
callback=None, include_self=True, skip_sid=None, **kwargs):
"""Send a server-generated SocketIO message.
This function sends a simple SocketIO message to one or more connected
clients. The message can be a string or a JSON... |
Run the SocketIO web server. | def run(self, app, host=None, port=None, **kwargs):
"""Run the SocketIO web server.
:param app: The Flask application instance.
:param host: The hostname or IP address for the server to listen on.
Defaults to 127.0.0.1.
:param port: The port number for the server to... |
Stop a running SocketIO web server. | def stop(self):
"""Stop a running SocketIO web server.
This method must be called from a HTTP or SocketIO handler function.
"""
if self.server.eio.async_mode == 'threading':
func = flask.request.environ.get('werkzeug.server.shutdown')
if func:
fun... |
Start a background task using the appropriate async model. | def start_background_task(self, target, *args, **kwargs):
"""Start a background task using the appropriate async model.
This is a utility function that applications can use to start a
background task using the method that is compatible with the
selected async mode.
:param targe... |
Dispatch an event to the proper handler method. | def trigger_event(self, event, *args):
"""Dispatch an event to the proper handler method.
In the most common usage, this method is not overloaded by subclasses,
as it performs the routing of events to methods. However, this
method can be overriden if special dispatching rules are needed... |
Emit a custom event to one or more connected clients. | def emit(self, event, data=None, room=None, include_self=True,
namespace=None, callback=None):
"""Emit a custom event to one or more connected clients."""
return self.socketio.emit(event, data, room=room,
include_self=include_self,
... |
Send a message to one or more connected clients. | def send(self, data, room=None, include_self=True, namespace=None,
callback=None):
"""Send a message to one or more connected clients."""
return self.socketio.send(data, room=room, include_self=include_self,
namespace=namespace or self.namespace,
... |
Close a room. | def close_room(self, room, namespace=None):
"""Close a room."""
return self.socketio.close_room(room=room,
namespace=namespace or self.namespace) |
Example of how to send server generated events to clients. | def background_thread():
"""Example of how to send server generated events to clients."""
count = 0
while True:
socketio.sleep(10)
count += 1
socketio.emit('my_response',
{'data': 'Server generated event', 'count': count},
namespace='/test'... |
Update query status and send email notification to a user | def on_failure(self, exc, task_id, args, kwargs, einfo):
"""Update query status and send email notification to a user"""
super().on_failure(exc, task_id, args, kwargs, einfo)
if isinstance(exc, OperationRunDoesNotExist):
return
self._operation_run.on_failure() |
Send email notification and a file if requested to do so by a user | def on_success(self, retval, task_id, args, kwargs):
"""Send email notification and a file, if requested to do so by a user"""
super().on_success(retval, task_id, args, kwargs)
self._operation_run.on_success() |
Record the event async. | def record_event(self, event: Event) -> None:
"""
Record the event async.
"""
from polyaxon.celery_api import celery_app
from polyaxon.settings import EventsCeleryTasks
if not event.ref_id:
event.ref_id = self.get_ref_id()
serialized_event = event.ser... |
Return event types where use acted on an object. | def user_write_events(self) -> List[str]:
"""Return event types where use acted on an object.
The write events are events with actions:
* CREATED
* UPDATED
* DELETED
* RESUMED
* COPIED
* CLONED
* STOPPED
"""
... |
Return event types where use viewed a main object. | def user_view_events(self) -> List[str]:
"""Return event types where use viewed a main object."""
return [event_type for event_type, event in self.items if event.get_event_action()
== event_actions.VIEWED] |
Validates a new email address by checking if it is already used by other users. | def validate_new_email(email):
"""Validates a "new" email address by checking if it is already used by other users."""
email = normalize_email(email)
User = get_user_model() # noqa
if User.objects.filter(email=email).exists():
raise ValidationError('The given email address is already registered... |
Pod spec to be used to create pods for project: tensorboard notebooks. | def get_project_pod_spec(volume_mounts,
volumes,
image,
command,
args,
ports,
env_vars=None,
env_from=None,
container_na... |
We memoize the access to this function in case a second call is made. | def get_object(self):
"""We memoize the access to this function in case a second call is made."""
if self._object:
return self._object
self._object = super().get_object()
if not self.AUDITOR_EVENT_TYPES:
return self._object
method = self.request.method
... |
Initializes the endpoint with the context keys based on the passed and/ or based on the query parameters ( request. GET ). | def initialize_context(self, request: HttpRequest, *args, **kwargs) -> None:
"""
Initializes the endpoint with the context keys based on the passed
and/or based on the query parameters (request.GET).
"""
for key in self.CONTEXT_KEYS:
setattr(self, key, kwargs.get(key)... |
Mount an tmpfs volume to/ dev/ shm. This will set/ dev/ shm size to half of the RAM of node. By default/ dev/ shm is very small only 64MB. Some experiments will fail due to lack of share memory such as some experiments running on Pytorch. | def get_shm_volumes():
"""
Mount an tmpfs volume to /dev/shm.
This will set /dev/shm size to half of the RAM of node.
By default, /dev/shm is very small, only 64MB.
Some experiments will fail due to lack of share memory,
such as some experiments running on Pytorch.
"""
volumes, volume_mo... |
The last constants of the job in this experiment. | def last_job_statuses(self) -> List[str]:
"""The last constants of the job in this experiment."""
statuses = []
for status in self.jobs.values_list('status__status', flat=True):
if status is not None:
statuses.append(status)
return statuses |
Return a boolean indicating if the experiment has any running jobs | def has_running_jobs(self) -> bool:
""""Return a boolean indicating if the experiment has any running jobs"""
return self.jobs.exclude(status__status__in=ExperimentLifeCycle.DONE_STATUS).exists() |
Return request s X_POLYAXON_INTERNAL: header as a bytestring. | def get_internal_header(request: HttpRequest) -> str:
"""
Return request's 'X_POLYAXON_INTERNAL:' header, as a bytestring.
"""
return get_header(request=request, header_service=conf.get('HEADERS_INTERNAL')) |
Signal handling for sidecars logs. | def logs_sidecars_experiments(experiment_name: str,
experiment_uuid: str,
job_uuid: str,
log_lines: Optional[Union[str, Iterable[str]]]) -> None:
"""Signal handling for sidecars logs."""
handle_experiment_job_log(experimen... |
Signal handling for sidecars logs. | def logs_sidecars_jobs(job_uuid: str,
job_name: str,
log_lines: Optional[Union[str, Iterable[str]]]) -> None:
"""Signal handling for sidecars logs."""
handle_job_logs(job_uuid=job_uuid,
job_name=job_name,
log_lines=log_lines)
... |
Signal handling for sidecars logs. | def logs_sidecars_builds(job_uuid: str,
job_name: str,
log_lines: Optional[Union[str, Iterable[str]]]) -> None:
"""Signal handling for sidecars logs."""
handle_build_job_logs(job_uuid=job_uuid,
job_name=job_name,
... |
One task ran ( checked ). | def is_checked(self) -> bool:
"""One task ran (checked)."""
if not self.redis_key_checked:
return False
value = self._red.get(self.redis_key_checked)
if not value:
return False
return True |
One task ran ( checked ) and one task has been delayed. | def is_delayed(self) -> bool:
"""One task ran (checked), and one task has been delayed."""
if not self.redis_key_delayed:
return False
value = self._red.get(self.redis_key_delayed)
if not value:
return False
return True |
This method connects to RabbitMQ returning the connection handle. When the connection is established the on_connection_open method will be invoked by pika. | def connect(self):
"""This method connects to RabbitMQ, returning the connection handle.
When the connection is established, the on_connection_open method
will be invoked by pika.
:rtype: pika.SelectConnection
"""
_logger.info('Connecting to %s', self.AMQP_URL)
w... |
This method is invoked by pika when the channel has been opened. The channel object is passed in so we can make use of it. | def on_channel_open(self, channel):
"""This method is invoked by pika when the channel has been opened.
The channel object is passed in so we can make use of it.
Since the channel is now open, we'll declare the exchange to use.
:param pika.channel.Channel channel: The channel object
... |
Setup the exchange on RabbitMQ by invoking the Exchange. Declare RPC command. When it is complete the on_exchange_declareok method will be invoked by pika. | def setup_exchange(self, exchange_name):
"""Setup the exchange on RabbitMQ by invoking the Exchange.Declare RPC
command. When it is complete, the on_exchange_declareok method will
be invoked by pika.
:param str|unicode exchange_name: The name of the exchange to declare
"""
... |
Setup the queue on RabbitMQ by invoking the Queue. Declare RPC command. When it is complete the on_queue_declareok method will be invoked by pika. | def setup_queue(self, queue_name):
"""Setup the queue on RabbitMQ by invoking the Queue.Declare RPC
command. When it is complete, the on_queue_declareok method will
be invoked by pika.
:param str|unicode queue_name: The name of the queue to declare.
"""
_logger.debug('De... |
Method invoked by pika when the Queue. Declare RPC call made in setup_queue has completed. In this method we will bind the queue and exchange together with the routing key by issuing the Queue. Bind RPC command. When this command is complete the on_bindok method will be invoked by pika. | def on_queue_declareok(self, method_frame):
"""Method invoked by pika when the Queue.Declare RPC call made in
setup_queue has completed. In this method we will bind the queue
and exchange together with the routing key by issuing the Queue.Bind
RPC command. When this command is complete, ... |
Invoked by pika when RabbitMQ sends a Basic. Cancel for a consumer receiving messages. | def on_consumer_cancelled(self, method_frame):
"""Invoked by pika when RabbitMQ sends a Basic.Cancel for a consumer
receiving messages.
:param pika.frame.Method method_frame: The Basic.Cancel frame
"""
_logger.info('Consumer was cancelled remotely, shutting down: %r', method_fra... |
Acknowledge the message delivery from RabbitMQ by sending a Basic. Ack RPC method for the delivery tag. | def acknowledge_message(self, delivery_tag):
"""Acknowledge the message delivery from RabbitMQ by sending a
Basic.Ack RPC method for the delivery tag.
:param int delivery_tag: The delivery tag from the Basic.Deliver frame
"""
_logger.debug('Acknowledging message %s', delivery_ta... |
Invoked by pika when a message is delivered from RabbitMQ. The channel is passed for your convenience. The basic_deliver object that is passed in carries the exchange routing key delivery tag and a redelivered flag for the message. The properties passed in is an instance of BasicProperties with the message properties a... | def on_message(self, unused_channel, basic_deliver, properties, body):
"""Invoked by pika when a message is delivered from RabbitMQ. The
channel is passed for your convenience. The basic_deliver object that
is passed in carries the exchange, routing key, delivery tag and
a redelivered fl... |
Tell RabbitMQ that you would like to stop consuming by sending the Basic. Cancel RPC command. | def stop_consuming(self):
"""Tell RabbitMQ that you would like to stop consuming by sending the
Basic.Cancel RPC command.
"""
if self._channel:
_logger.debug('Sending a Basic.Cancel RPC command to RabbitMQ')
self._channel.basic_cancel(self.on_cancelok, self._consu... |
Open a new channel with RabbitMQ by issuing the Channel. Open RPC command. When RabbitMQ responds that the channel is open the on_channel_open callback will be invoked by pika. | def open_channel(self):
"""Open a new channel with RabbitMQ by issuing the Channel.Open RPC
command. When RabbitMQ responds that the channel is open, the
on_channel_open callback will be invoked by pika.
"""
_logger.info('Creating a new channel')
self._connection.channel(... |
Run the example consumer by connecting to RabbitMQ and then starting the IOLoop to block and allow the SelectConnection to operate. | def run(self):
"""Run the example consumer by connecting to RabbitMQ and then
starting the IOLoop to block and allow the SelectConnection to operate.
"""
self._connection = self.connect()
self._connection.ioloop.start() |
Cleanly shutdown the connection to RabbitMQ by stopping the consumer with RabbitMQ. When RabbitMQ confirms the cancellation on_cancelok will be invoked by pika which will then closing the channel and connection. The IOLoop is started again because this method is invoked when CTRL - C is pressed raising a KeyboardInterr... | def stop(self):
"""Cleanly shutdown the connection to RabbitMQ by stopping the consumer
with RabbitMQ. When RabbitMQ confirms the cancellation, on_cancelok
will be invoked by pika, which will then closing the channel and
connection. The IOLoop is started again because this method is invo... |
Renders both the subject and body templates in the given context. Returns a tuple ( subject body ) of the result. | def render_mail_template(subject_template, body_template, context):
"""
Renders both the subject and body templates in the given context.
Returns a tuple (subject, body) of the result.
"""
try:
subject = strip_spaces(render_to_string(subject_template, context))
body = render_to_strin... |
Renders an email subject and body using the given templates and context then sends it to the given recipients list. | def send_mass_template_mail(subject_template, body_template, recipients, context=None):
"""
Renders an email subject and body using the given templates and context,
then sends it to the given recipients list.
The emails are send one-by-one.
"""
if context:
subject, body = render_mail_te... |
Similar to send_mass_template_mail this function renders the given templates into email subjects and bodies. | def send_mass_user_template_mail(subject_template, body_template, users, context):
"""
Similar to `send_mass_template_mail` this function renders the given templates
into email subjects and bodies.
The emails are send one-by-one.
"""
message_tuples = []
for user in users:
context['u... |
Checkout to a specific commit. | def checkout_commit(repo_path: str,
commit: Any = None) -> None: # pylint:disable=redefined-outer-name
"""Checkout to a specific commit.
If commit is None then checkout to master.
"""
commit = commit or 'master'
run_command(cmd='git checkout {}'.format(commit), data=None, locat... |
Create a tar file based on the list of files passed | def create_tarfile(files: List[str], tar_path: str) -> None:
"""Create a tar file based on the list of files passed"""
with tarfile.open(tar_path, "w:gz") as tar:
for f in files:
tar.add(f) |
Open and close the broker channel. | def check() -> Result:
"""Open and close the broker channel."""
try:
# Context to release connection
with Connection(conf.get('CELERY_BROKER_URL')) as conn:
conn.connect()
except ConnectionRefusedError:
return Result(message='Service unable to ... |
Return a list of suggestions based on grid search. | def get_suggestions(self, iteration_config=None):
"""Return a list of suggestions based on grid search.
Params:
matrix: `dict` representing the {hyperparam: hyperparam matrix config}.
n_suggestions: number of suggestions to make.
"""
matrix = self.hptuning_config... |
Find argmax of the acquisition function. | def _maximize(self):
""" Find argmax of the acquisition function."""
if not self.space.is_observations_valid():
return None
y_max = self.space.y.max()
self.utility_function.gaussian_process.fit(self.space.x, self.space.y)
return self.utility_function.max_compute(y_max... |
Construct the DAG of this pipeline based on the its operations and their downstream. | def dag(self) -> Tuple[Dict, Dict]:
"""Construct the DAG of this pipeline based on the its operations and their downstream."""
from pipelines import dags
operations = self.operations.all().prefetch_related('downstream_operations')
def get_downstream(op):
return op.downstrea... |
Calculate the countdown for a celery task retry. | def get_countdown(self, retries) -> int:
"""Calculate the countdown for a celery task retry."""
retry_delay = self.retry_delay
if self.retry_exponential_backoff:
return min(
max(2 ** retries, retry_delay), # Exp. backoff
self.max_retry_delay # The co... |
Return the params to run the celery task. | def get_run_params(self) -> Dict:
"""Return the params to run the celery task."""
params = {}
if self.celery_queue:
params['queue'] = self.celery_queue
if self.timeout:
params['soft_time_limit'] = self.timeout
# We set also a hard time limit that will... |
Update the status of the current instance. | def can_transition(self, status_from: str, status_to: str) -> bool:
"""Update the status of the current instance.
Returns:
boolean: if the instance is updated.
"""
if not self.STATUSES.can_transition(status_from=status_from, status_to=status_to):
_logger.info(
... |
Construct the DAG of this pipeline run based on the its operation runs and their downstream. | def dag(self) -> Tuple[Dict, Dict]:
"""Construct the DAG of this pipeline run
based on the its operation runs and their downstream.
"""
from pipelines import dags
operation_runs = self.operation_runs.all().prefetch_related('downstream_runs')
def get_downstream(op_run):
... |
Checks the concurrency of the operation run. | def check_concurrency(self) -> bool:
"""Checks the concurrency of the operation run.
Checks the concurrency of the operation run
to validate if we can start a new operation run.
Returns:
boolean: Whether to start a new operation run or not.
"""
if not self.o... |
Checks the upstream and the trigger rule. | def check_upstream_trigger(self) -> bool:
"""Checks the upstream and the trigger rule."""
if self.operation.trigger_policy == TriggerPolicy.ONE_DONE:
return self.upstream_runs.filter(
status__status__in=self.STATUSES.DONE_STATUS).exists()
if self.operation.trigger_pol... |
Schedule the task: check first if the task can start: 1. we check that the task is still in the CREATED state. 2. we check that the upstream dependency is met. 3. we check that pipeline can start a new task ; i. e. we check the concurrency of the pipeline. 4. we check that operation can start a new instance ; i. e. we ... | def schedule_start(self) -> bool:
"""Schedule the task: check first if the task can start:
1. we check that the task is still in the CREATED state.
2. we check that the upstream dependency is met.
3. we check that pipeline can start a new task;
i.e. we check the... |
Start the celery task of this operation. | def start(self) -> None:
"""Start the celery task of this operation."""
kwargs = self.celery_task_context
# Update we the operation run id
kwargs['operation_run_id'] = self.id # pylint:disable=unsupported-assignment-operation
async_result = celery_app.send_task(
sel... |
Return the image name and image tag for an experiment | def get_experiment_image_info(experiment: 'Experiment') -> Tuple[str, str]:
"""Return the image name and image tag for an experiment"""
project_name = experiment.project.name
repo_name = project_name
image_name = '{}/{}'.format(conf.get('REGISTRY_URI'), repo_name)
image_tag = experiment.code_refere... |
Return the image name and image tag for a job | def get_job_image_info(project: 'Project', job: Any) -> Tuple[str, str]:
"""Return the image name and image tag for a job"""
project_name = project.name
repo_name = project_name
image_name = '{}/{}'.format(conf.get('REGISTRY_URI'), repo_name)
try:
last_commit = project.repo.last_commit
... |
Return the image name and image tag for a job | def get_notebook_image_info(project: 'Project', job: Any) -> Tuple[str, str]:
"""Return the image name and image tag for a job"""
image_name, _ = get_job_image_info(project, job)
return image_name, LATEST_IMAGE_TAG |
Create an iteration for the experiment group. | def create_iteration(self, num_suggestions):
"""Create an iteration for the experiment group."""
from db.models.experiment_groups import ExperimentGroupIteration
iteration_config = self.experiment_group.iteration_config
if iteration_config is None:
iteration = 0
... |
Update the last experiment group s iteration with experiment performance. | def update_iteration(self):
"""Update the last experiment group's iteration with experiment performance."""
iteration_config = self.get_iteration_config()
if not iteration_config:
return
experiments_metrics = self.experiment_group.get_experiments_metrics(
experime... |
Return the number of configs to keep and resume. | def get_n_config_to_keep(self, n_suggestions, bracket_iteration):
"""Return the number of configs to keep and resume."""
n_configs = n_suggestions * (self.eta ** -bracket_iteration)
return int(n_configs / self.eta) |
Return the number of configs to keep for an iteration and iteration bracket. | def get_n_config_to_keep_for_iteration(self, iteration, bracket_iteration):
"""Return the number of configs to keep for an iteration and iteration bracket.
This is just util function around `get_n_config_to_keep`
"""
bracket = self.get_bracket(iteration=iteration)
if bracket_ite... |
Return the number of iterations to run for this barcket_i | def get_n_resources_for_iteration(self, iteration, bracket_iteration):
"""Return the number of iterations to run for this barcket_i
This is just util function around `get_n_resources`
"""
bracket = self.get_bracket(iteration=iteration)
n_resources = self.get_resources(bracket=br... |
Return a list of suggestions/ arms based on hyperband. | def get_suggestions(self, iteration_config=None):
"""Return a list of suggestions/arms based on hyperband."""
if not iteration_config or not isinstance(iteration_config, HyperbandIterationConfig):
raise ValueError('Hyperband get suggestions requires an iteration.')
bracket = self.get... |
Return a boolean to indicate if we need to reschedule another iteration. | def should_reschedule(self, iteration, bracket_iteration):
"""Return a boolean to indicate if we need to reschedule another iteration."""
bracket = self.get_bracket(iteration=iteration)
if bracket_iteration < bracket:
# The bracket is still processing
return False
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.